blob: 1e15960e395b82282d9207b133cab15977ac1981 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
jeffhaoe343b762011-12-05 16:36:44 -080016
17#include "trace.h"
18
jeffhaoa9ef3fd2011-12-13 18:33:43 -080019#include <sys/uio.h>
John Reck0624a272015-03-26 15:47:54 -070020#include <unistd.h>
jeffhaoa9ef3fd2011-12-13 18:33:43 -080021
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampee34a42c2015-04-25 14:44:29 -070023#include "base/casts.h"
Jeff Hao0abc72e2013-08-13 13:45:14 -070024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080027#include "base/unix_file/fd_file.h"
jeffhaoe343b762011-12-05 16:36:44 -080028#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080029#include "common_throws.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080030#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070031#include "dex_file-inl.h"
Mathieu Chartieraa516822015-10-02 15:53:37 -070032#include "gc/scoped_gc_critical_section.h"
jeffhao725a9572012-11-13 18:20:12 -080033#include "instrumentation.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/class-inl.h"
Andreas Gampe40da2862015-02-27 12:49:04 -080035#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/object_array-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "mirror/object-inl.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080038#include "os.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070039#include "scoped_thread_state_change.h"
Jeff Hao0abc72e2013-08-13 13:45:14 -070040#include "ScopedLocalRef.h"
jeffhaoe343b762011-12-05 16:36:44 -080041#include "thread.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070042#include "thread_list.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "utils.h"
Ian Rogers166db042013-07-26 12:05:57 -070044#include "entrypoints/quick/quick_entrypoints.h"
jeffhao2692b572011-12-16 15:42:28 -080045
46namespace art {
47
Mathieu Chartier4d64cd42015-06-02 16:38:29 -070048static constexpr size_t TraceActionBits = MinimumBitsToStore(
49 static_cast<size_t>(kTraceMethodActionMask));
Andreas Gampe40da2862015-02-27 12:49:04 -080050static constexpr uint8_t kOpNewMethod = 1U;
51static constexpr uint8_t kOpNewThread = 2U;
52
Jeff Hao0abc72e2013-08-13 13:45:14 -070053class BuildStackTraceVisitor : public StackVisitor {
54 public:
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +010055 explicit BuildStackTraceVisitor(Thread* thread)
56 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
57 method_trace_(Trace::AllocStackTrace()) {}
Jeff Hao0abc72e2013-08-13 13:45:14 -070058
Mathieu Chartier90443472015-07-16 20:32:27 -070059 bool VisitFrame() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -070060 ArtMethod* m = GetMethod();
Jeff Hao0abc72e2013-08-13 13:45:14 -070061 // Ignore runtime frames (in particular callee save).
62 if (!m->IsRuntimeMethod()) {
63 method_trace_->push_back(m);
64 }
65 return true;
66 }
67
68 // Returns a stack trace where the topmost frame corresponds with the first element of the vector.
Mathieu Chartiere401d142015-04-22 13:56:20 -070069 std::vector<ArtMethod*>* GetStackTrace() const {
Jeff Hao0abc72e2013-08-13 13:45:14 -070070 return method_trace_;
71 }
72
73 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -070074 std::vector<ArtMethod*>* const method_trace_;
Sebastien Hertz26f72862015-09-15 09:52:07 +020075
76 DISALLOW_COPY_AND_ASSIGN(BuildStackTraceVisitor);
Jeff Hao0abc72e2013-08-13 13:45:14 -070077};
78
jeffhaoa9ef3fd2011-12-13 18:33:43 -080079static const char kTraceTokenChar = '*';
80static const uint16_t kTraceHeaderLength = 32;
81static const uint32_t kTraceMagicValue = 0x574f4c53;
82static const uint16_t kTraceVersionSingleClock = 2;
83static const uint16_t kTraceVersionDualClock = 3;
Mathieu Chartier4d64cd42015-06-02 16:38:29 -070084static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
85static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
jeffhaoa9ef3fd2011-12-13 18:33:43 -080086
Ian Rogerse63db272014-07-15 15:36:11 -070087TraceClockSource Trace::default_clock_source_ = kDefaultTraceClockSource;
Elliott Hughese119a362012-05-22 17:37:06 -070088
Andreas Gampe40da2862015-02-27 12:49:04 -080089Trace* volatile Trace::the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -070090pthread_t Trace::sampling_pthread_ = 0U;
Mathieu Chartiere401d142015-04-22 13:56:20 -070091std::unique_ptr<std::vector<ArtMethod*>> Trace::temp_stack_trace_;
Ian Rogers62d6c772013-02-27 08:32:07 -080092
Sebastien Hertz0462c4c2015-04-01 16:34:17 +020093// The key identifying the tracer to update instrumentation.
94static constexpr const char* kTracerInstrumentationKey = "Tracer";
95
Ian Rogers62d6c772013-02-27 08:32:07 -080096static TraceAction DecodeTraceAction(uint32_t tmid) {
97 return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
98}
99
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700100ArtMethod* Trace::DecodeTraceMethod(uint32_t tmid) {
101 MutexLock mu(Thread::Current(), *unique_methods_lock_);
102 return unique_methods_[tmid >> TraceActionBits];
103}
104
105uint32_t Trace::EncodeTraceMethod(ArtMethod* method) {
106 MutexLock mu(Thread::Current(), *unique_methods_lock_);
107 uint32_t idx;
108 auto it = art_method_id_map_.find(method);
109 if (it != art_method_id_map_.end()) {
110 idx = it->second;
111 } else {
112 unique_methods_.push_back(method);
113 idx = unique_methods_.size() - 1;
114 art_method_id_map_.emplace(method, idx);
115 }
116 DCHECK_LT(idx, unique_methods_.size());
117 DCHECK_EQ(unique_methods_[idx], method);
118 return idx;
119}
120
121uint32_t Trace::EncodeTraceMethodAndAction(ArtMethod* method, TraceAction action) {
122 uint32_t tmid = (EncodeTraceMethod(method) << TraceActionBits) | action;
123 DCHECK_EQ(method, DecodeTraceMethod(tmid));
Ian Rogers62d6c772013-02-27 08:32:07 -0800124 return tmid;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800125}
126
Mathieu Chartiere401d142015-04-22 13:56:20 -0700127std::vector<ArtMethod*>* Trace::AllocStackTrace() {
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700128 return (temp_stack_trace_.get() != nullptr) ? temp_stack_trace_.release() :
129 new std::vector<ArtMethod*>();
Jeff Hao5ce4b172013-08-16 16:27:18 -0700130}
131
Mathieu Chartiere401d142015-04-22 13:56:20 -0700132void Trace::FreeStackTrace(std::vector<ArtMethod*>* stack_trace) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700133 stack_trace->clear();
134 temp_stack_trace_.reset(stack_trace);
135}
136
Ian Rogerse63db272014-07-15 15:36:11 -0700137void Trace::SetDefaultClockSource(TraceClockSource clock_source) {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800138#if defined(__linux__)
Ian Rogers62d6c772013-02-27 08:32:07 -0800139 default_clock_source_ = clock_source;
140#else
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800141 if (clock_source != TraceClockSource::kWall) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700142 LOG(WARNING) << "Ignoring tracing request to use CPU time.";
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 }
144#endif
145}
146
Ian Rogerse63db272014-07-15 15:36:11 -0700147static uint16_t GetTraceVersion(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800148 return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800149 : kTraceVersionSingleClock;
150}
151
Ian Rogerse63db272014-07-15 15:36:11 -0700152static uint16_t GetRecordSize(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800153 return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800154 : kTraceRecordSizeSingleClock;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800155}
156
Elliott Hughese119a362012-05-22 17:37:06 -0700157bool Trace::UseThreadCpuClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800158 return (clock_source_ == TraceClockSource::kThreadCpu) ||
159 (clock_source_ == TraceClockSource::kDual);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800160}
161
Elliott Hughese119a362012-05-22 17:37:06 -0700162bool Trace::UseWallClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800163 return (clock_source_ == TraceClockSource::kWall) ||
164 (clock_source_ == TraceClockSource::kDual);
Elliott Hughese119a362012-05-22 17:37:06 -0700165}
166
Jeff Haoc5d824a2014-07-28 18:35:38 -0700167void Trace::MeasureClockOverhead() {
168 if (UseThreadCpuClock()) {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700169 Thread::Current()->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700171 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800172 MicroTime();
173 }
174}
175
Jeff Hao5ce4b172013-08-16 16:27:18 -0700176// Compute an average time taken to measure clocks.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700177uint32_t Trace::GetClockOverheadNanoSeconds() {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700178 Thread* self = Thread::Current();
179 uint64_t start = self->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800180
181 for (int i = 4000; i > 0; i--) {
Jeff Haoc5d824a2014-07-28 18:35:38 -0700182 MeasureClockOverhead();
183 MeasureClockOverhead();
184 MeasureClockOverhead();
185 MeasureClockOverhead();
186 MeasureClockOverhead();
187 MeasureClockOverhead();
188 MeasureClockOverhead();
189 MeasureClockOverhead();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800190 }
191
Jeff Hao5ce4b172013-08-16 16:27:18 -0700192 uint64_t elapsed_us = self->GetCpuMicroTime() - start;
193 return static_cast<uint32_t>(elapsed_us / 32);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800194}
195
Elliott Hughesffb465f2012-03-01 18:46:05 -0800196// TODO: put this somewhere with the big-endian equivalent used by JDWP.
197static void Append2LE(uint8_t* buf, uint16_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700198 *buf++ = static_cast<uint8_t>(val);
199 *buf++ = static_cast<uint8_t>(val >> 8);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800200}
201
Elliott Hughesffb465f2012-03-01 18:46:05 -0800202// TODO: put this somewhere with the big-endian equivalent used by JDWP.
203static void Append4LE(uint8_t* buf, uint32_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700204 *buf++ = static_cast<uint8_t>(val);
205 *buf++ = static_cast<uint8_t>(val >> 8);
206 *buf++ = static_cast<uint8_t>(val >> 16);
207 *buf++ = static_cast<uint8_t>(val >> 24);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800208}
209
Elliott Hughesffb465f2012-03-01 18:46:05 -0800210// TODO: put this somewhere with the big-endian equivalent used by JDWP.
211static void Append8LE(uint8_t* buf, uint64_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700212 *buf++ = static_cast<uint8_t>(val);
213 *buf++ = static_cast<uint8_t>(val >> 8);
214 *buf++ = static_cast<uint8_t>(val >> 16);
215 *buf++ = static_cast<uint8_t>(val >> 24);
216 *buf++ = static_cast<uint8_t>(val >> 32);
217 *buf++ = static_cast<uint8_t>(val >> 40);
218 *buf++ = static_cast<uint8_t>(val >> 48);
219 *buf++ = static_cast<uint8_t>(val >> 56);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800220}
221
Mathieu Chartier90443472015-07-16 20:32:27 -0700222static void GetSample(Thread* thread, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700223 BuildStackTraceVisitor build_trace_visitor(thread);
224 build_trace_visitor.WalkStack();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700225 std::vector<ArtMethod*>* stack_trace = build_trace_visitor.GetStackTrace();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700226 Trace* the_trace = reinterpret_cast<Trace*>(arg);
227 the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
228}
229
Andreas Gampeca714582015-04-03 19:41:34 -0700230static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700231 thread->SetTraceClockBase(0);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700232 std::vector<ArtMethod*>* stack_trace = thread->GetStackTraceSample();
Andreas Gampe40da2862015-02-27 12:49:04 -0800233 thread->SetStackTraceSample(nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700234 delete stack_trace;
235}
236
Jeff Hao0abc72e2013-08-13 13:45:14 -0700237void Trace::CompareAndUpdateStackTrace(Thread* thread,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700238 std::vector<ArtMethod*>* stack_trace) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700239 CHECK_EQ(pthread_self(), sampling_pthread_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700240 std::vector<ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
Jeff Hao5ce4b172013-08-16 16:27:18 -0700241 // Update the thread's stack trace sample.
242 thread->SetStackTraceSample(stack_trace);
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700243 // Read timer clocks to use for all events in this trace.
244 uint32_t thread_clock_diff = 0;
245 uint32_t wall_clock_diff = 0;
246 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
Andreas Gampe40da2862015-02-27 12:49:04 -0800247 if (old_stack_trace == nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700248 // If there's no previous stack trace sample for this thread, log an entry event for all
Jeff Hao0abc72e2013-08-13 13:45:14 -0700249 // methods in the trace.
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700250 for (auto rit = stack_trace->rbegin(); rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700251 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
252 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700253 }
254 } else {
255 // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
256 // events accordingly.
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700257 auto old_rit = old_stack_trace->rbegin();
258 auto rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700259 // Iterate bottom-up over both traces until there's a difference between them.
260 while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
261 old_rit++;
262 rit++;
263 }
264 // Iterate top-down over the old trace until the point where they differ, emitting exit events.
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700265 for (auto old_it = old_stack_trace->begin(); old_it != old_rit.base(); ++old_it) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700266 LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
267 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700268 }
269 // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
270 for (; rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700271 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
272 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700273 }
Jeff Hao5ce4b172013-08-16 16:27:18 -0700274 FreeStackTrace(old_stack_trace);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700275 }
276}
277
278void* Trace::RunSamplingThread(void* arg) {
279 Runtime* runtime = Runtime::Current();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800280 intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
Jeff Hao4044bda2014-01-06 15:50:45 -0800281 CHECK_GE(interval_us, 0);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700282 CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800283 !runtime->IsAotCompiler()));
Jeff Hao0abc72e2013-08-13 13:45:14 -0700284
285 while (true) {
Jeff Hao23009dc2013-08-22 15:36:42 -0700286 usleep(interval_us);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800287 ScopedTrace trace("Profile sampling");
Jeff Hao0abc72e2013-08-13 13:45:14 -0700288 Thread* self = Thread::Current();
289 Trace* the_trace;
290 {
291 MutexLock mu(self, *Locks::trace_lock_);
292 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800293 if (the_trace == nullptr) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700294 break;
295 }
296 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700297 {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700298 ScopedSuspendAll ssa(__FUNCTION__);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700299 MutexLock mu(self, *Locks::thread_list_lock_);
300 runtime->GetThreadList()->ForEach(GetSample, the_trace);
301 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700302 }
303
304 runtime->DetachCurrentThread();
Andreas Gampe40da2862015-02-27 12:49:04 -0800305 return nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700306}
307
Andreas Gampee34a42c2015-04-25 14:44:29 -0700308void Trace::Start(const char* trace_filename, int trace_fd, size_t buffer_size, int flags,
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700309 TraceOutputMode output_mode, TraceMode trace_mode, int interval_us) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800310 Thread* self = Thread::Current();
311 {
312 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800313 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800314 LOG(ERROR) << "Trace already in progress, ignoring this request";
315 return;
316 }
jeffhaoe343b762011-12-05 16:36:44 -0800317 }
Jeff Haod063d912014-09-08 09:38:18 -0700318
319 // Check interval if sampling is enabled
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700320 if (trace_mode == TraceMode::kSampling && interval_us <= 0) {
Jeff Haod063d912014-09-08 09:38:18 -0700321 LOG(ERROR) << "Invalid sampling interval: " << interval_us;
322 ScopedObjectAccess soa(self);
323 ThrowRuntimeException("Invalid sampling interval: %d", interval_us);
324 return;
325 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800326
jeffhao2692b572011-12-16 15:42:28 -0800327 // Open trace file if not going directly to ddms.
Ian Rogers700a4022014-05-19 16:49:03 -0700328 std::unique_ptr<File> trace_file;
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700329 if (output_mode != TraceOutputMode::kDDMS) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800330 if (trace_fd < 0) {
Calin Juravlef83e7332015-11-04 16:16:47 +0000331 trace_file.reset(OS::CreateEmptyFileWriteOnly(trace_filename));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800332 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800333 trace_file.reset(new File(trace_fd, "tracefile"));
Elliott Hughes76160052012-12-12 16:31:20 -0800334 trace_file->DisableAutoClose();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800335 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800336 if (trace_file.get() == nullptr) {
jeffhaob5e81852012-03-12 11:15:45 -0700337 PLOG(ERROR) << "Unable to open trace file '" << trace_filename << "'";
Ian Rogers62d6c772013-02-27 08:32:07 -0800338 ScopedObjectAccess soa(self);
339 ThrowRuntimeException("Unable to open trace file '%s'", trace_filename);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800340 return;
341 }
342 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800343
Jeff Haod063d912014-09-08 09:38:18 -0700344 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700345
346 // Enable count of allocs if specified in the flags.
347 bool enable_stats = false;
348
jeffhao2692b572011-12-16 15:42:28 -0800349 // Create Trace object.
Ian Rogers62d6c772013-02-27 08:32:07 -0800350 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700351 // Required since EnableMethodTracing calls ConfigureStubs which visits class linker classes.
352 gc::ScopedGCCriticalSection gcs(self,
353 gc::kGcCauseInstrumentation,
354 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700355 ScopedSuspendAll ssa(__FUNCTION__);
Ian Rogers62d6c772013-02-27 08:32:07 -0800356 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800357 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800358 LOG(ERROR) << "Trace already in progress, ignoring this request";
359 } else {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700360 enable_stats = (flags && kTraceCountAllocs) != 0;
Andreas Gampe40da2862015-02-27 12:49:04 -0800361 the_trace_ = new Trace(trace_file.release(), trace_filename, buffer_size, flags, output_mode,
362 trace_mode);
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700363 if (trace_mode == TraceMode::kSampling) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800364 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
Jeff Hao23009dc2013-08-22 15:36:42 -0700365 reinterpret_cast<void*>(interval_us)),
366 "Sampling profiler thread");
Andreas Gampe40da2862015-02-27 12:49:04 -0800367 the_trace_->interval_us_ = interval_us;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700368 } else {
369 runtime->GetInstrumentation()->AddListener(the_trace_,
370 instrumentation::Instrumentation::kMethodEntered |
371 instrumentation::Instrumentation::kMethodExited |
372 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe40da2862015-02-27 12:49:04 -0800373 // TODO: In full-PIC mode, we don't need to fully deopt.
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200374 runtime->GetInstrumentation()->EnableMethodTracing(kTracerInstrumentationKey);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700375 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800376 }
jeffhao0791adc2012-04-04 11:14:32 -0700377 }
Jeff Haod063d912014-09-08 09:38:18 -0700378
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700379 // Can't call this when holding the mutator lock.
380 if (enable_stats) {
381 runtime->SetStatsEnabled(true);
382 }
jeffhao2692b572011-12-16 15:42:28 -0800383}
384
Andreas Gampe40da2862015-02-27 12:49:04 -0800385void Trace::StopTracing(bool finish_tracing, bool flush_file) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700386 bool stop_alloc_counting = false;
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700387 Runtime* const runtime = Runtime::Current();
388 Trace* the_trace = nullptr;
Hiroshi Yamauchi9ea02c42016-03-03 15:09:27 -0800389 Thread* const self = Thread::Current();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700390 pthread_t sampling_pthread = 0U;
Ian Rogers62d6c772013-02-27 08:32:07 -0800391 {
Hiroshi Yamauchi9ea02c42016-03-03 15:09:27 -0800392 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800393 if (the_trace_ == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800394 LOG(ERROR) << "Trace stop requested, but no trace currently running";
395 } else {
396 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800397 the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700398 sampling_pthread = sampling_pthread_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800399 }
jeffhao2692b572011-12-16 15:42:28 -0800400 }
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700401 // Make sure that we join before we delete the trace since we don't want to have
402 // the sampling thread access a stale pointer. This finishes since the sampling thread exits when
403 // the_trace_ is null.
404 if (sampling_pthread != 0U) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800405 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700406 sampling_pthread_ = 0U;
407 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800408
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700409 {
Hiroshi Yamauchi9ea02c42016-03-03 15:09:27 -0800410 gc::ScopedGCCriticalSection gcs(self,
411 gc::kGcCauseInstrumentation,
412 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700413 ScopedSuspendAll ssa(__FUNCTION__);
414 if (the_trace != nullptr) {
415 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
416 if (finish_tracing) {
417 the_trace->FinishTracing();
418 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700419
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700420 if (the_trace->trace_mode_ == TraceMode::kSampling) {
Hiroshi Yamauchi9ea02c42016-03-03 15:09:27 -0800421 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700422 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
Andreas Gampe40da2862015-02-27 12:49:04 -0800423 } else {
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700424 runtime->GetInstrumentation()->DisableMethodTracing(kTracerInstrumentationKey);
425 runtime->GetInstrumentation()->RemoveListener(
426 the_trace, instrumentation::Instrumentation::kMethodEntered |
427 instrumentation::Instrumentation::kMethodExited |
428 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe4303ba92014-11-06 01:00:46 -0800429 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700430 if (the_trace->trace_file_.get() != nullptr) {
431 // Do not try to erase, so flush and close explicitly.
432 if (flush_file) {
433 if (the_trace->trace_file_->Flush() != 0) {
434 PLOG(WARNING) << "Could not flush trace file.";
435 }
436 } else {
437 the_trace->trace_file_->MarkUnchecked(); // Do not trigger guard.
438 }
439 if (the_trace->trace_file_->Close() != 0) {
440 PLOG(ERROR) << "Could not close trace file.";
441 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800442 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700443 delete the_trace;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800444 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800445 }
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700446 if (stop_alloc_counting) {
447 // Can be racy since SetStatsEnabled is not guarded by any locks.
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700448 runtime->SetStatsEnabled(false);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700449 }
jeffhao2692b572011-12-16 15:42:28 -0800450}
451
Andreas Gampe40da2862015-02-27 12:49:04 -0800452void Trace::Abort() {
453 // Do not write anything anymore.
454 StopTracing(false, false);
455}
456
457void Trace::Stop() {
458 // Finish writing.
459 StopTracing(true, true);
460}
461
jeffhaob5e81852012-03-12 11:15:45 -0700462void Trace::Shutdown() {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700463 if (GetMethodTracingMode() != kTracingInactive) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800464 Stop();
jeffhaob5e81852012-03-12 11:15:45 -0700465 }
jeffhaob5e81852012-03-12 11:15:45 -0700466}
467
Andreas Gampe40da2862015-02-27 12:49:04 -0800468void Trace::Pause() {
469 bool stop_alloc_counting = false;
470 Runtime* runtime = Runtime::Current();
471 Trace* the_trace = nullptr;
472
Mathieu Chartieraa516822015-10-02 15:53:37 -0700473 Thread* const self = Thread::Current();
Andreas Gampe40da2862015-02-27 12:49:04 -0800474 pthread_t sampling_pthread = 0U;
475 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700476 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800477 if (the_trace_ == nullptr) {
478 LOG(ERROR) << "Trace pause requested, but no trace currently running";
479 return;
480 } else {
481 the_trace = the_trace_;
482 sampling_pthread = sampling_pthread_;
483 }
484 }
485
486 if (sampling_pthread != 0U) {
487 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700488 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800489 the_trace_ = nullptr;
490 }
491 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
492 sampling_pthread_ = 0U;
493 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700494 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800495 the_trace_ = the_trace;
496 }
497 }
498
499 if (the_trace != nullptr) {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700500 gc::ScopedGCCriticalSection gcs(self,
501 gc::kGcCauseInstrumentation,
502 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700503 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampe40da2862015-02-27 12:49:04 -0800504 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
505
506 if (the_trace->trace_mode_ == TraceMode::kSampling) {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700507 MutexLock mu(self, *Locks::thread_list_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800508 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
509 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200510 runtime->GetInstrumentation()->DisableMethodTracing(kTracerInstrumentationKey);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700511 runtime->GetInstrumentation()->RemoveListener(
512 the_trace,
513 instrumentation::Instrumentation::kMethodEntered |
514 instrumentation::Instrumentation::kMethodExited |
515 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe40da2862015-02-27 12:49:04 -0800516 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800517 }
518
519 if (stop_alloc_counting) {
520 // Can be racy since SetStatsEnabled is not guarded by any locks.
521 Runtime::Current()->SetStatsEnabled(false);
522 }
523}
524
525void Trace::Resume() {
526 Thread* self = Thread::Current();
527 Trace* the_trace;
528 {
529 MutexLock mu(self, *Locks::trace_lock_);
530 if (the_trace_ == nullptr) {
531 LOG(ERROR) << "No trace to resume (or sampling mode), ignoring this request";
532 return;
533 }
534 the_trace = the_trace_;
535 }
536
537 Runtime* runtime = Runtime::Current();
538
539 // Enable count of allocs if specified in the flags.
540 bool enable_stats = (the_trace->flags_ && kTraceCountAllocs) != 0;
541
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700542 {
Mathieu Chartieraa516822015-10-02 15:53:37 -0700543 gc::ScopedGCCriticalSection gcs(self,
544 gc::kGcCauseInstrumentation,
545 gc::kCollectorTypeInstrumentation);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700546 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampe40da2862015-02-27 12:49:04 -0800547
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700548 // Reenable.
549 if (the_trace->trace_mode_ == TraceMode::kSampling) {
550 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
551 reinterpret_cast<void*>(the_trace->interval_us_)), "Sampling profiler thread");
552 } else {
553 runtime->GetInstrumentation()->AddListener(the_trace,
554 instrumentation::Instrumentation::kMethodEntered |
555 instrumentation::Instrumentation::kMethodExited |
556 instrumentation::Instrumentation::kMethodUnwind);
557 // TODO: In full-PIC mode, we don't need to fully deopt.
558 runtime->GetInstrumentation()->EnableMethodTracing(kTracerInstrumentationKey);
559 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800560 }
561
Andreas Gampe40da2862015-02-27 12:49:04 -0800562 // Can't call this when holding the mutator lock.
563 if (enable_stats) {
564 runtime->SetStatsEnabled(true);
565 }
566}
567
Jeff Hao64caa7d2013-08-29 11:18:01 -0700568TracingMode Trace::GetMethodTracingMode() {
Ian Rogers62d6c772013-02-27 08:32:07 -0800569 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800570 if (the_trace_ == nullptr) {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700571 return kTracingInactive;
Jeff Hao64caa7d2013-08-29 11:18:01 -0700572 } else {
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700573 switch (the_trace_->trace_mode_) {
574 case TraceMode::kSampling:
575 return kSampleProfilingActive;
576 case TraceMode::kMethodTracing:
577 return kMethodTracingActive;
578 }
579 LOG(FATAL) << "Unreachable";
580 UNREACHABLE();
Jeff Hao64caa7d2013-08-29 11:18:01 -0700581 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800582}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800583
Andreas Gampee34a42c2015-04-25 14:44:29 -0700584static constexpr size_t kMinBufSize = 18U; // Trace header is up to 18B.
Andreas Gampe40da2862015-02-27 12:49:04 -0800585
Andreas Gampee34a42c2015-04-25 14:44:29 -0700586Trace::Trace(File* trace_file, const char* trace_name, size_t buffer_size, int flags,
Andreas Gampe40da2862015-02-27 12:49:04 -0800587 TraceOutputMode output_mode, TraceMode trace_mode)
588 : trace_file_(trace_file),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700589 buf_(new uint8_t[std::max(kMinBufSize, buffer_size)]()),
Andreas Gampe40da2862015-02-27 12:49:04 -0800590 flags_(flags), trace_output_mode_(output_mode), trace_mode_(trace_mode),
591 clock_source_(default_clock_source_),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700592 buffer_size_(std::max(kMinBufSize, buffer_size)),
Andreas Gampe40da2862015-02-27 12:49:04 -0800593 start_time_(MicroTime()), clock_overhead_ns_(GetClockOverheadNanoSeconds()), cur_offset_(0),
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700594 overflow_(false), interval_us_(0), streaming_lock_(nullptr),
Andreas Gampe7526d782015-06-22 22:53:45 -0700595 unique_methods_lock_(new Mutex("unique methods lock", kTracingUniqueMethodsLock)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800596 uint16_t trace_version = GetTraceVersion(clock_source_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800597 if (output_mode == TraceOutputMode::kStreaming) {
598 trace_version |= 0xF0U;
599 }
600 // Set up the beginning of the trace.
jeffhao2692b572011-12-16 15:42:28 -0800601 memset(buf_.get(), 0, kTraceHeaderLength);
602 Append4LE(buf_.get(), kTraceMagicValue);
Ian Rogers62d6c772013-02-27 08:32:07 -0800603 Append2LE(buf_.get() + 4, trace_version);
jeffhao2692b572011-12-16 15:42:28 -0800604 Append2LE(buf_.get() + 6, kTraceHeaderLength);
605 Append8LE(buf_.get() + 8, start_time_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800606 if (trace_version >= kTraceVersionDualClock) {
607 uint16_t record_size = GetRecordSize(clock_source_);
608 Append2LE(buf_.get() + 16, record_size);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800609 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700610 static_assert(18 <= kMinBufSize, "Minimum buffer size not large enough for trace header");
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800611
jeffhao2692b572011-12-16 15:42:28 -0800612 // Update current offset.
Ian Rogers8ab25ef2014-07-09 18:00:50 -0700613 cur_offset_.StoreRelaxed(kTraceHeaderLength);
Andreas Gampe40da2862015-02-27 12:49:04 -0800614
615 if (output_mode == TraceOutputMode::kStreaming) {
616 streaming_file_name_ = trace_name;
Andreas Gampe7526d782015-06-22 22:53:45 -0700617 streaming_lock_ = new Mutex("tracing lock", LockLevel::kTracingStreamingLock);
Andreas Gampe40da2862015-02-27 12:49:04 -0800618 seen_threads_.reset(new ThreadIDBitSet());
619 }
620}
621
622Trace::~Trace() {
623 delete streaming_lock_;
Andreas Gampe7526d782015-06-22 22:53:45 -0700624 delete unique_methods_lock_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800625}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800626
Mathieu Chartiere401d142015-04-22 13:56:20 -0700627static uint64_t ReadBytes(uint8_t* buf, size_t bytes) {
628 uint64_t ret = 0;
629 for (size_t i = 0; i < bytes; ++i) {
630 ret |= static_cast<uint64_t>(buf[i]) << (i * 8);
631 }
632 return ret;
633}
634
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700635void Trace::DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800636 uint8_t* ptr = buf + kTraceHeaderLength;
637 uint8_t* end = buf + buf_size;
638
639 while (ptr < end) {
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700640 uint32_t tmid = ReadBytes(ptr + 2, sizeof(tmid));
641 ArtMethod* method = DecodeTraceMethod(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800642 TraceAction action = DecodeTraceAction(tmid);
643 LOG(INFO) << PrettyMethod(method) << " " << static_cast<int>(action);
644 ptr += GetRecordSize(clock_source);
645 }
jeffhaoe343b762011-12-05 16:36:44 -0800646}
647
Andreas Gampe40da2862015-02-27 12:49:04 -0800648void Trace::FinishTracing() {
649 size_t final_offset = 0;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800650
Mathieu Chartiere401d142015-04-22 13:56:20 -0700651 std::set<ArtMethod*> visited_methods;
Andreas Gampe40da2862015-02-27 12:49:04 -0800652 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800653 // Clean up.
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700654 STLDeleteValues(&seen_methods_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800655 } else {
656 final_offset = cur_offset_.LoadRelaxed();
657 GetVisitedMethods(final_offset, &visited_methods);
658 }
659
660 // Compute elapsed time.
661 uint64_t elapsed = MicroTime() - start_time_;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800662
663 std::ostringstream os;
664
665 os << StringPrintf("%cversion\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800666 os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800667 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
668 if (UseThreadCpuClock()) {
669 if (UseWallClock()) {
670 os << StringPrintf("clock=dual\n");
671 } else {
672 os << StringPrintf("clock=thread-cpu\n");
673 }
674 } else {
675 os << StringPrintf("clock=wall\n");
676 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800677 os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
Andreas Gampe40da2862015-02-27 12:49:04 -0800678 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
679 size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
680 os << StringPrintf("num-method-calls=%zd\n", num_records);
681 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700682 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800683 os << StringPrintf("vm=art\n");
John Reck0624a272015-03-26 15:47:54 -0700684 os << StringPrintf("pid=%d\n", getpid());
jeffhao0791adc2012-04-04 11:14:32 -0700685 if ((flags_ & kTraceCountAllocs) != 0) {
686 os << StringPrintf("alloc-count=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS));
687 os << StringPrintf("alloc-size=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES));
688 os << StringPrintf("gc-count=%d\n", Runtime::Current()->GetStat(KIND_GC_INVOCATIONS));
689 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800690 os << StringPrintf("%cthreads\n", kTraceTokenChar);
691 DumpThreadList(os);
692 os << StringPrintf("%cmethods\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800693 DumpMethodList(os, visited_methods);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800694 os << StringPrintf("%cend\n", kTraceTokenChar);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800695 std::string header(os.str());
Andreas Gampe40da2862015-02-27 12:49:04 -0800696
697 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
Andreas Gampedf878922015-08-13 16:44:54 -0700698 File file(streaming_file_name_ + ".sec", O_CREAT | O_WRONLY, true);
699 if (!file.IsOpened()) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800700 LOG(WARNING) << "Could not open secondary trace file!";
701 return;
Ian Rogers62d6c772013-02-27 08:32:07 -0800702 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800703 if (!file.WriteFully(header.c_str(), header.length())) {
704 file.Erase();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700705 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
706 PLOG(ERROR) << detail;
Ian Rogers62d6c772013-02-27 08:32:07 -0800707 ThrowRuntimeException("%s", detail.c_str());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800708 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800709 if (file.FlushCloseOrErase() != 0) {
710 PLOG(ERROR) << "Could not write secondary file";
711 }
712 } else {
713 if (trace_file_.get() == nullptr) {
714 iovec iov[2];
715 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
716 iov[0].iov_len = header.length();
717 iov[1].iov_base = buf_.get();
718 iov[1].iov_len = final_offset;
719 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
720 const bool kDumpTraceInfo = false;
721 if (kDumpTraceInfo) {
722 LOG(INFO) << "Trace sent:\n" << header;
723 DumpBuf(buf_.get(), final_offset, clock_source_);
724 }
725 } else {
726 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
727 !trace_file_->WriteFully(buf_.get(), final_offset)) {
728 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
729 PLOG(ERROR) << detail;
730 ThrowRuntimeException("%s", detail.c_str());
731 }
732 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800733 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800734}
735
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100736void Trace::DexPcMoved(Thread* thread ATTRIBUTE_UNUSED,
737 mirror::Object* this_object ATTRIBUTE_UNUSED,
738 ArtMethod* method,
739 uint32_t new_dex_pc) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800740 // We're not recorded to listen to this kind of event, so complain.
741 LOG(ERROR) << "Unexpected dex PC event in tracing " << PrettyMethod(method) << " " << new_dex_pc;
Andreas Gampec8ccf682014-09-29 20:07:43 -0700742}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800743
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100744void Trace::FieldRead(Thread* thread ATTRIBUTE_UNUSED,
745 mirror::Object* this_object ATTRIBUTE_UNUSED,
746 ArtMethod* method,
747 uint32_t dex_pc,
748 ArtField* field ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700749 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200750 // We're not recorded to listen to this kind of event, so complain.
751 LOG(ERROR) << "Unexpected field read event in tracing " << PrettyMethod(method) << " " << dex_pc;
752}
753
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100754void Trace::FieldWritten(Thread* thread ATTRIBUTE_UNUSED,
755 mirror::Object* this_object ATTRIBUTE_UNUSED,
756 ArtMethod* method,
757 uint32_t dex_pc,
758 ArtField* field ATTRIBUTE_UNUSED,
759 const JValue& field_value ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700760 SHARED_REQUIRES(Locks::mutator_lock_) {
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200761 // We're not recorded to listen to this kind of event, so complain.
762 LOG(ERROR) << "Unexpected field write event in tracing " << PrettyMethod(method) << " " << dex_pc;
763}
764
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700765void Trace::MethodEntered(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700766 ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700767 uint32_t thread_clock_diff = 0;
768 uint32_t wall_clock_diff = 0;
769 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
770 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodEntered,
771 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800772}
773
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700774void Trace::MethodExited(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700775 ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700776 const JValue& return_value ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700777 uint32_t thread_clock_diff = 0;
778 uint32_t wall_clock_diff = 0;
779 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
780 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodExited,
781 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800782}
783
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700784void Trace::MethodUnwind(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700785 ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700786 uint32_t thread_clock_diff = 0;
787 uint32_t wall_clock_diff = 0;
788 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
789 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
790 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800791}
792
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100793void Trace::ExceptionCaught(Thread* thread ATTRIBUTE_UNUSED,
794 mirror::Throwable* exception_object ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700795 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800796 LOG(ERROR) << "Unexpected exception caught event in tracing";
797}
798
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000799void Trace::Branch(Thread* /*thread*/, ArtMethod* method,
800 uint32_t /*dex_pc*/, int32_t /*dex_pc_offset*/)
Mathieu Chartier90443472015-07-16 20:32:27 -0700801 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray81f0f952016-01-20 16:25:19 +0000802 LOG(ERROR) << "Unexpected branch event in tracing" << PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800803}
804
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100805void Trace::InvokeVirtualOrInterface(Thread*,
806 mirror::Object*,
807 ArtMethod* method,
808 uint32_t dex_pc,
809 ArtMethod*) {
810 LOG(ERROR) << "Unexpected invoke event in tracing" << PrettyMethod(method)
811 << " " << dex_pc;
812}
813
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700814void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
815 if (UseThreadCpuClock()) {
816 uint64_t clock_base = thread->GetTraceClockBase();
817 if (UNLIKELY(clock_base == 0)) {
818 // First event, record the base time in the map.
819 uint64_t time = thread->GetCpuMicroTime();
820 thread->SetTraceClockBase(time);
821 } else {
822 *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
823 }
824 }
825 if (UseWallClock()) {
826 *wall_clock_diff = MicroTime() - start_time_;
827 }
828}
829
Mathieu Chartiere401d142015-04-22 13:56:20 -0700830bool Trace::RegisterMethod(ArtMethod* method) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800831 mirror::DexCache* dex_cache = method->GetDexCache();
Andreas Gampe7526d782015-06-22 22:53:45 -0700832 const DexFile* dex_file = dex_cache->GetDexFile();
Andreas Gampe7526d782015-06-22 22:53:45 -0700833 if (seen_methods_.find(dex_file) == seen_methods_.end()) {
834 seen_methods_.insert(std::make_pair(dex_file, new DexIndexBitSet()));
Andreas Gampe40da2862015-02-27 12:49:04 -0800835 }
Andreas Gampe7526d782015-06-22 22:53:45 -0700836 DexIndexBitSet* bit_set = seen_methods_.find(dex_file)->second;
Andreas Gampe40da2862015-02-27 12:49:04 -0800837 if (!(*bit_set)[method->GetDexMethodIndex()]) {
838 bit_set->set(method->GetDexMethodIndex());
839 return true;
840 }
841 return false;
842}
843
844bool Trace::RegisterThread(Thread* thread) {
845 pid_t tid = thread->GetTid();
846 CHECK_LT(0U, static_cast<uint32_t>(tid));
Alex Lighta344f6a2016-07-20 10:43:39 -0700847 CHECK_LT(static_cast<uint32_t>(tid), kMaxThreadIdNumber);
Andreas Gampe40da2862015-02-27 12:49:04 -0800848
849 if (!(*seen_threads_)[tid]) {
850 seen_threads_->set(tid);
851 return true;
852 }
853 return false;
854}
855
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700856std::string Trace::GetMethodLine(ArtMethod* method) {
Mathieu Chartiere3b034a2015-05-31 14:29:23 -0700857 method = method->GetInterfaceMethodIfProxy(sizeof(void*));
Alex Light0f7e8f52016-07-19 11:21:32 -0700858 return StringPrintf("%#x\t%s\t%s\t%s\t%s\n", (EncodeTraceMethod(method) << TraceActionBits),
Andreas Gampe40da2862015-02-27 12:49:04 -0800859 PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
860 method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
861}
862
863void Trace::WriteToBuf(const uint8_t* src, size_t src_size) {
864 int32_t old_offset = cur_offset_.LoadRelaxed();
865 int32_t new_offset = old_offset + static_cast<int32_t>(src_size);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700866 if (dchecked_integral_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800867 // Flush buffer.
868 if (!trace_file_->WriteFully(buf_.get(), old_offset)) {
869 PLOG(WARNING) << "Failed streaming a tracing event.";
870 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700871
872 // Check whether the data is too large for the buffer, then write immediately.
873 if (src_size >= buffer_size_) {
874 if (!trace_file_->WriteFully(src, src_size)) {
875 PLOG(WARNING) << "Failed streaming a tracing event.";
876 }
877 cur_offset_.StoreRelease(0); // Buffer is empty now.
878 return;
879 }
880
Andreas Gampe40da2862015-02-27 12:49:04 -0800881 old_offset = 0;
882 new_offset = static_cast<int32_t>(src_size);
883 }
884 cur_offset_.StoreRelease(new_offset);
885 // Fill in data.
886 memcpy(buf_.get() + old_offset, src, src_size);
887}
888
Mathieu Chartiere401d142015-04-22 13:56:20 -0700889void Trace::LogMethodTraceEvent(Thread* thread, ArtMethod* method,
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700890 instrumentation::Instrumentation::InstrumentationEvent event,
891 uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800892 // Advance cur_offset_ atomically.
893 int32_t new_offset;
Andreas Gampe40da2862015-02-27 12:49:04 -0800894 int32_t old_offset = 0;
895
896 // We do a busy loop here trying to acquire the next offset.
897 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
898 do {
899 old_offset = cur_offset_.LoadRelaxed();
900 new_offset = old_offset + GetRecordSize(clock_source_);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700901 if (static_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800902 overflow_ = true;
903 return;
904 }
905 } while (!cur_offset_.CompareExchangeWeakSequentiallyConsistent(old_offset, new_offset));
906 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800907
Ian Rogers62d6c772013-02-27 08:32:07 -0800908 TraceAction action = kTraceMethodEnter;
909 switch (event) {
910 case instrumentation::Instrumentation::kMethodEntered:
911 action = kTraceMethodEnter;
912 break;
913 case instrumentation::Instrumentation::kMethodExited:
914 action = kTraceMethodExit;
915 break;
916 case instrumentation::Instrumentation::kMethodUnwind:
917 action = kTraceUnroll;
918 break;
919 default:
920 UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
921 }
922
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700923 uint32_t method_value = EncodeTraceMethodAndAction(method, action);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800924
925 // Write data
Andreas Gampe40da2862015-02-27 12:49:04 -0800926 uint8_t* ptr;
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700927 static constexpr size_t kPacketSize = 14U; // The maximum size of data in a packet.
Andreas Gampe40da2862015-02-27 12:49:04 -0800928 uint8_t stack_buf[kPacketSize]; // Space to store a packet when in streaming mode.
929 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
930 ptr = stack_buf;
931 } else {
932 ptr = buf_.get() + old_offset;
933 }
934
Ian Rogers62d6c772013-02-27 08:32:07 -0800935 Append2LE(ptr, thread->GetTid());
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700936 Append4LE(ptr + 2, method_value);
937 ptr += 6;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800938
939 if (UseThreadCpuClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800940 Append4LE(ptr, thread_clock_diff);
941 ptr += 4;
942 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800943 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800944 Append4LE(ptr, wall_clock_diff);
945 }
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700946 static_assert(kPacketSize == 2 + 4 + 4 + 4, "Packet size incorrect.");
Andreas Gampe40da2862015-02-27 12:49:04 -0800947
948 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
949 MutexLock mu(Thread::Current(), *streaming_lock_); // To serialize writing.
950 if (RegisterMethod(method)) {
951 // Write a special block with the name.
952 std::string method_line(GetMethodLine(method));
953 uint8_t buf2[5];
954 Append2LE(buf2, 0);
955 buf2[2] = kOpNewMethod;
956 Append2LE(buf2 + 3, static_cast<uint16_t>(method_line.length()));
957 WriteToBuf(buf2, sizeof(buf2));
958 WriteToBuf(reinterpret_cast<const uint8_t*>(method_line.c_str()), method_line.length());
959 }
960 if (RegisterThread(thread)) {
961 // It might be better to postpone this. Threads might not have received names...
962 std::string thread_name;
963 thread->GetThreadName(thread_name);
964 uint8_t buf2[7];
965 Append2LE(buf2, 0);
966 buf2[2] = kOpNewThread;
967 Append2LE(buf2 + 3, static_cast<uint16_t>(thread->GetTid()));
968 Append2LE(buf2 + 5, static_cast<uint16_t>(thread_name.length()));
969 WriteToBuf(buf2, sizeof(buf2));
970 WriteToBuf(reinterpret_cast<const uint8_t*>(thread_name.c_str()), thread_name.length());
971 }
972 WriteToBuf(stack_buf, sizeof(stack_buf));
973 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800974}
975
Ian Rogers62d6c772013-02-27 08:32:07 -0800976void Trace::GetVisitedMethods(size_t buf_size,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700977 std::set<ArtMethod*>* visited_methods) {
jeffhao2692b572011-12-16 15:42:28 -0800978 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
Ian Rogers62d6c772013-02-27 08:32:07 -0800979 uint8_t* end = buf_.get() + buf_size;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800980
981 while (ptr < end) {
Mathieu Chartier4d64cd42015-06-02 16:38:29 -0700982 uint32_t tmid = ReadBytes(ptr + 2, sizeof(tmid));
983 ArtMethod* method = DecodeTraceMethod(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800984 visited_methods->insert(method);
985 ptr += GetRecordSize(clock_source_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800986 }
987}
988
Mathieu Chartiere401d142015-04-22 13:56:20 -0700989void Trace::DumpMethodList(std::ostream& os, const std::set<ArtMethod*>& visited_methods) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700990 for (const auto& method : visited_methods) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800991 os << GetMethodLine(method);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800992 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800993}
994
995static void DumpThread(Thread* t, void* arg) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800996 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
997 std::string name;
998 t->GetThreadName(name);
999 os << t->GetTid() << "\t" << name << "\n";
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001000}
1001
1002void Trace::DumpThreadList(std::ostream& os) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001003 Thread* self = Thread::Current();
Jeff Haoe094b872014-10-14 13:12:01 -07001004 for (auto it : exited_threads_) {
1005 os << it.first << "\t" << it.second << "\n";
1006 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001007 Locks::thread_list_lock_->AssertNotHeld(self);
1008 MutexLock mu(self, *Locks::thread_list_lock_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001009 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -08001010}
1011
Jeff Haoe094b872014-10-14 13:12:01 -07001012void Trace::StoreExitingThreadInfo(Thread* thread) {
1013 MutexLock mu(thread, *Locks::trace_lock_);
1014 if (the_trace_ != nullptr) {
1015 std::string name;
1016 thread->GetThreadName(name);
Andreas Gampea1785c52014-11-25 20:40:08 -08001017 // The same thread/tid may be used multiple times. As SafeMap::Put does not allow to override
1018 // a previous mapping, use SafeMap::Overwrite.
1019 the_trace_->exited_threads_.Overwrite(thread->GetTid(), name);
Jeff Haoe094b872014-10-14 13:12:01 -07001020 }
1021}
1022
Andreas Gampe40da2862015-02-27 12:49:04 -08001023Trace::TraceOutputMode Trace::GetOutputMode() {
1024 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1025 CHECK(the_trace_ != nullptr) << "Trace output mode requested, but no trace currently running";
1026 return the_trace_->trace_output_mode_;
1027}
1028
1029Trace::TraceMode Trace::GetMode() {
1030 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1031 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1032 return the_trace_->trace_mode_;
1033}
1034
Andreas Gampee34a42c2015-04-25 14:44:29 -07001035size_t Trace::GetBufferSize() {
1036 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1037 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1038 return the_trace_->buffer_size_;
1039}
1040
Mathieu Chartier7778b882015-10-05 16:41:10 -07001041bool Trace::IsTracingEnabled() {
1042 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1043 return the_trace_ != nullptr;
1044}
1045
jeffhaoe343b762011-12-05 16:36:44 -08001046} // namespace art