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 #include <unistd.h>
21
22 #include "android-base/macros.h"
23 #include "android-base/stringprintf.h"
24
25 #include "art_method-inl.h"
26 #include "base/casts.h"
27 #include "base/enums.h"
28 #include "base/os.h"
29 #include "base/stl_util.h"
30 #include "base/systrace.h"
31 #include "base/time_utils.h"
32 #include "base/unix_file/fd_file.h"
33 #include "base/utils.h"
34 #include "class_linker.h"
35 #include "common_throws.h"
36 #include "debugger.h"
37 #include "dex/descriptors_names.h"
38 #include "dex/dex_file-inl.h"
39 #include "entrypoints/quick/quick_entrypoints.h"
40 #include "gc/scoped_gc_critical_section.h"
41 #include "instrumentation.h"
42 #include "jit/jit.h"
43 #include "jit/jit_code_cache.h"
44 #include "mirror/class-inl.h"
45 #include "mirror/dex_cache-inl.h"
46 #include "mirror/object-inl.h"
47 #include "mirror/object_array-inl.h"
48 #include "nativehelper/scoped_local_ref.h"
49 #include "scoped_thread_state_change-inl.h"
50 #include "stack.h"
51 #include "thread.h"
52 #include "thread_list.h"
53
54 namespace art {
55
56 using android::base::StringPrintf;
57
58 static constexpr size_t TraceActionBits = MinimumBitsToStore(
59 static_cast<size_t>(kTraceMethodActionMask));
60 static constexpr uint8_t kOpNewMethod = 1U;
61 static constexpr uint8_t kOpNewThread = 2U;
62 static constexpr uint8_t kOpTraceSummary = 3U;
63
64 static const char kTraceTokenChar = '*';
65 static const uint16_t kTraceHeaderLength = 32;
66 static const uint32_t kTraceMagicValue = 0x574f4c53;
67 static const uint16_t kTraceVersionSingleClock = 2;
68 static const uint16_t kTraceVersionDualClock = 3;
69 static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
70 static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
71
72 TraceClockSource Trace::default_clock_source_ = kDefaultTraceClockSource;
73
74 Trace* volatile Trace::the_trace_ = nullptr;
75 pthread_t Trace::sampling_pthread_ = 0U;
76 std::unique_ptr<std::vector<ArtMethod*>> Trace::temp_stack_trace_;
77
78 // The key identifying the tracer to update instrumentation.
79 static constexpr const char* kTracerInstrumentationKey = "Tracer";
80
DecodeTraceAction(uint32_t tmid)81 static TraceAction DecodeTraceAction(uint32_t tmid) {
82 return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
83 }
84
DecodeTraceMethod(uint32_t tmid)85 ArtMethod* Trace::DecodeTraceMethod(uint32_t tmid) {
86 MutexLock mu(Thread::Current(), *unique_methods_lock_);
87 return unique_methods_[tmid >> TraceActionBits];
88 }
89
EncodeTraceMethod(ArtMethod * method)90 uint32_t Trace::EncodeTraceMethod(ArtMethod* method) {
91 MutexLock mu(Thread::Current(), *unique_methods_lock_);
92 uint32_t idx;
93 auto it = art_method_id_map_.find(method);
94 if (it != art_method_id_map_.end()) {
95 idx = it->second;
96 } else {
97 unique_methods_.push_back(method);
98 idx = unique_methods_.size() - 1;
99 art_method_id_map_.emplace(method, idx);
100 }
101 DCHECK_LT(idx, unique_methods_.size());
102 DCHECK_EQ(unique_methods_[idx], method);
103 return idx;
104 }
105
EncodeTraceMethodAndAction(ArtMethod * method,TraceAction action)106 uint32_t Trace::EncodeTraceMethodAndAction(ArtMethod* method, TraceAction action) {
107 uint32_t tmid = (EncodeTraceMethod(method) << TraceActionBits) | action;
108 DCHECK_EQ(method, DecodeTraceMethod(tmid));
109 return tmid;
110 }
111
AllocStackTrace()112 std::vector<ArtMethod*>* Trace::AllocStackTrace() {
113 return (temp_stack_trace_.get() != nullptr) ? temp_stack_trace_.release() :
114 new std::vector<ArtMethod*>();
115 }
116
FreeStackTrace(std::vector<ArtMethod * > * stack_trace)117 void Trace::FreeStackTrace(std::vector<ArtMethod*>* stack_trace) {
118 stack_trace->clear();
119 temp_stack_trace_.reset(stack_trace);
120 }
121
SetDefaultClockSource(TraceClockSource clock_source)122 void Trace::SetDefaultClockSource(TraceClockSource clock_source) {
123 #if defined(__linux__)
124 default_clock_source_ = clock_source;
125 #else
126 if (clock_source != TraceClockSource::kWall) {
127 LOG(WARNING) << "Ignoring tracing request to use CPU time.";
128 }
129 #endif
130 }
131
GetTraceVersion(TraceClockSource clock_source)132 static uint16_t GetTraceVersion(TraceClockSource clock_source) {
133 return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
134 : kTraceVersionSingleClock;
135 }
136
GetRecordSize(TraceClockSource clock_source)137 static uint16_t GetRecordSize(TraceClockSource clock_source) {
138 return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
139 : kTraceRecordSizeSingleClock;
140 }
141
UseThreadCpuClock()142 bool Trace::UseThreadCpuClock() {
143 return (clock_source_ == TraceClockSource::kThreadCpu) ||
144 (clock_source_ == TraceClockSource::kDual);
145 }
146
UseWallClock()147 bool Trace::UseWallClock() {
148 return (clock_source_ == TraceClockSource::kWall) ||
149 (clock_source_ == TraceClockSource::kDual);
150 }
151
MeasureClockOverhead()152 void Trace::MeasureClockOverhead() {
153 if (UseThreadCpuClock()) {
154 Thread::Current()->GetCpuMicroTime();
155 }
156 if (UseWallClock()) {
157 MicroTime();
158 }
159 }
160
161 // Compute an average time taken to measure clocks.
GetClockOverheadNanoSeconds()162 uint32_t Trace::GetClockOverheadNanoSeconds() {
163 Thread* self = Thread::Current();
164 uint64_t start = self->GetCpuMicroTime();
165
166 for (int i = 4000; i > 0; i--) {
167 MeasureClockOverhead();
168 MeasureClockOverhead();
169 MeasureClockOverhead();
170 MeasureClockOverhead();
171 MeasureClockOverhead();
172 MeasureClockOverhead();
173 MeasureClockOverhead();
174 MeasureClockOverhead();
175 }
176
177 uint64_t elapsed_us = self->GetCpuMicroTime() - start;
178 return static_cast<uint32_t>(elapsed_us / 32);
179 }
180
181 // TODO: put this somewhere with the big-endian equivalent used by JDWP.
Append2LE(uint8_t * buf,uint16_t val)182 static void Append2LE(uint8_t* buf, uint16_t val) {
183 *buf++ = static_cast<uint8_t>(val);
184 *buf++ = static_cast<uint8_t>(val >> 8);
185 }
186
187 // TODO: put this somewhere with the big-endian equivalent used by JDWP.
Append4LE(uint8_t * buf,uint32_t val)188 static void Append4LE(uint8_t* buf, uint32_t val) {
189 *buf++ = static_cast<uint8_t>(val);
190 *buf++ = static_cast<uint8_t>(val >> 8);
191 *buf++ = static_cast<uint8_t>(val >> 16);
192 *buf++ = static_cast<uint8_t>(val >> 24);
193 }
194
195 // TODO: put this somewhere with the big-endian equivalent used by JDWP.
Append8LE(uint8_t * buf,uint64_t val)196 static void Append8LE(uint8_t* buf, uint64_t val) {
197 *buf++ = static_cast<uint8_t>(val);
198 *buf++ = static_cast<uint8_t>(val >> 8);
199 *buf++ = static_cast<uint8_t>(val >> 16);
200 *buf++ = static_cast<uint8_t>(val >> 24);
201 *buf++ = static_cast<uint8_t>(val >> 32);
202 *buf++ = static_cast<uint8_t>(val >> 40);
203 *buf++ = static_cast<uint8_t>(val >> 48);
204 *buf++ = static_cast<uint8_t>(val >> 56);
205 }
206
GetSample(Thread * thread,void * arg)207 static void GetSample(Thread* thread, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
208 std::vector<ArtMethod*>* const stack_trace = Trace::AllocStackTrace();
209 StackVisitor::WalkStack(
210 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
211 ArtMethod* m = stack_visitor->GetMethod();
212 // Ignore runtime frames (in particular callee save).
213 if (!m->IsRuntimeMethod()) {
214 stack_trace->push_back(m);
215 }
216 return true;
217 },
218 thread,
219 /* context= */ nullptr,
220 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
221 Trace* the_trace = reinterpret_cast<Trace*>(arg);
222 the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
223 }
224
ClearThreadStackTraceAndClockBase(Thread * thread,void * arg ATTRIBUTE_UNUSED)225 static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
226 thread->SetTraceClockBase(0);
227 std::vector<ArtMethod*>* stack_trace = thread->GetStackTraceSample();
228 thread->SetStackTraceSample(nullptr);
229 delete stack_trace;
230 }
231
CompareAndUpdateStackTrace(Thread * thread,std::vector<ArtMethod * > * stack_trace)232 void Trace::CompareAndUpdateStackTrace(Thread* thread,
233 std::vector<ArtMethod*>* stack_trace) {
234 CHECK_EQ(pthread_self(), sampling_pthread_);
235 std::vector<ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
236 // Update the thread's stack trace sample.
237 thread->SetStackTraceSample(stack_trace);
238 // Read timer clocks to use for all events in this trace.
239 uint32_t thread_clock_diff = 0;
240 uint32_t wall_clock_diff = 0;
241 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
242 if (old_stack_trace == nullptr) {
243 // If there's no previous stack trace sample for this thread, log an entry event for all
244 // methods in the trace.
245 for (auto rit = stack_trace->rbegin(); rit != stack_trace->rend(); ++rit) {
246 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
247 thread_clock_diff, wall_clock_diff);
248 }
249 } else {
250 // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
251 // events accordingly.
252 auto old_rit = old_stack_trace->rbegin();
253 auto rit = stack_trace->rbegin();
254 // Iterate bottom-up over both traces until there's a difference between them.
255 while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
256 old_rit++;
257 rit++;
258 }
259 // Iterate top-down over the old trace until the point where they differ, emitting exit events.
260 for (auto old_it = old_stack_trace->begin(); old_it != old_rit.base(); ++old_it) {
261 LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
262 thread_clock_diff, wall_clock_diff);
263 }
264 // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
265 for (; rit != stack_trace->rend(); ++rit) {
266 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
267 thread_clock_diff, wall_clock_diff);
268 }
269 FreeStackTrace(old_stack_trace);
270 }
271 }
272
RunSamplingThread(void * arg)273 void* Trace::RunSamplingThread(void* arg) {
274 Runtime* runtime = Runtime::Current();
275 intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
276 CHECK_GE(interval_us, 0);
277 CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
278 !runtime->IsAotCompiler()));
279
280 while (true) {
281 usleep(interval_us);
282 ScopedTrace trace("Profile sampling");
283 Thread* self = Thread::Current();
284 Trace* the_trace;
285 {
286 MutexLock mu(self, *Locks::trace_lock_);
287 the_trace = the_trace_;
288 if (the_trace == nullptr) {
289 break;
290 }
291 }
292 {
293 // Avoid a deadlock between a thread doing garbage collection
294 // and the profile sampling thread, by blocking GC when sampling
295 // thread stacks (see b/73624630).
296 gc::ScopedGCCriticalSection gcs(self,
297 art::gc::kGcCauseInstrumentation,
298 art::gc::kCollectorTypeInstrumentation);
299 ScopedSuspendAll ssa(__FUNCTION__);
300 MutexLock mu(self, *Locks::thread_list_lock_);
301 runtime->GetThreadList()->ForEach(GetSample, the_trace);
302 }
303 }
304
305 runtime->DetachCurrentThread();
306 return nullptr;
307 }
308
Start(const char * trace_filename,size_t buffer_size,int flags,TraceOutputMode output_mode,TraceMode trace_mode,int interval_us)309 void Trace::Start(const char* trace_filename,
310 size_t buffer_size,
311 int flags,
312 TraceOutputMode output_mode,
313 TraceMode trace_mode,
314 int interval_us) {
315 std::unique_ptr<File> file(OS::CreateEmptyFileWriteOnly(trace_filename));
316 if (file == nullptr) {
317 std::string msg = android::base::StringPrintf("Unable to open trace file '%s'", trace_filename);
318 PLOG(ERROR) << msg;
319 ScopedObjectAccess soa(Thread::Current());
320 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;", msg.c_str());
321 return;
322 }
323 Start(std::move(file), buffer_size, flags, output_mode, trace_mode, interval_us);
324 }
325
Start(int trace_fd,size_t buffer_size,int flags,TraceOutputMode output_mode,TraceMode trace_mode,int interval_us)326 void Trace::Start(int trace_fd,
327 size_t buffer_size,
328 int flags,
329 TraceOutputMode output_mode,
330 TraceMode trace_mode,
331 int interval_us) {
332 if (trace_fd < 0) {
333 std::string msg = android::base::StringPrintf("Unable to start tracing with invalid fd %d",
334 trace_fd);
335 LOG(ERROR) << msg;
336 ScopedObjectAccess soa(Thread::Current());
337 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;", msg.c_str());
338 return;
339 }
340 std::unique_ptr<File> file(new File(trace_fd, /* path= */ "tracefile", /* check_usage= */ true));
341 Start(std::move(file), buffer_size, flags, output_mode, trace_mode, interval_us);
342 }
343
StartDDMS(size_t buffer_size,int flags,TraceMode trace_mode,int interval_us)344 void Trace::StartDDMS(size_t buffer_size,
345 int flags,
346 TraceMode trace_mode,
347 int interval_us) {
348 Start(std::unique_ptr<File>(),
349 buffer_size,
350 flags,
351 TraceOutputMode::kDDMS,
352 trace_mode,
353 interval_us);
354 }
355
Start(std::unique_ptr<File> && trace_file_in,size_t buffer_size,int flags,TraceOutputMode output_mode,TraceMode trace_mode,int interval_us)356 void Trace::Start(std::unique_ptr<File>&& trace_file_in,
357 size_t buffer_size,
358 int flags,
359 TraceOutputMode output_mode,
360 TraceMode trace_mode,
361 int interval_us) {
362 // We own trace_file now and are responsible for closing it. To account for error situations, use
363 // a specialized unique_ptr to ensure we close it on the way out (if it hasn't been passed to a
364 // Trace instance).
365 auto deleter = [](File* file) {
366 if (file != nullptr) {
367 file->MarkUnchecked(); // Don't deal with flushing requirements.
368 int result ATTRIBUTE_UNUSED = file->Close();
369 delete file;
370 }
371 };
372 std::unique_ptr<File, decltype(deleter)> trace_file(trace_file_in.release(), deleter);
373
374 Thread* self = Thread::Current();
375 {
376 MutexLock mu(self, *Locks::trace_lock_);
377 if (the_trace_ != nullptr) {
378 LOG(ERROR) << "Trace already in progress, ignoring this request";
379 return;
380 }
381 }
382
383 // Check interval if sampling is enabled
384 if (trace_mode == TraceMode::kSampling && interval_us <= 0) {
385 LOG(ERROR) << "Invalid sampling interval: " << interval_us;
386 ScopedObjectAccess soa(self);
387 ThrowRuntimeException("Invalid sampling interval: %d", interval_us);
388 return;
389 }
390
391 Runtime* runtime = Runtime::Current();
392
393 // Enable count of allocs if specified in the flags.
394 bool enable_stats = false;
395
396 if (runtime->GetJit() != nullptr) {
397 // TODO b/110263880 It would be better if we didn't need to do this.
398 // Since we need to hold the method entrypoint across a suspend to ensure instrumentation
399 // hooks are called correctly we have to disable jit-gc to ensure that the entrypoint doesn't
400 // go away. Furthermore we need to leave this off permanently since one could get the same
401 // effect by causing this to be toggled on and off.
402 runtime->GetJit()->GetCodeCache()->SetGarbageCollectCode(false);
403 }
404
405 // Create Trace object.
406 {
407 // Required since EnableMethodTracing calls ConfigureStubs which visits class linker classes.
408 gc::ScopedGCCriticalSection gcs(self,
409 gc::kGcCauseInstrumentation,
410 gc::kCollectorTypeInstrumentation);
411 ScopedSuspendAll ssa(__FUNCTION__);
412 MutexLock mu(self, *Locks::trace_lock_);
413 if (the_trace_ != nullptr) {
414 LOG(ERROR) << "Trace already in progress, ignoring this request";
415 } else {
416 enable_stats = (flags & kTraceCountAllocs) != 0;
417 the_trace_ = new Trace(trace_file.release(), buffer_size, flags, output_mode, trace_mode);
418 if (trace_mode == TraceMode::kSampling) {
419 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
420 reinterpret_cast<void*>(interval_us)),
421 "Sampling profiler thread");
422 the_trace_->interval_us_ = interval_us;
423 } else {
424 runtime->GetInstrumentation()->AddListener(the_trace_,
425 instrumentation::Instrumentation::kMethodEntered |
426 instrumentation::Instrumentation::kMethodExited |
427 instrumentation::Instrumentation::kMethodUnwind);
428 // TODO: In full-PIC mode, we don't need to fully deopt.
429 // TODO: We can only use trampoline entrypoints if we are java-debuggable since in that case
430 // we know that inlining and other problematic optimizations are disabled. We might just
431 // want to use the trampolines anyway since it is faster. It makes the story with disabling
432 // jit-gc more complex though.
433 runtime->GetInstrumentation()->EnableMethodTracing(
434 kTracerInstrumentationKey, /*needs_interpreter=*/!runtime->IsJavaDebuggable());
435 }
436 }
437 }
438
439 // Can't call this when holding the mutator lock.
440 if (enable_stats) {
441 runtime->SetStatsEnabled(true);
442 }
443 }
444
StopTracing(bool finish_tracing,bool flush_file)445 void Trace::StopTracing(bool finish_tracing, bool flush_file) {
446 bool stop_alloc_counting = false;
447 Runtime* const runtime = Runtime::Current();
448 Trace* the_trace = nullptr;
449 Thread* const self = Thread::Current();
450 pthread_t sampling_pthread = 0U;
451 {
452 MutexLock mu(self, *Locks::trace_lock_);
453 if (the_trace_ == nullptr) {
454 LOG(ERROR) << "Trace stop requested, but no trace currently running";
455 } else {
456 the_trace = the_trace_;
457 the_trace_ = nullptr;
458 sampling_pthread = sampling_pthread_;
459 }
460 }
461 // Make sure that we join before we delete the trace since we don't want to have
462 // the sampling thread access a stale pointer. This finishes since the sampling thread exits when
463 // the_trace_ is null.
464 if (sampling_pthread != 0U) {
465 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
466 sampling_pthread_ = 0U;
467 }
468
469 if (the_trace != nullptr) {
470 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
471 // Stop the trace sources adding more entries to the trace buffer and synchronise stores.
472 {
473 gc::ScopedGCCriticalSection gcs(self,
474 gc::kGcCauseInstrumentation,
475 gc::kCollectorTypeInstrumentation);
476 ScopedSuspendAll ssa(__FUNCTION__);
477
478 if (the_trace->trace_mode_ == TraceMode::kSampling) {
479 MutexLock mu(self, *Locks::thread_list_lock_);
480 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
481 } else {
482 runtime->GetInstrumentation()->RemoveListener(
483 the_trace, instrumentation::Instrumentation::kMethodEntered |
484 instrumentation::Instrumentation::kMethodExited |
485 instrumentation::Instrumentation::kMethodUnwind);
486 runtime->GetInstrumentation()->DisableMethodTracing(kTracerInstrumentationKey);
487 }
488 }
489 // At this point, code may read buf_ as it's writers are shutdown
490 // and the ScopedSuspendAll above has ensured all stores to buf_
491 // are now visible.
492 if (finish_tracing) {
493 the_trace->FinishTracing();
494 }
495 if (the_trace->trace_file_.get() != nullptr) {
496 // Do not try to erase, so flush and close explicitly.
497 if (flush_file) {
498 if (the_trace->trace_file_->Flush() != 0) {
499 PLOG(WARNING) << "Could not flush trace file.";
500 }
501 } else {
502 the_trace->trace_file_->MarkUnchecked(); // Do not trigger guard.
503 }
504 if (the_trace->trace_file_->Close() != 0) {
505 PLOG(ERROR) << "Could not close trace file.";
506 }
507 }
508 delete the_trace;
509 }
510 if (stop_alloc_counting) {
511 // Can be racy since SetStatsEnabled is not guarded by any locks.
512 runtime->SetStatsEnabled(false);
513 }
514 }
515
Abort()516 void Trace::Abort() {
517 // Do not write anything anymore.
518 StopTracing(false, false);
519 }
520
Stop()521 void Trace::Stop() {
522 // Finish writing.
523 StopTracing(true, true);
524 }
525
Shutdown()526 void Trace::Shutdown() {
527 if (GetMethodTracingMode() != kTracingInactive) {
528 Stop();
529 }
530 }
531
GetMethodTracingMode()532 TracingMode Trace::GetMethodTracingMode() {
533 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
534 if (the_trace_ == nullptr) {
535 return kTracingInactive;
536 } else {
537 switch (the_trace_->trace_mode_) {
538 case TraceMode::kSampling:
539 return kSampleProfilingActive;
540 case TraceMode::kMethodTracing:
541 return kMethodTracingActive;
542 }
543 LOG(FATAL) << "Unreachable";
544 UNREACHABLE();
545 }
546 }
547
548 static constexpr size_t kMinBufSize = 18U; // Trace header is up to 18B.
549
Trace(File * trace_file,size_t buffer_size,int flags,TraceOutputMode output_mode,TraceMode trace_mode)550 Trace::Trace(File* trace_file,
551 size_t buffer_size,
552 int flags,
553 TraceOutputMode output_mode,
554 TraceMode trace_mode)
555 : trace_file_(trace_file),
556 buf_(new uint8_t[std::max(kMinBufSize, buffer_size)]()),
557 flags_(flags), trace_output_mode_(output_mode), trace_mode_(trace_mode),
558 clock_source_(default_clock_source_),
559 buffer_size_(std::max(kMinBufSize, buffer_size)),
560 start_time_(MicroTime()), clock_overhead_ns_(GetClockOverheadNanoSeconds()),
561 overflow_(false), interval_us_(0), streaming_lock_(nullptr),
562 unique_methods_lock_(new Mutex("unique methods lock", kTracingUniqueMethodsLock)) {
563 CHECK(trace_file != nullptr || output_mode == TraceOutputMode::kDDMS);
564
565 uint16_t trace_version = GetTraceVersion(clock_source_);
566 if (output_mode == TraceOutputMode::kStreaming) {
567 trace_version |= 0xF0U;
568 }
569 // Set up the beginning of the trace.
570 memset(buf_.get(), 0, kTraceHeaderLength);
571 Append4LE(buf_.get(), kTraceMagicValue);
572 Append2LE(buf_.get() + 4, trace_version);
573 Append2LE(buf_.get() + 6, kTraceHeaderLength);
574 Append8LE(buf_.get() + 8, start_time_);
575 if (trace_version >= kTraceVersionDualClock) {
576 uint16_t record_size = GetRecordSize(clock_source_);
577 Append2LE(buf_.get() + 16, record_size);
578 }
579 static_assert(18 <= kMinBufSize, "Minimum buffer size not large enough for trace header");
580
581 cur_offset_.store(kTraceHeaderLength, std::memory_order_relaxed);
582
583 if (output_mode == TraceOutputMode::kStreaming) {
584 streaming_lock_ = new Mutex("tracing lock", LockLevel::kTracingStreamingLock);
585 seen_threads_.reset(new ThreadIDBitSet());
586 }
587 }
588
~Trace()589 Trace::~Trace() {
590 delete streaming_lock_;
591 delete unique_methods_lock_;
592 }
593
ReadBytes(uint8_t * buf,size_t bytes)594 static uint64_t ReadBytes(uint8_t* buf, size_t bytes) {
595 uint64_t ret = 0;
596 for (size_t i = 0; i < bytes; ++i) {
597 ret |= static_cast<uint64_t>(buf[i]) << (i * 8);
598 }
599 return ret;
600 }
601
DumpBuf(uint8_t * buf,size_t buf_size,TraceClockSource clock_source)602 void Trace::DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source) {
603 uint8_t* ptr = buf + kTraceHeaderLength;
604 uint8_t* end = buf + buf_size;
605
606 while (ptr < end) {
607 uint32_t tmid = ReadBytes(ptr + 2, sizeof(tmid));
608 ArtMethod* method = DecodeTraceMethod(tmid);
609 TraceAction action = DecodeTraceAction(tmid);
610 LOG(INFO) << ArtMethod::PrettyMethod(method) << " " << static_cast<int>(action);
611 ptr += GetRecordSize(clock_source);
612 }
613 }
614
FinishTracing()615 void Trace::FinishTracing() {
616 size_t final_offset = 0;
617 std::set<ArtMethod*> visited_methods;
618 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
619 // Clean up.
620 MutexLock mu(Thread::Current(), *streaming_lock_);
621 STLDeleteValues(&seen_methods_);
622 } else {
623 final_offset = cur_offset_.load(std::memory_order_relaxed);
624 GetVisitedMethods(final_offset, &visited_methods);
625 }
626
627 // Compute elapsed time.
628 uint64_t elapsed = MicroTime() - start_time_;
629
630 std::ostringstream os;
631
632 os << StringPrintf("%cversion\n", kTraceTokenChar);
633 os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
634 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
635 if (UseThreadCpuClock()) {
636 if (UseWallClock()) {
637 os << StringPrintf("clock=dual\n");
638 } else {
639 os << StringPrintf("clock=thread-cpu\n");
640 }
641 } else {
642 os << StringPrintf("clock=wall\n");
643 }
644 os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
645 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
646 size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
647 os << StringPrintf("num-method-calls=%zd\n", num_records);
648 }
649 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns_);
650 os << StringPrintf("vm=art\n");
651 os << StringPrintf("pid=%d\n", getpid());
652 if ((flags_ & kTraceCountAllocs) != 0) {
653 os << "alloc-count=" << Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS) << "\n";
654 os << "alloc-size=" << Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES) << "\n";
655 os << "gc-count=" << Runtime::Current()->GetStat(KIND_GC_INVOCATIONS) << "\n";
656 }
657 os << StringPrintf("%cthreads\n", kTraceTokenChar);
658 DumpThreadList(os);
659 os << StringPrintf("%cmethods\n", kTraceTokenChar);
660 DumpMethodList(os, visited_methods);
661 os << StringPrintf("%cend\n", kTraceTokenChar);
662 std::string header(os.str());
663
664 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
665 // Protect access to buf_ and satisfy sanitizer for calls to WriteBuf / FlushBuf.
666 MutexLock mu(Thread::Current(), *streaming_lock_);
667 // Write a special token to mark the end of trace records and the start of
668 // trace summary.
669 uint8_t buf[7];
670 Append2LE(buf, 0);
671 buf[2] = kOpTraceSummary;
672 Append4LE(buf + 3, static_cast<uint32_t>(header.length()));
673 WriteToBuf(buf, sizeof(buf));
674 // Write the trace summary. The summary is identical to the file header when
675 // the output mode is not streaming (except for methods).
676 WriteToBuf(reinterpret_cast<const uint8_t*>(header.c_str()), header.length());
677 // Flush the buffer, which may include some trace records before the summary.
678 FlushBuf();
679 } else {
680 if (trace_file_.get() == nullptr) {
681 std::vector<uint8_t> data;
682 data.resize(header.length() + final_offset);
683 memcpy(data.data(), header.c_str(), header.length());
684 memcpy(data.data() + header.length(), buf_.get(), final_offset);
685 Runtime::Current()->GetRuntimeCallbacks()->DdmPublishChunk(CHUNK_TYPE("MPSE"),
686 ArrayRef<const uint8_t>(data));
687 const bool kDumpTraceInfo = false;
688 if (kDumpTraceInfo) {
689 LOG(INFO) << "Trace sent:\n" << header;
690 DumpBuf(buf_.get(), final_offset, clock_source_);
691 }
692 } else {
693 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
694 !trace_file_->WriteFully(buf_.get(), final_offset)) {
695 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
696 PLOG(ERROR) << detail;
697 ThrowRuntimeException("%s", detail.c_str());
698 }
699 }
700 }
701 }
702
DexPcMoved(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t new_dex_pc)703 void Trace::DexPcMoved(Thread* thread ATTRIBUTE_UNUSED,
704 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
705 ArtMethod* method,
706 uint32_t new_dex_pc) {
707 // We're not recorded to listen to this kind of event, so complain.
708 LOG(ERROR) << "Unexpected dex PC event in tracing " << ArtMethod::PrettyMethod(method)
709 << " " << new_dex_pc;
710 }
711
FieldRead(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc,ArtField * field ATTRIBUTE_UNUSED)712 void Trace::FieldRead(Thread* thread ATTRIBUTE_UNUSED,
713 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
714 ArtMethod* method,
715 uint32_t dex_pc,
716 ArtField* field ATTRIBUTE_UNUSED)
717 REQUIRES_SHARED(Locks::mutator_lock_) {
718 // We're not recorded to listen to this kind of event, so complain.
719 LOG(ERROR) << "Unexpected field read event in tracing " << ArtMethod::PrettyMethod(method)
720 << " " << dex_pc;
721 }
722
FieldWritten(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc,ArtField * field ATTRIBUTE_UNUSED,const JValue & field_value ATTRIBUTE_UNUSED)723 void Trace::FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
724 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
725 ArtMethod* method,
726 uint32_t dex_pc,
727 ArtField* field ATTRIBUTE_UNUSED,
728 const JValue& field_value ATTRIBUTE_UNUSED)
729 REQUIRES_SHARED(Locks::mutator_lock_) {
730 // We're not recorded to listen to this kind of event, so complain.
731 LOG(ERROR) << "Unexpected field write event in tracing " << ArtMethod::PrettyMethod(method)
732 << " " << dex_pc;
733 }
734
MethodEntered(Thread * thread,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc ATTRIBUTE_UNUSED)735 void Trace::MethodEntered(Thread* thread,
736 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
737 ArtMethod* method,
738 uint32_t dex_pc ATTRIBUTE_UNUSED) {
739 uint32_t thread_clock_diff = 0;
740 uint32_t wall_clock_diff = 0;
741 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
742 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodEntered,
743 thread_clock_diff, wall_clock_diff);
744 }
745
MethodExited(Thread * thread,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc ATTRIBUTE_UNUSED,instrumentation::OptionalFrame frame ATTRIBUTE_UNUSED,JValue & return_value ATTRIBUTE_UNUSED)746 void Trace::MethodExited(Thread* thread,
747 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
748 ArtMethod* method,
749 uint32_t dex_pc ATTRIBUTE_UNUSED,
750 instrumentation::OptionalFrame frame ATTRIBUTE_UNUSED,
751 JValue& return_value ATTRIBUTE_UNUSED) {
752 uint32_t thread_clock_diff = 0;
753 uint32_t wall_clock_diff = 0;
754 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
755 LogMethodTraceEvent(thread,
756 method,
757 instrumentation::Instrumentation::kMethodExited,
758 thread_clock_diff,
759 wall_clock_diff);
760 }
761
MethodUnwind(Thread * thread,Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,ArtMethod * method,uint32_t dex_pc ATTRIBUTE_UNUSED)762 void Trace::MethodUnwind(Thread* thread,
763 Handle<mirror::Object> this_object ATTRIBUTE_UNUSED,
764 ArtMethod* method,
765 uint32_t dex_pc ATTRIBUTE_UNUSED) {
766 uint32_t thread_clock_diff = 0;
767 uint32_t wall_clock_diff = 0;
768 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
769 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
770 thread_clock_diff, wall_clock_diff);
771 }
772
ExceptionThrown(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Throwable> exception_object ATTRIBUTE_UNUSED)773 void Trace::ExceptionThrown(Thread* thread ATTRIBUTE_UNUSED,
774 Handle<mirror::Throwable> exception_object ATTRIBUTE_UNUSED)
775 REQUIRES_SHARED(Locks::mutator_lock_) {
776 LOG(ERROR) << "Unexpected exception thrown event in tracing";
777 }
778
ExceptionHandled(Thread * thread ATTRIBUTE_UNUSED,Handle<mirror::Throwable> exception_object ATTRIBUTE_UNUSED)779 void Trace::ExceptionHandled(Thread* thread ATTRIBUTE_UNUSED,
780 Handle<mirror::Throwable> exception_object ATTRIBUTE_UNUSED)
781 REQUIRES_SHARED(Locks::mutator_lock_) {
782 LOG(ERROR) << "Unexpected exception thrown event in tracing";
783 }
784
Branch(Thread *,ArtMethod * method,uint32_t,int32_t)785 void Trace::Branch(Thread* /*thread*/, ArtMethod* method,
786 uint32_t /*dex_pc*/, int32_t /*dex_pc_offset*/)
787 REQUIRES_SHARED(Locks::mutator_lock_) {
788 LOG(ERROR) << "Unexpected branch event in tracing" << ArtMethod::PrettyMethod(method);
789 }
790
WatchedFramePop(Thread * self ATTRIBUTE_UNUSED,const ShadowFrame & frame ATTRIBUTE_UNUSED)791 void Trace::WatchedFramePop(Thread* self ATTRIBUTE_UNUSED,
792 const ShadowFrame& frame ATTRIBUTE_UNUSED) {
793 LOG(ERROR) << "Unexpected WatchedFramePop event in tracing";
794 }
795
ReadClocks(Thread * thread,uint32_t * thread_clock_diff,uint32_t * wall_clock_diff)796 void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
797 if (UseThreadCpuClock()) {
798 uint64_t clock_base = thread->GetTraceClockBase();
799 if (UNLIKELY(clock_base == 0)) {
800 // First event, record the base time in the map.
801 uint64_t time = thread->GetCpuMicroTime();
802 thread->SetTraceClockBase(time);
803 } else {
804 *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
805 }
806 }
807 if (UseWallClock()) {
808 *wall_clock_diff = MicroTime() - start_time_;
809 }
810 }
811
RegisterMethod(ArtMethod * method)812 bool Trace::RegisterMethod(ArtMethod* method) {
813 const DexFile* dex_file = method->GetDexFile();
814 if (seen_methods_.find(dex_file) == seen_methods_.end()) {
815 seen_methods_.insert(std::make_pair(dex_file, new DexIndexBitSet()));
816 }
817 DexIndexBitSet* bit_set = seen_methods_.find(dex_file)->second;
818 if (!(*bit_set)[method->GetDexMethodIndex()]) {
819 bit_set->set(method->GetDexMethodIndex());
820 return true;
821 }
822 return false;
823 }
824
RegisterThread(Thread * thread)825 bool Trace::RegisterThread(Thread* thread) {
826 pid_t tid = thread->GetTid();
827 CHECK_LT(0U, static_cast<uint32_t>(tid));
828 CHECK_LT(static_cast<uint32_t>(tid), kMaxThreadIdNumber);
829
830 if (!(*seen_threads_)[tid]) {
831 seen_threads_->set(tid);
832 return true;
833 }
834 return false;
835 }
836
GetMethodLine(ArtMethod * method)837 std::string Trace::GetMethodLine(ArtMethod* method) {
838 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
839 return StringPrintf("%#x\t%s\t%s\t%s\t%s\n", (EncodeTraceMethod(method) << TraceActionBits),
840 PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
841 method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
842 }
843
WriteToBuf(const uint8_t * src,size_t src_size)844 void Trace::WriteToBuf(const uint8_t* src, size_t src_size) {
845 // Updates to cur_offset_ are done under the streaming_lock_ here as in streaming mode.
846 int32_t old_offset = cur_offset_.load(std::memory_order_relaxed);
847 int32_t new_offset = old_offset + static_cast<int32_t>(src_size);
848 if (dchecked_integral_cast<size_t>(new_offset) > buffer_size_) {
849 // Flush buffer.
850 if (!trace_file_->WriteFully(buf_.get(), old_offset)) {
851 PLOG(WARNING) << "Failed streaming a tracing event.";
852 }
853
854 // Check whether the data is too large for the buffer, then write immediately.
855 if (src_size >= buffer_size_) {
856 if (!trace_file_->WriteFully(src, src_size)) {
857 PLOG(WARNING) << "Failed streaming a tracing event.";
858 }
859 cur_offset_.store(0, std::memory_order_relaxed); // Buffer is empty now.
860 return;
861 }
862
863 old_offset = 0;
864 new_offset = static_cast<int32_t>(src_size);
865 }
866 cur_offset_.store(new_offset, std::memory_order_relaxed);
867 // Fill in data.
868 memcpy(buf_.get() + old_offset, src, src_size);
869 }
870
FlushBuf()871 void Trace::FlushBuf() {
872 // Updates to cur_offset_ are done under the streaming_lock_ here as in streaming mode.
873 int32_t offset = cur_offset_.load(std::memory_order_relaxed);
874 if (!trace_file_->WriteFully(buf_.get(), offset)) {
875 PLOG(WARNING) << "Failed flush the remaining data in streaming.";
876 }
877 cur_offset_.store(0, std::memory_order_relaxed);
878 }
879
LogMethodTraceEvent(Thread * thread,ArtMethod * method,instrumentation::Instrumentation::InstrumentationEvent event,uint32_t thread_clock_diff,uint32_t wall_clock_diff)880 void Trace::LogMethodTraceEvent(Thread* thread, ArtMethod* method,
881 instrumentation::Instrumentation::InstrumentationEvent event,
882 uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
883 // This method is called in both tracing modes (method and
884 // sampling). In sampling mode, this method is only called by the
885 // sampling thread. In method tracing mode, it can be called
886 // concurrently.
887
888 // Ensure we always use the non-obsolete version of the method so that entry/exit events have the
889 // same pointer value.
890 method = method->GetNonObsoleteMethod();
891
892 // Advance cur_offset_ atomically.
893 int32_t new_offset;
894 int32_t old_offset = 0;
895
896 // In the non-streaming case, we do a busy loop here trying to get
897 // an offset to write our record and advance cur_offset_ for the
898 // next use.
899 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
900 // Although multiple threads can call this method concurrently,
901 // the compare_exchange_weak here is still atomic (by definition).
902 // A succeeding update is visible to other cores when they pass
903 // through this point.
904 old_offset = cur_offset_.load(std::memory_order_relaxed); // Speculative read
905 do {
906 new_offset = old_offset + GetRecordSize(clock_source_);
907 if (static_cast<size_t>(new_offset) > buffer_size_) {
908 overflow_ = true;
909 return;
910 }
911 } while (!cur_offset_.compare_exchange_weak(old_offset, new_offset, std::memory_order_relaxed));
912 }
913
914 TraceAction action = kTraceMethodEnter;
915 switch (event) {
916 case instrumentation::Instrumentation::kMethodEntered:
917 action = kTraceMethodEnter;
918 break;
919 case instrumentation::Instrumentation::kMethodExited:
920 action = kTraceMethodExit;
921 break;
922 case instrumentation::Instrumentation::kMethodUnwind:
923 action = kTraceUnroll;
924 break;
925 default:
926 UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
927 }
928
929 uint32_t method_value = EncodeTraceMethodAndAction(method, action);
930
931 // Write data into the tracing buffer (if not streaming) or into a
932 // small buffer on the stack (if streaming) which we'll put into the
933 // tracing buffer below.
934 //
935 // These writes to the tracing buffer are synchronised with the
936 // future reads that (only) occur under FinishTracing(). The callers
937 // of FinishTracing() acquire locks and (implicitly) synchronise
938 // the buffer memory.
939 uint8_t* ptr;
940 static constexpr size_t kPacketSize = 14U; // The maximum size of data in a packet.
941 uint8_t stack_buf[kPacketSize]; // Space to store a packet when in streaming mode.
942 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
943 ptr = stack_buf;
944 } else {
945 ptr = buf_.get() + old_offset;
946 }
947
948 Append2LE(ptr, thread->GetTid());
949 Append4LE(ptr + 2, method_value);
950 ptr += 6;
951
952 if (UseThreadCpuClock()) {
953 Append4LE(ptr, thread_clock_diff);
954 ptr += 4;
955 }
956 if (UseWallClock()) {
957 Append4LE(ptr, wall_clock_diff);
958 }
959 static_assert(kPacketSize == 2 + 4 + 4 + 4, "Packet size incorrect.");
960
961 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
962 MutexLock mu(Thread::Current(), *streaming_lock_); // To serialize writing.
963 if (RegisterMethod(method)) {
964 // Write a special block with the name.
965 std::string method_line(GetMethodLine(method));
966 uint8_t buf2[5];
967 Append2LE(buf2, 0);
968 buf2[2] = kOpNewMethod;
969 Append2LE(buf2 + 3, static_cast<uint16_t>(method_line.length()));
970 WriteToBuf(buf2, sizeof(buf2));
971 WriteToBuf(reinterpret_cast<const uint8_t*>(method_line.c_str()), method_line.length());
972 }
973 if (RegisterThread(thread)) {
974 // It might be better to postpone this. Threads might not have received names...
975 std::string thread_name;
976 thread->GetThreadName(thread_name);
977 uint8_t buf2[7];
978 Append2LE(buf2, 0);
979 buf2[2] = kOpNewThread;
980 Append2LE(buf2 + 3, static_cast<uint16_t>(thread->GetTid()));
981 Append2LE(buf2 + 5, static_cast<uint16_t>(thread_name.length()));
982 WriteToBuf(buf2, sizeof(buf2));
983 WriteToBuf(reinterpret_cast<const uint8_t*>(thread_name.c_str()), thread_name.length());
984 }
985 WriteToBuf(stack_buf, sizeof(stack_buf));
986 }
987 }
988
GetVisitedMethods(size_t buf_size,std::set<ArtMethod * > * visited_methods)989 void Trace::GetVisitedMethods(size_t buf_size,
990 std::set<ArtMethod*>* visited_methods) {
991 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
992 uint8_t* end = buf_.get() + buf_size;
993
994 while (ptr < end) {
995 uint32_t tmid = ReadBytes(ptr + 2, sizeof(tmid));
996 ArtMethod* method = DecodeTraceMethod(tmid);
997 visited_methods->insert(method);
998 ptr += GetRecordSize(clock_source_);
999 }
1000 }
1001
DumpMethodList(std::ostream & os,const std::set<ArtMethod * > & visited_methods)1002 void Trace::DumpMethodList(std::ostream& os, const std::set<ArtMethod*>& visited_methods) {
1003 for (const auto& method : visited_methods) {
1004 os << GetMethodLine(method);
1005 }
1006 }
1007
DumpThread(Thread * t,void * arg)1008 static void DumpThread(Thread* t, void* arg) {
1009 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
1010 std::string name;
1011 t->GetThreadName(name);
1012 os << t->GetTid() << "\t" << name << "\n";
1013 }
1014
DumpThreadList(std::ostream & os)1015 void Trace::DumpThreadList(std::ostream& os) {
1016 Thread* self = Thread::Current();
1017 for (const auto& it : exited_threads_) {
1018 os << it.first << "\t" << it.second << "\n";
1019 }
1020 Locks::thread_list_lock_->AssertNotHeld(self);
1021 MutexLock mu(self, *Locks::thread_list_lock_);
1022 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
1023 }
1024
StoreExitingThreadInfo(Thread * thread)1025 void Trace::StoreExitingThreadInfo(Thread* thread) {
1026 MutexLock mu(thread, *Locks::trace_lock_);
1027 if (the_trace_ != nullptr) {
1028 std::string name;
1029 thread->GetThreadName(name);
1030 // The same thread/tid may be used multiple times. As SafeMap::Put does not allow to override
1031 // a previous mapping, use SafeMap::Overwrite.
1032 the_trace_->exited_threads_.Overwrite(thread->GetTid(), name);
1033 }
1034 }
1035
GetOutputMode()1036 Trace::TraceOutputMode Trace::GetOutputMode() {
1037 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1038 CHECK(the_trace_ != nullptr) << "Trace output mode requested, but no trace currently running";
1039 return the_trace_->trace_output_mode_;
1040 }
1041
GetMode()1042 Trace::TraceMode Trace::GetMode() {
1043 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1044 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1045 return the_trace_->trace_mode_;
1046 }
1047
GetBufferSize()1048 size_t Trace::GetBufferSize() {
1049 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1050 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1051 return the_trace_->buffer_size_;
1052 }
1053
IsTracingEnabled()1054 bool Trace::IsTracingEnabled() {
1055 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1056 return the_trace_ != nullptr;
1057 }
1058
1059 } // namespace art
1060