blob: 56e1eac9adce606b195557a7ff031975a56fdda2 [file] [log] [blame]
jeffhaoe343b762011-12-05 16:36:44 -08001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#include "trace.h"
4
jeffhaoa9ef3fd2011-12-13 18:33:43 -08005#include <sys/uio.h>
6
jeffhaoe343b762011-12-05 16:36:44 -08007#include "class_linker.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -08008#include "debugger.h"
jeffhaoe343b762011-12-05 16:36:44 -08009#include "dex_cache.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080010#include "object_utils.h"
11#include "os.h"
jeffhaoe343b762011-12-05 16:36:44 -080012#include "runtime_support.h"
13#include "thread.h"
14
jeffhaoa9ef3fd2011-12-13 18:33:43 -080015static const uint32_t kTraceMethodActionMask = 0x03; // two bits
16static const char kTraceTokenChar = '*';
17static const uint16_t kTraceHeaderLength = 32;
18static const uint32_t kTraceMagicValue = 0x574f4c53;
19static const uint16_t kTraceVersionSingleClock = 2;
20static const uint16_t kTraceVersionDualClock = 3;
21static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
22static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
23
24static inline uint32_t TraceMethodId(uint32_t methodValue) {
25 return (methodValue & ~kTraceMethodActionMask);
26}
27static inline uint32_t TraceMethodCombine(uint32_t method, uint8_t traceEvent) {
28 return (method | traceEvent);
29}
30
jeffhaoe343b762011-12-05 16:36:44 -080031namespace art {
32
jeffhaoa9ef3fd2011-12-13 18:33:43 -080033// TODO: Replace class statics with singleton instance
34bool Trace::method_tracing_active_ = false;
35std::map<const Method*, const void*> Trace::saved_code_map_;
36std::set<const Method*> Trace::visited_methods_;
37std::map<Thread*, uint64_t> Trace::thread_clock_base_map_;
38uint8_t* Trace::buf_;
39File* Trace::trace_file_;
40bool Trace::direct_to_ddms_ = false;
41int Trace::buffer_size_ = 0;
42uint64_t Trace::start_time_ = 0;
43bool Trace::overflow_ = false;
44uint16_t Trace::trace_version_;
45uint16_t Trace::record_size_;
46volatile int32_t Trace::cur_offset_;
47
48bool UseThreadCpuClock() {
49 // TODO: Allow control over which clock is used
50 return true;
51}
52
53bool UseWallClock() {
54 // TODO: Allow control over which clock is used
55 return true;
56}
57
58void MeasureClockOverhead() {
59 if (UseThreadCpuClock()) {
60 ThreadCpuMicroTime();
61 }
62 if (UseWallClock()) {
63 MicroTime();
64 }
65}
66
67uint32_t GetClockOverhead() {
68 uint64_t start = ThreadCpuMicroTime();
69
70 for (int i = 4000; i > 0; i--) {
71 MeasureClockOverhead();
72 MeasureClockOverhead();
73 MeasureClockOverhead();
74 MeasureClockOverhead();
75 MeasureClockOverhead();
76 MeasureClockOverhead();
77 MeasureClockOverhead();
78 MeasureClockOverhead();
79 }
80
81 uint64_t elapsed = ThreadCpuMicroTime() - start;
82 return uint32_t (elapsed / 32);
83}
84
85void Append2LE(uint8_t* buf, uint16_t val) {
86 *buf++ = (uint8_t) val;
87 *buf++ = (uint8_t) (val >> 8);
88}
89
90void Append4LE(uint8_t* buf, uint32_t val) {
91 *buf++ = (uint8_t) val;
92 *buf++ = (uint8_t) (val >> 8);
93 *buf++ = (uint8_t) (val >> 16);
94 *buf++ = (uint8_t) (val >> 24);
95}
96
97void Append8LE(uint8_t* buf, uint64_t val) {
98 *buf++ = (uint8_t) val;
99 *buf++ = (uint8_t) (val >> 8);
100 *buf++ = (uint8_t) (val >> 16);
101 *buf++ = (uint8_t) (val >> 24);
102 *buf++ = (uint8_t) (val >> 32);
103 *buf++ = (uint8_t) (val >> 40);
104 *buf++ = (uint8_t) (val >> 48);
105 *buf++ = (uint8_t) (val >> 56);
106}
107
jeffhaoe343b762011-12-05 16:36:44 -0800108#if defined(__arm__)
109static bool InstallStubsClassVisitor(Class* klass, void* trace_stub) {
110 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
111 Method* method = klass->GetDirectMethod(i);
112 if (method->GetCode() != trace_stub) {
113 Trace::SaveAndUpdateCode(method, trace_stub);
114 }
115 }
116
117 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
118 Method* method = klass->GetVirtualMethod(i);
119 if (method->GetCode() != trace_stub) {
120 Trace::SaveAndUpdateCode(method, trace_stub);
121 }
122 }
123
124 if (!klass->IsArrayClass() && !klass->IsPrimitive()) {
125 CodeAndDirectMethods* c_and_dm = klass->GetDexCache()->GetCodeAndDirectMethods();
126 for (size_t i = 0; i < c_and_dm->NumCodeAndDirectMethods(); i++) {
127 Method* method = c_and_dm->GetResolvedMethod(i);
128 if (method != NULL && (size_t) method != i) {
129 c_and_dm->SetResolvedDirectMethodTraceEntry(i, trace_stub);
130 }
131 }
132 }
133 return true;
134}
135
136static bool UninstallStubsClassVisitor(Class* klass, void* trace_stub) {
137 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
138 Method* method = klass->GetDirectMethod(i);
139 if (Trace::GetSavedCodeFromMap(method) != NULL) {
140 Trace::ResetSavedCode(method);
141 }
142 }
143
144 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
145 Method* method = klass->GetVirtualMethod(i);
146 if (Trace::GetSavedCodeFromMap(method) != NULL) {
147 Trace::ResetSavedCode(method);
148 }
149 }
150
151 if (!klass->IsArrayClass() && !klass->IsPrimitive()) {
152 CodeAndDirectMethods* c_and_dm = klass->GetDexCache()->GetCodeAndDirectMethods();
153 for (size_t i = 0; i < c_and_dm->NumCodeAndDirectMethods(); i++) {
154 const void* code = c_and_dm->GetResolvedCode(i);
155 if (code == trace_stub) {
156 Method* method = klass->GetDexCache()->GetResolvedMethod(i);
157 if (Trace::GetSavedCodeFromMap(method) != NULL) {
158 Trace::ResetSavedCode(method);
159 }
160 c_and_dm->SetResolvedDirectMethod(i, method);
161 }
162 }
163 }
164 return true;
165}
166
167static void TraceRestoreStack(Thread* t, void*) {
168 uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
169
170 Frame frame = t->GetTopOfStack();
171 if (frame.GetSP() != 0) {
172 for ( ; frame.GetMethod() != 0; frame.Next()) {
173 if (t->IsTraceStackEmpty()) {
174 break;
175 }
176 uintptr_t pc = frame.GetReturnPC();
177 Method* method = frame.GetMethod();
178 if (trace_exit == pc) {
179 TraceStackFrame trace_frame = t->PopTraceStackFrame();
180 frame.SetReturnPC(trace_frame.return_pc_);
181 CHECK(method == trace_frame.method_);
182 }
183 }
184 }
185}
186#endif
187
jeffhaoe343b762011-12-05 16:36:44 -0800188void Trace::AddSavedCodeToMap(const Method* method, const void* code) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800189 CHECK(IsMethodTracingActive());
jeffhaoe343b762011-12-05 16:36:44 -0800190 saved_code_map_.insert(std::make_pair(method, code));
191}
192
193void Trace::RemoveSavedCodeFromMap(const Method* method) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800194 CHECK(IsMethodTracingActive());
jeffhaoe343b762011-12-05 16:36:44 -0800195 saved_code_map_.erase(method);
196}
197
198const void* Trace::GetSavedCodeFromMap(const Method* method) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800199 CHECK(IsMethodTracingActive());
jeffhaoe343b762011-12-05 16:36:44 -0800200 return saved_code_map_.find(method)->second;
201}
202
203void Trace::SaveAndUpdateCode(Method* method, const void* new_code) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800204 CHECK(IsMethodTracingActive());
jeffhaoe343b762011-12-05 16:36:44 -0800205 CHECK(GetSavedCodeFromMap(method) == NULL);
206 AddSavedCodeToMap(method, method->GetCode());
207 method->SetCode(new_code);
208}
209
210void Trace::ResetSavedCode(Method* method) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800211 CHECK(IsMethodTracingActive());
jeffhaoe343b762011-12-05 16:36:44 -0800212 CHECK(GetSavedCodeFromMap(method) != NULL);
213 method->SetCode(GetSavedCodeFromMap(method));
214 RemoveSavedCodeFromMap(method);
215}
216
217bool Trace::IsMethodTracingActive() {
218 return method_tracing_active_;
219}
220
221void Trace::SetMethodTracingActive(bool value) {
222 method_tracing_active_ = value;
223}
224
225void Trace::Start(const char* trace_filename, int trace_fd, int buffer_size, int flags, bool direct_to_ddms) {
226 LOG(INFO) << "Starting method tracing...";
227 if (IsMethodTracingActive()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800228 // TODO: Stop the trace, then start it up again instead of returning.
229 LOG(INFO) << "Trace already in progress, ignoring this request";
jeffhaoe343b762011-12-05 16:36:44 -0800230 return;
231 }
232
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800233 // Suspend all threads.
234 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
235 Runtime::Current()->GetThreadList()->SuspendAll(false);
236
237 // Open files and allocate storage.
238 if (!direct_to_ddms) {
239 if (trace_fd < 0) {
240 trace_file_ = OS::OpenFile(trace_filename, true);
241 } else {
242 trace_file_ = OS::FileFromFd("tracefile", trace_fd);
243 }
244 if (trace_file_ == NULL) {
245 PLOG(ERROR) << "Unable to open trace file '" << trace_filename;
246 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
247 StringPrintf("Unable to open trace file '%s'", trace_filename).c_str());
248 Runtime::Current()->GetThreadList()->ResumeAll(false);
249 return;
250 }
251 }
252 buf_ = new uint8_t[buffer_size]();
253
254 // Populate profiler state.
255 direct_to_ddms_ = direct_to_ddms;
256 buffer_size_ = buffer_size;
257 overflow_ = false;
258 start_time_ = MicroTime();
259
260 if (UseThreadCpuClock() && UseWallClock()) {
261 trace_version_ = kTraceVersionDualClock;
262 record_size_ = kTraceRecordSizeDualClock;
263 } else {
264 trace_version_ = kTraceVersionSingleClock;
265 record_size_ = kTraceRecordSizeSingleClock;
266 }
267
268 saved_code_map_.clear();
269 visited_methods_.clear();
270 thread_clock_base_map_.clear();
271
272 // Set up the beginning of the trace.
273 memset(buf_, 0, kTraceHeaderLength);
274 Append4LE(buf_, kTraceMagicValue);
275 Append2LE(buf_ + 4, trace_version_);
276 Append2LE(buf_ + 6, kTraceHeaderLength);
277 Append8LE(buf_ + 8, start_time_);
278 if (trace_version_ >= kTraceVersionDualClock) {
279 Append2LE(buf_ + 16, record_size_);
280 }
281 cur_offset_ = kTraceHeaderLength;
282
jeffhaoe343b762011-12-05 16:36:44 -0800283 SetMethodTracingActive(true);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800284
285 // Install all method tracing stubs.
jeffhaoe343b762011-12-05 16:36:44 -0800286 InstallStubs();
287 LOG(INFO) << "Method tracing started";
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800288
289 Runtime::Current()->GetThreadList()->ResumeAll(false);
jeffhaoe343b762011-12-05 16:36:44 -0800290}
291
292void Trace::Stop() {
293 LOG(INFO) << "Stopping method tracing...";
294 if (!IsMethodTracingActive()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800295 LOG(INFO) << "Trace stop requested, but no trace currently running";
jeffhaoe343b762011-12-05 16:36:44 -0800296 return;
297 }
298
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800299 // Suspend all threads.
300 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
301 Runtime::Current()->GetThreadList()->SuspendAll(false);
302
303 // Uninstall all method tracing stubs.
jeffhaoe343b762011-12-05 16:36:44 -0800304 UninstallStubs();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800305
jeffhaoe343b762011-12-05 16:36:44 -0800306 SetMethodTracingActive(false);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800307
308 // Compute elapsed time.
309 uint64_t elapsed = MicroTime() - start_time_;
310
311 size_t final_offset = cur_offset_;
312 uint32_t clock_overhead = GetClockOverhead();
313
314 GetVisitedMethods(final_offset);
315
316 std::ostringstream os;
317
318 os << StringPrintf("%cversion\n", kTraceTokenChar);
319 os << StringPrintf("%d\n", trace_version_);
320 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
321 if (UseThreadCpuClock()) {
322 if (UseWallClock()) {
323 os << StringPrintf("clock=dual\n");
324 } else {
325 os << StringPrintf("clock=thread-cpu\n");
326 }
327 } else {
328 os << StringPrintf("clock=wall\n");
329 }
330 os << StringPrintf("elapsed-time-usec=%llu\n", elapsed);
331 os << StringPrintf("num-method-calls=%d\n", (final_offset - kTraceHeaderLength) / record_size_);
332 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead);
333 os << StringPrintf("vm=art\n");
334 os << StringPrintf("%cthreads\n", kTraceTokenChar);
335 DumpThreadList(os);
336 os << StringPrintf("%cmethods\n", kTraceTokenChar);
337 DumpMethodList(os);
338 os << StringPrintf("%cend\n", kTraceTokenChar);
339
340 std::string header(os.str());
341 if (direct_to_ddms_) {
342 struct iovec iov[2];
343 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
344 iov[0].iov_len = header.length();
345 iov[1].iov_base = buf_;
346 iov[1].iov_len = final_offset;
347 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
348 } else {
349 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
350 !trace_file_->WriteFully(buf_, final_offset)) {
351 int err = errno;
352 LOG(ERROR) << "Trace data write failed: " << strerror(err);
353 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
354 StringPrintf("Trace data write failed: %s", strerror(err)).c_str());
355 }
356 delete trace_file_;
357 }
358
359 delete buf_;
360
jeffhaoe343b762011-12-05 16:36:44 -0800361 LOG(INFO) << "Method tracing stopped";
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800362
363 Runtime::Current()->GetThreadList()->ResumeAll(false);
364}
365
366void Trace::LogMethodTraceEvent(Thread* self, const Method* method, Trace::TraceEvent event) {
367 if (thread_clock_base_map_.find(self) == thread_clock_base_map_.end()) {
368 uint64_t time = ThreadCpuMicroTime();
369 thread_clock_base_map_.insert(std::make_pair(self, time));
370 }
371
372 // Advance cur_offset_ atomically.
373 int32_t new_offset;
374 int32_t old_offset;
375 do {
376 old_offset = cur_offset_;
377 new_offset = old_offset + record_size_;
378 if (new_offset > buffer_size_) {
379 overflow_ = true;
380 return;
381 }
382 } while (android_atomic_release_cas(old_offset, new_offset, &cur_offset_) != 0);
383
384 uint32_t method_value = TraceMethodCombine(reinterpret_cast<uint32_t>(method), event);
385
386 // Write data
387 uint8_t* ptr = buf_ + old_offset;
388 Append2LE(ptr, self->GetTid());
389 Append4LE(ptr + 2, method_value);
390 ptr += 6;
391
392 if (UseThreadCpuClock()) {
393 uint64_t thread_clock_base = thread_clock_base_map_.find(self)->second;
394 uint32_t thread_clock_diff = ThreadCpuMicroTime() - thread_clock_base;
395 Append4LE(ptr, thread_clock_diff);
396 ptr += 4;
397 }
398
399 if (UseWallClock()) {
400 uint32_t wall_clock_diff = MicroTime() - start_time_;
401 Append4LE(ptr, wall_clock_diff);
402 }
403}
404
405void Trace::GetVisitedMethods(size_t end_offset) {
406 uint8_t* ptr = buf_ + kTraceHeaderLength;
407 uint8_t* end = buf_ + end_offset;
408
409 while (ptr < end) {
410 uint32_t method_value = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
411 Method* method = reinterpret_cast<Method*>(TraceMethodId(method_value));
412 visited_methods_.insert(method);
413 ptr += record_size_;
414 }
415}
416
417void Trace::DumpMethodList(std::ostream& os) {
418 typedef std::set<const Method*>::const_iterator It; // TODO: C++0x auto
419 for (It it = visited_methods_.begin(); it != visited_methods_.end(); ++it) {
420 const Method* method = *it;
421 MethodHelper mh(method);
422 os << StringPrintf("0x%08x\t%s\t%s\t%s\t%s\t%d\n", (int) method,
423 PrettyDescriptor(mh.GetDeclaringClassDescriptor()).c_str(), mh.GetName(),
424 mh.GetSignature().c_str(), mh.GetDeclaringClassSourceFile(),
425 mh.GetLineNumFromNativePC(0));
426 }
427 visited_methods_.clear();
428}
429
430static void DumpThread(Thread* t, void* arg) {
431 std::ostream* os = reinterpret_cast<std::ostream*>(arg);
432 *os << StringPrintf("%d\t%s\n", t->GetTid(), t->GetName()->ToModifiedUtf8().c_str());
433}
434
435void Trace::DumpThreadList(std::ostream& os) {
436 ScopedThreadListLock thread_list_lock;
437 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -0800438}
439
440void Trace::InstallStubs() {
441#if defined(__arm__)
jeffhaoe343b762011-12-05 16:36:44 -0800442 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
443 Runtime::Current()->GetClassLinker()->VisitClasses(InstallStubsClassVisitor, trace_stub);
jeffhaoe343b762011-12-05 16:36:44 -0800444#else
445 UNIMPLEMENTED(WARNING);
446#endif
447}
448
449void Trace::UninstallStubs() {
450#if defined(__arm__)
jeffhaoe343b762011-12-05 16:36:44 -0800451 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
452 Runtime::Current()->GetClassLinker()->VisitClasses(UninstallStubsClassVisitor, trace_stub);
453
454 // Restore stacks of all threads
455 {
456 ScopedThreadListLock thread_list_lock;
457 Runtime::Current()->GetThreadList()->ForEach(TraceRestoreStack, NULL);
458 }
jeffhaoe343b762011-12-05 16:36:44 -0800459#else
460 UNIMPLEMENTED(WARNING);
461#endif
462}
463
464} // namespace art