trace.cc revision 82558acbca3eae5b7e47748bcfb8070855266676
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "trace.h"
18
19#include <sys/uio.h>
20
21#include "base/stl_util.h"
22#include "base/unix_file/fd_file.h"
23#include "class_linker.h"
24#include "common_throws.h"
25#include "debugger.h"
26#include "dex_file-inl.h"
27#include "instrumentation.h"
28#include "mirror/art_method-inl.h"
29#include "mirror/class-inl.h"
30#include "mirror/dex_cache.h"
31#include "mirror/object_array-inl.h"
32#include "mirror/object-inl.h"
33#include "object_utils.h"
34#include "os.h"
35#include "scoped_thread_state_change.h"
36#include "ScopedLocalRef.h"
37#include "thread.h"
38#include "thread_list.h"
39#if !defined(ART_USE_PORTABLE_COMPILER)
40#include "entrypoints/quick/quick_entrypoints.h"
41#endif
42
43namespace art {
44
45// File format:
46//     header
47//     record 0
48//     record 1
49//     ...
50//
51// Header format:
52//     u4  magic ('SLOW')
53//     u2  version
54//     u2  offset to data
55//     u8  start date/time in usec
56//     u2  record size in bytes (version >= 2 only)
57//     ... padding to 32 bytes
58//
59// Record format v1:
60//     u1  thread ID
61//     u4  method ID | method action
62//     u4  time delta since start, in usec
63//
64// Record format v2:
65//     u2  thread ID
66//     u4  method ID | method action
67//     u4  time delta since start, in usec
68//
69// Record format v3:
70//     u2  thread ID
71//     u4  method ID | method action
72//     u4  time delta since start, in usec
73//     u4  wall time since start, in usec (when clock == "dual" only)
74//
75// 32 bits of microseconds is 70 minutes.
76//
77// All values are stored in little-endian order.
78
79enum TraceAction {
80    kTraceMethodEnter = 0x00,       // method entry
81    kTraceMethodExit = 0x01,        // method exit
82    kTraceUnroll = 0x02,            // method exited by exception unrolling
83    // 0x03 currently unused
84    kTraceMethodActionMask = 0x03,  // two bits
85};
86
87class BuildStackTraceVisitor : public StackVisitor {
88 public:
89  explicit BuildStackTraceVisitor(Thread* thread) : StackVisitor(thread, NULL),
90      method_trace_(Trace::AllocStackTrace()) {}
91
92  bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
93    mirror::ArtMethod* m = GetMethod();
94    // Ignore runtime frames (in particular callee save).
95    if (!m->IsRuntimeMethod()) {
96      method_trace_->push_back(m);
97    }
98    return true;
99  }
100
101  // Returns a stack trace where the topmost frame corresponds with the first element of the vector.
102  std::vector<mirror::ArtMethod*>* GetStackTrace() const {
103    return method_trace_;
104  }
105
106 private:
107  std::vector<mirror::ArtMethod*>* const method_trace_;
108};
109
110static const char     kTraceTokenChar             = '*';
111static const uint16_t kTraceHeaderLength          = 32;
112static const uint32_t kTraceMagicValue            = 0x574f4c53;
113static const uint16_t kTraceVersionSingleClock    = 2;
114static const uint16_t kTraceVersionDualClock      = 3;
115static const uint16_t kTraceRecordSizeSingleClock = 10;  // using v2
116static const uint16_t kTraceRecordSizeDualClock   = 14;  // using v3 with two timestamps
117
118ProfilerClockSource Trace::default_clock_source_ = kDefaultProfilerClockSource;
119
120Trace* volatile Trace::the_trace_ = NULL;
121pthread_t Trace::sampling_pthread_ = 0U;
122std::unique_ptr<std::vector<mirror::ArtMethod*>> Trace::temp_stack_trace_;
123
124static mirror::ArtMethod* DecodeTraceMethodId(uint32_t tmid) {
125  return reinterpret_cast<mirror::ArtMethod*>(tmid & ~kTraceMethodActionMask);
126}
127
128static TraceAction DecodeTraceAction(uint32_t tmid) {
129  return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
130}
131
132static uint32_t EncodeTraceMethodAndAction(mirror::ArtMethod* method,
133                                           TraceAction action) {
134  uint32_t tmid = PointerToLowMemUInt32(method) | action;
135  DCHECK_EQ(method, DecodeTraceMethodId(tmid));
136  return tmid;
137}
138
139std::vector<mirror::ArtMethod*>* Trace::AllocStackTrace() {
140  if (temp_stack_trace_.get() != NULL) {
141    return temp_stack_trace_.release();
142  } else {
143    return new std::vector<mirror::ArtMethod*>();
144  }
145}
146
147void Trace::FreeStackTrace(std::vector<mirror::ArtMethod*>* stack_trace) {
148  stack_trace->clear();
149  temp_stack_trace_.reset(stack_trace);
150}
151
152void Trace::SetDefaultClockSource(ProfilerClockSource clock_source) {
153#if defined(HAVE_POSIX_CLOCKS)
154  default_clock_source_ = clock_source;
155#else
156  if (clock_source != kProfilerClockSourceWall) {
157    LOG(WARNING) << "Ignoring tracing request to use CPU time.";
158  }
159#endif
160}
161
162static uint16_t GetTraceVersion(ProfilerClockSource clock_source) {
163  return (clock_source == kProfilerClockSourceDual) ? kTraceVersionDualClock
164                                                    : kTraceVersionSingleClock;
165}
166
167static uint16_t GetRecordSize(ProfilerClockSource clock_source) {
168  return (clock_source == kProfilerClockSourceDual) ? kTraceRecordSizeDualClock
169                                                    : kTraceRecordSizeSingleClock;
170}
171
172bool Trace::UseThreadCpuClock() {
173  return (clock_source_ == kProfilerClockSourceThreadCpu) ||
174      (clock_source_ == kProfilerClockSourceDual);
175}
176
177bool Trace::UseWallClock() {
178  return (clock_source_ == kProfilerClockSourceWall) ||
179      (clock_source_ == kProfilerClockSourceDual);
180}
181
182static void MeasureClockOverhead(Trace* trace) {
183  if (trace->UseThreadCpuClock()) {
184    Thread::Current()->GetCpuMicroTime();
185  }
186  if (trace->UseWallClock()) {
187    MicroTime();
188  }
189}
190
191// Compute an average time taken to measure clocks.
192static uint32_t GetClockOverheadNanoSeconds(Trace* trace) {
193  Thread* self = Thread::Current();
194  uint64_t start = self->GetCpuMicroTime();
195
196  for (int i = 4000; i > 0; i--) {
197    MeasureClockOverhead(trace);
198    MeasureClockOverhead(trace);
199    MeasureClockOverhead(trace);
200    MeasureClockOverhead(trace);
201    MeasureClockOverhead(trace);
202    MeasureClockOverhead(trace);
203    MeasureClockOverhead(trace);
204    MeasureClockOverhead(trace);
205  }
206
207  uint64_t elapsed_us = self->GetCpuMicroTime() - start;
208  return static_cast<uint32_t>(elapsed_us / 32);
209}
210
211// TODO: put this somewhere with the big-endian equivalent used by JDWP.
212static void Append2LE(uint8_t* buf, uint16_t val) {
213  *buf++ = static_cast<uint8_t>(val);
214  *buf++ = static_cast<uint8_t>(val >> 8);
215}
216
217// TODO: put this somewhere with the big-endian equivalent used by JDWP.
218static void Append4LE(uint8_t* buf, uint32_t val) {
219  *buf++ = static_cast<uint8_t>(val);
220  *buf++ = static_cast<uint8_t>(val >> 8);
221  *buf++ = static_cast<uint8_t>(val >> 16);
222  *buf++ = static_cast<uint8_t>(val >> 24);
223}
224
225// TODO: put this somewhere with the big-endian equivalent used by JDWP.
226static void Append8LE(uint8_t* buf, uint64_t val) {
227  *buf++ = static_cast<uint8_t>(val);
228  *buf++ = static_cast<uint8_t>(val >> 8);
229  *buf++ = static_cast<uint8_t>(val >> 16);
230  *buf++ = static_cast<uint8_t>(val >> 24);
231  *buf++ = static_cast<uint8_t>(val >> 32);
232  *buf++ = static_cast<uint8_t>(val >> 40);
233  *buf++ = static_cast<uint8_t>(val >> 48);
234  *buf++ = static_cast<uint8_t>(val >> 56);
235}
236
237static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
238  BuildStackTraceVisitor build_trace_visitor(thread);
239  build_trace_visitor.WalkStack();
240  std::vector<mirror::ArtMethod*>* stack_trace = build_trace_visitor.GetStackTrace();
241  Trace* the_trace = reinterpret_cast<Trace*>(arg);
242  the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
243}
244
245static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg) {
246  thread->SetTraceClockBase(0);
247  std::vector<mirror::ArtMethod*>* stack_trace = thread->GetStackTraceSample();
248  thread->SetStackTraceSample(NULL);
249  delete stack_trace;
250}
251
252void Trace::CompareAndUpdateStackTrace(Thread* thread,
253                                       std::vector<mirror::ArtMethod*>* stack_trace) {
254  CHECK_EQ(pthread_self(), sampling_pthread_);
255  std::vector<mirror::ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
256  // Update the thread's stack trace sample.
257  thread->SetStackTraceSample(stack_trace);
258  // Read timer clocks to use for all events in this trace.
259  uint32_t thread_clock_diff = 0;
260  uint32_t wall_clock_diff = 0;
261  ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
262  if (old_stack_trace == NULL) {
263    // If there's no previous stack trace sample for this thread, log an entry event for all
264    // methods in the trace.
265    for (std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
266         rit != stack_trace->rend(); ++rit) {
267      LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
268                          thread_clock_diff, wall_clock_diff);
269    }
270  } else {
271    // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
272    // events accordingly.
273    std::vector<mirror::ArtMethod*>::reverse_iterator old_rit = old_stack_trace->rbegin();
274    std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
275    // Iterate bottom-up over both traces until there's a difference between them.
276    while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
277      old_rit++;
278      rit++;
279    }
280    // Iterate top-down over the old trace until the point where they differ, emitting exit events.
281    for (std::vector<mirror::ArtMethod*>::iterator old_it = old_stack_trace->begin();
282         old_it != old_rit.base(); ++old_it) {
283      LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
284                          thread_clock_diff, wall_clock_diff);
285    }
286    // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
287    for (; rit != stack_trace->rend(); ++rit) {
288      LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
289                          thread_clock_diff, wall_clock_diff);
290    }
291    FreeStackTrace(old_stack_trace);
292  }
293}
294
295void* Trace::RunSamplingThread(void* arg) {
296  Runtime* runtime = Runtime::Current();
297  intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
298  CHECK_GE(interval_us, 0);
299  CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
300                                     !runtime->IsCompiler()));
301
302  while (true) {
303    usleep(interval_us);
304    ATRACE_BEGIN("Profile sampling");
305    Thread* self = Thread::Current();
306    Trace* the_trace;
307    {
308      MutexLock mu(self, *Locks::trace_lock_);
309      the_trace = the_trace_;
310      if (the_trace == NULL) {
311        break;
312      }
313    }
314
315    runtime->GetThreadList()->SuspendAll();
316    {
317      MutexLock mu(self, *Locks::thread_list_lock_);
318      runtime->GetThreadList()->ForEach(GetSample, the_trace);
319    }
320    runtime->GetThreadList()->ResumeAll();
321    ATRACE_END();
322  }
323
324  runtime->DetachCurrentThread();
325  return NULL;
326}
327
328void Trace::Start(const char* trace_filename, int trace_fd, int buffer_size, int flags,
329                  bool direct_to_ddms, bool sampling_enabled, int interval_us) {
330  Thread* self = Thread::Current();
331  {
332    MutexLock mu(self, *Locks::trace_lock_);
333    if (the_trace_ != NULL) {
334      LOG(ERROR) << "Trace already in progress, ignoring this request";
335      return;
336    }
337  }
338  Runtime* runtime = Runtime::Current();
339  runtime->GetThreadList()->SuspendAll();
340
341  // Open trace file if not going directly to ddms.
342  std::unique_ptr<File> trace_file;
343  if (!direct_to_ddms) {
344    if (trace_fd < 0) {
345      trace_file.reset(OS::CreateEmptyFile(trace_filename));
346    } else {
347      trace_file.reset(new File(trace_fd, "tracefile"));
348      trace_file->DisableAutoClose();
349    }
350    if (trace_file.get() == NULL) {
351      PLOG(ERROR) << "Unable to open trace file '" << trace_filename << "'";
352      runtime->GetThreadList()->ResumeAll();
353      ScopedObjectAccess soa(self);
354      ThrowRuntimeException("Unable to open trace file '%s'", trace_filename);
355      return;
356    }
357  }
358
359  // Create Trace object.
360  {
361    MutexLock mu(self, *Locks::trace_lock_);
362    if (the_trace_ != NULL) {
363      LOG(ERROR) << "Trace already in progress, ignoring this request";
364    } else {
365      the_trace_ = new Trace(trace_file.release(), buffer_size, flags, sampling_enabled);
366
367      // Enable count of allocs if specified in the flags.
368      if ((flags && kTraceCountAllocs) != 0) {
369        runtime->SetStatsEnabled(true);
370      }
371
372
373
374      if (sampling_enabled) {
375        CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, NULL, &RunSamplingThread,
376                                            reinterpret_cast<void*>(interval_us)),
377                                            "Sampling profiler thread");
378      } else {
379        runtime->GetInstrumentation()->AddListener(the_trace_,
380                                                   instrumentation::Instrumentation::kMethodEntered |
381                                                   instrumentation::Instrumentation::kMethodExited |
382                                                   instrumentation::Instrumentation::kMethodUnwind);
383        runtime->GetInstrumentation()->EnableMethodTracing();
384      }
385    }
386  }
387  runtime->GetThreadList()->ResumeAll();
388}
389
390void Trace::Stop() {
391  Runtime* runtime = Runtime::Current();
392  runtime->GetThreadList()->SuspendAll();
393  Trace* the_trace = NULL;
394  pthread_t sampling_pthread = 0U;
395  {
396    MutexLock mu(Thread::Current(), *Locks::trace_lock_);
397    if (the_trace_ == NULL) {
398      LOG(ERROR) << "Trace stop requested, but no trace currently running";
399    } else {
400      the_trace = the_trace_;
401      the_trace_ = NULL;
402      sampling_pthread = sampling_pthread_;
403      sampling_pthread_ = 0U;
404    }
405  }
406  if (the_trace != NULL) {
407    the_trace->FinishTracing();
408
409    if (the_trace->sampling_enabled_) {
410      MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
411      runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, NULL);
412    } else {
413      runtime->GetInstrumentation()->DisableMethodTracing();
414      runtime->GetInstrumentation()->RemoveListener(the_trace,
415                                                    instrumentation::Instrumentation::kMethodEntered |
416                                                    instrumentation::Instrumentation::kMethodExited |
417                                                    instrumentation::Instrumentation::kMethodUnwind);
418    }
419    delete the_trace;
420  }
421  runtime->GetThreadList()->ResumeAll();
422
423  if (sampling_pthread != 0U) {
424    CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, NULL), "sampling thread shutdown");
425  }
426}
427
428void Trace::Shutdown() {
429  if (GetMethodTracingMode() != kTracingInactive) {
430    Stop();
431  }
432}
433
434TracingMode Trace::GetMethodTracingMode() {
435  MutexLock mu(Thread::Current(), *Locks::trace_lock_);
436  if (the_trace_ == NULL) {
437    return kTracingInactive;
438  } else if (the_trace_->sampling_enabled_) {
439    return kSampleProfilingActive;
440  } else {
441    return kMethodTracingActive;
442  }
443}
444
445Trace::Trace(File* trace_file, int buffer_size, int flags, bool sampling_enabled)
446    : trace_file_(trace_file), buf_(new uint8_t[buffer_size]()), flags_(flags),
447      sampling_enabled_(sampling_enabled), clock_source_(default_clock_source_),
448      buffer_size_(buffer_size), start_time_(MicroTime()), cur_offset_(0),  overflow_(false) {
449  // Set up the beginning of the trace.
450  uint16_t trace_version = GetTraceVersion(clock_source_);
451  memset(buf_.get(), 0, kTraceHeaderLength);
452  Append4LE(buf_.get(), kTraceMagicValue);
453  Append2LE(buf_.get() + 4, trace_version);
454  Append2LE(buf_.get() + 6, kTraceHeaderLength);
455  Append8LE(buf_.get() + 8, start_time_);
456  if (trace_version >= kTraceVersionDualClock) {
457    uint16_t record_size = GetRecordSize(clock_source_);
458    Append2LE(buf_.get() + 16, record_size);
459  }
460
461  // Update current offset.
462  cur_offset_.StoreRelaxed(kTraceHeaderLength);
463}
464
465static void DumpBuf(uint8_t* buf, size_t buf_size, ProfilerClockSource clock_source)
466    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
467  uint8_t* ptr = buf + kTraceHeaderLength;
468  uint8_t* end = buf + buf_size;
469
470  while (ptr < end) {
471    uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
472    mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
473    TraceAction action = DecodeTraceAction(tmid);
474    LOG(INFO) << PrettyMethod(method) << " " << static_cast<int>(action);
475    ptr += GetRecordSize(clock_source);
476  }
477}
478
479void Trace::FinishTracing() {
480  // Compute elapsed time.
481  uint64_t elapsed = MicroTime() - start_time_;
482
483  size_t final_offset = cur_offset_.LoadRelaxed();
484  uint32_t clock_overhead_ns = GetClockOverheadNanoSeconds(this);
485
486  if ((flags_ & kTraceCountAllocs) != 0) {
487    Runtime::Current()->SetStatsEnabled(false);
488  }
489
490  std::set<mirror::ArtMethod*> visited_methods;
491  GetVisitedMethods(final_offset, &visited_methods);
492
493  std::ostringstream os;
494
495  os << StringPrintf("%cversion\n", kTraceTokenChar);
496  os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
497  os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
498  if (UseThreadCpuClock()) {
499    if (UseWallClock()) {
500      os << StringPrintf("clock=dual\n");
501    } else {
502      os << StringPrintf("clock=thread-cpu\n");
503    }
504  } else {
505    os << StringPrintf("clock=wall\n");
506  }
507  os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
508  size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
509  os << StringPrintf("num-method-calls=%zd\n", num_records);
510  os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns);
511  os << StringPrintf("vm=art\n");
512  if ((flags_ & kTraceCountAllocs) != 0) {
513    os << StringPrintf("alloc-count=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS));
514    os << StringPrintf("alloc-size=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES));
515    os << StringPrintf("gc-count=%d\n", Runtime::Current()->GetStat(KIND_GC_INVOCATIONS));
516  }
517  os << StringPrintf("%cthreads\n", kTraceTokenChar);
518  DumpThreadList(os);
519  os << StringPrintf("%cmethods\n", kTraceTokenChar);
520  DumpMethodList(os, visited_methods);
521  os << StringPrintf("%cend\n", kTraceTokenChar);
522
523  std::string header(os.str());
524  if (trace_file_.get() == NULL) {
525    iovec iov[2];
526    iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
527    iov[0].iov_len = header.length();
528    iov[1].iov_base = buf_.get();
529    iov[1].iov_len = final_offset;
530    Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
531    const bool kDumpTraceInfo = false;
532    if (kDumpTraceInfo) {
533      LOG(INFO) << "Trace sent:\n" << header;
534      DumpBuf(buf_.get(), final_offset, clock_source_);
535    }
536  } else {
537    if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
538        !trace_file_->WriteFully(buf_.get(), final_offset)) {
539      std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
540      PLOG(ERROR) << detail;
541      ThrowRuntimeException("%s", detail.c_str());
542    }
543  }
544}
545
546void Trace::DexPcMoved(Thread* thread, mirror::Object* this_object,
547                       mirror::ArtMethod* method, uint32_t new_dex_pc) {
548  // We're not recorded to listen to this kind of event, so complain.
549  LOG(ERROR) << "Unexpected dex PC event in tracing " << PrettyMethod(method) << " " << new_dex_pc;
550};
551
552void Trace::FieldRead(Thread* /*thread*/, mirror::Object* this_object,
553                       mirror::ArtMethod* method, uint32_t dex_pc, mirror::ArtField* field)
554    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
555  // We're not recorded to listen to this kind of event, so complain.
556  LOG(ERROR) << "Unexpected field read event in tracing " << PrettyMethod(method) << " " << dex_pc;
557}
558
559void Trace::FieldWritten(Thread* /*thread*/, mirror::Object* this_object,
560                          mirror::ArtMethod* method, uint32_t dex_pc, mirror::ArtField* field,
561                          const JValue& field_value)
562    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
563  // We're not recorded to listen to this kind of event, so complain.
564  LOG(ERROR) << "Unexpected field write event in tracing " << PrettyMethod(method) << " " << dex_pc;
565}
566
567void Trace::MethodEntered(Thread* thread, mirror::Object* this_object,
568                          mirror::ArtMethod* method, uint32_t dex_pc) {
569  uint32_t thread_clock_diff = 0;
570  uint32_t wall_clock_diff = 0;
571  ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
572  LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodEntered,
573                      thread_clock_diff, wall_clock_diff);
574}
575
576void Trace::MethodExited(Thread* thread, mirror::Object* this_object,
577                         mirror::ArtMethod* method, uint32_t dex_pc,
578                         const JValue& return_value) {
579  UNUSED(return_value);
580  uint32_t thread_clock_diff = 0;
581  uint32_t wall_clock_diff = 0;
582  ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
583  LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodExited,
584                      thread_clock_diff, wall_clock_diff);
585}
586
587void Trace::MethodUnwind(Thread* thread, mirror::Object* this_object,
588                         mirror::ArtMethod* method, uint32_t dex_pc) {
589  uint32_t thread_clock_diff = 0;
590  uint32_t wall_clock_diff = 0;
591  ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
592  LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
593                      thread_clock_diff, wall_clock_diff);
594}
595
596void Trace::ExceptionCaught(Thread* thread, const ThrowLocation& throw_location,
597                            mirror::ArtMethod* catch_method, uint32_t catch_dex_pc,
598                            mirror::Throwable* exception_object)
599    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
600  LOG(ERROR) << "Unexpected exception caught event in tracing";
601}
602
603void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
604  if (UseThreadCpuClock()) {
605    uint64_t clock_base = thread->GetTraceClockBase();
606    if (UNLIKELY(clock_base == 0)) {
607      // First event, record the base time in the map.
608      uint64_t time = thread->GetCpuMicroTime();
609      thread->SetTraceClockBase(time);
610    } else {
611      *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
612    }
613  }
614  if (UseWallClock()) {
615    *wall_clock_diff = MicroTime() - start_time_;
616  }
617}
618
619void Trace::LogMethodTraceEvent(Thread* thread, mirror::ArtMethod* method,
620                                instrumentation::Instrumentation::InstrumentationEvent event,
621                                uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
622  // Advance cur_offset_ atomically.
623  int32_t new_offset;
624  int32_t old_offset;
625  do {
626    old_offset = cur_offset_.LoadRelaxed();
627    new_offset = old_offset + GetRecordSize(clock_source_);
628    if (new_offset > buffer_size_) {
629      overflow_ = true;
630      return;
631    }
632  } while (!cur_offset_.CompareExchangeWeakSequentiallyConsistent(old_offset, new_offset));
633
634  TraceAction action = kTraceMethodEnter;
635  switch (event) {
636    case instrumentation::Instrumentation::kMethodEntered:
637      action = kTraceMethodEnter;
638      break;
639    case instrumentation::Instrumentation::kMethodExited:
640      action = kTraceMethodExit;
641      break;
642    case instrumentation::Instrumentation::kMethodUnwind:
643      action = kTraceUnroll;
644      break;
645    default:
646      UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
647  }
648
649  uint32_t method_value = EncodeTraceMethodAndAction(method, action);
650
651  // Write data
652  uint8_t* ptr = buf_.get() + old_offset;
653  Append2LE(ptr, thread->GetTid());
654  Append4LE(ptr + 2, method_value);
655  ptr += 6;
656
657  if (UseThreadCpuClock()) {
658    Append4LE(ptr, thread_clock_diff);
659    ptr += 4;
660  }
661  if (UseWallClock()) {
662    Append4LE(ptr, wall_clock_diff);
663  }
664}
665
666void Trace::GetVisitedMethods(size_t buf_size,
667                              std::set<mirror::ArtMethod*>* visited_methods) {
668  uint8_t* ptr = buf_.get() + kTraceHeaderLength;
669  uint8_t* end = buf_.get() + buf_size;
670
671  while (ptr < end) {
672    uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
673    mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
674    visited_methods->insert(method);
675    ptr += GetRecordSize(clock_source_);
676  }
677}
678
679void Trace::DumpMethodList(std::ostream& os, const std::set<mirror::ArtMethod*>& visited_methods) {
680  for (const auto& method : visited_methods) {
681    os << StringPrintf("%p\t%s\t%s\t%s\t%s\n", method,
682        PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
683        method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
684  }
685}
686
687static void DumpThread(Thread* t, void* arg) {
688  std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
689  std::string name;
690  t->GetThreadName(name);
691  os << t->GetTid() << "\t" << name << "\n";
692}
693
694void Trace::DumpThreadList(std::ostream& os) {
695  Thread* self = Thread::Current();
696  Locks::thread_list_lock_->AssertNotHeld(self);
697  MutexLock mu(self, *Locks::thread_list_lock_);
698  Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
699}
700
701}  // namespace art
702