blob: 3b8feda2cd86937a470a9b9dd177fd783f5faead [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
Ian Rogerscf7f1912014-10-22 22:06:39 -070022#define ATRACE_TAG ATRACE_TAG_DALVIK
23#include "cutils/trace.h"
24
Andreas Gampee34a42c2015-04-25 14:44:29 -070025#include "base/casts.h"
Jeff Hao0abc72e2013-08-13 13:45:14 -070026#include "base/stl_util.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"
jeffhao725a9572012-11-13 18:20:12 -080032#include "instrumentation.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070033#include "mirror/art_method-inl.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"
Ian Rogers166db042013-07-26 12:05:57 -070043#include "entrypoints/quick/quick_entrypoints.h"
jeffhao2692b572011-12-16 15:42:28 -080044
45namespace art {
46
Elliott Hughese119a362012-05-22 17:37:06 -070047// File format:
48// header
49// record 0
50// record 1
51// ...
52//
53// Header format:
54// u4 magic ('SLOW')
55// u2 version
56// u2 offset to data
57// u8 start date/time in usec
58// u2 record size in bytes (version >= 2 only)
59// ... padding to 32 bytes
60//
61// Record format v1:
62// u1 thread ID
63// u4 method ID | method action
64// u4 time delta since start, in usec
65//
66// Record format v2:
67// u2 thread ID
68// u4 method ID | method action
69// u4 time delta since start, in usec
70//
71// Record format v3:
72// u2 thread ID
73// u4 method ID | method action
74// u4 time delta since start, in usec
75// u4 wall time since start, in usec (when clock == "dual" only)
76//
77// 32 bits of microseconds is 70 minutes.
78//
79// All values are stored in little-endian order.
80
Ian Rogers62d6c772013-02-27 08:32:07 -080081enum TraceAction {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070082 kTraceMethodEnter = 0x00, // method entry
83 kTraceMethodExit = 0x01, // method exit
84 kTraceUnroll = 0x02, // method exited by exception unrolling
Ian Rogers62d6c772013-02-27 08:32:07 -080085 // 0x03 currently unused
Brian Carlstrom7934ac22013-07-26 10:54:15 -070086 kTraceMethodActionMask = 0x03, // two bits
Ian Rogers62d6c772013-02-27 08:32:07 -080087};
88
Andreas Gampe40da2862015-02-27 12:49:04 -080089static constexpr uint8_t kOpNewMethod = 1U;
90static constexpr uint8_t kOpNewThread = 2U;
91
Jeff Hao0abc72e2013-08-13 13:45:14 -070092class BuildStackTraceVisitor : public StackVisitor {
93 public:
Andreas Gampe40da2862015-02-27 12:49:04 -080094 explicit BuildStackTraceVisitor(Thread* thread) : StackVisitor(thread, nullptr),
Jeff Hao5ce4b172013-08-16 16:27:18 -070095 method_trace_(Trace::AllocStackTrace()) {}
Jeff Hao0abc72e2013-08-13 13:45:14 -070096
Ian Rogersef7d42f2014-01-06 12:55:46 -080097 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogerse2f77e72013-08-13 19:19:40 -070098 mirror::ArtMethod* m = GetMethod();
Jeff Hao0abc72e2013-08-13 13:45:14 -070099 // Ignore runtime frames (in particular callee save).
100 if (!m->IsRuntimeMethod()) {
101 method_trace_->push_back(m);
102 }
103 return true;
104 }
105
106 // Returns a stack trace where the topmost frame corresponds with the first element of the vector.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700107 std::vector<mirror::ArtMethod*>* GetStackTrace() const {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700108 return method_trace_;
109 }
110
111 private:
Ian Rogerse2f77e72013-08-13 19:19:40 -0700112 std::vector<mirror::ArtMethod*>* const method_trace_;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700113};
114
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800115static const char kTraceTokenChar = '*';
116static const uint16_t kTraceHeaderLength = 32;
117static const uint32_t kTraceMagicValue = 0x574f4c53;
118static const uint16_t kTraceVersionSingleClock = 2;
119static const uint16_t kTraceVersionDualClock = 3;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700120static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
121static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800122
Ian Rogerse63db272014-07-15 15:36:11 -0700123TraceClockSource Trace::default_clock_source_ = kDefaultTraceClockSource;
Elliott Hughese119a362012-05-22 17:37:06 -0700124
Andreas Gampe40da2862015-02-27 12:49:04 -0800125Trace* volatile Trace::the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700126pthread_t Trace::sampling_pthread_ = 0U;
Ian Rogers700a4022014-05-19 16:49:03 -0700127std::unique_ptr<std::vector<mirror::ArtMethod*>> Trace::temp_stack_trace_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800128
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200129// The key identifying the tracer to update instrumentation.
130static constexpr const char* kTracerInstrumentationKey = "Tracer";
131
Brian Carlstromea46f952013-07-30 01:26:50 -0700132static mirror::ArtMethod* DecodeTraceMethodId(uint32_t tmid) {
133 return reinterpret_cast<mirror::ArtMethod*>(tmid & ~kTraceMethodActionMask);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800134}
Elliott Hughese119a362012-05-22 17:37:06 -0700135
Ian Rogers62d6c772013-02-27 08:32:07 -0800136static TraceAction DecodeTraceAction(uint32_t tmid) {
137 return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
138}
139
Ian Rogersef7d42f2014-01-06 12:55:46 -0800140static uint32_t EncodeTraceMethodAndAction(mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 TraceAction action) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800142 uint32_t tmid = PointerToLowMemUInt32(method) | action;
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 DCHECK_EQ(method, DecodeTraceMethodId(tmid));
144 return tmid;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800145}
146
Jeff Hao5ce4b172013-08-16 16:27:18 -0700147std::vector<mirror::ArtMethod*>* Trace::AllocStackTrace() {
Andreas Gampe40da2862015-02-27 12:49:04 -0800148 if (temp_stack_trace_.get() != nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700149 return temp_stack_trace_.release();
150 } else {
151 return new std::vector<mirror::ArtMethod*>();
152 }
153}
154
155void Trace::FreeStackTrace(std::vector<mirror::ArtMethod*>* stack_trace) {
156 stack_trace->clear();
157 temp_stack_trace_.reset(stack_trace);
158}
159
Ian Rogerse63db272014-07-15 15:36:11 -0700160void Trace::SetDefaultClockSource(TraceClockSource clock_source) {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800161#if defined(__linux__)
Ian Rogers62d6c772013-02-27 08:32:07 -0800162 default_clock_source_ = clock_source;
163#else
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800164 if (clock_source != TraceClockSource::kWall) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700165 LOG(WARNING) << "Ignoring tracing request to use CPU time.";
Ian Rogers62d6c772013-02-27 08:32:07 -0800166 }
167#endif
168}
169
Ian Rogerse63db272014-07-15 15:36:11 -0700170static uint16_t GetTraceVersion(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800171 return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800172 : kTraceVersionSingleClock;
173}
174
Ian Rogerse63db272014-07-15 15:36:11 -0700175static uint16_t GetRecordSize(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800176 return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800177 : kTraceRecordSizeSingleClock;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800178}
179
Elliott Hughese119a362012-05-22 17:37:06 -0700180bool Trace::UseThreadCpuClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800181 return (clock_source_ == TraceClockSource::kThreadCpu) ||
182 (clock_source_ == TraceClockSource::kDual);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800183}
184
Elliott Hughese119a362012-05-22 17:37:06 -0700185bool Trace::UseWallClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800186 return (clock_source_ == TraceClockSource::kWall) ||
187 (clock_source_ == TraceClockSource::kDual);
Elliott Hughese119a362012-05-22 17:37:06 -0700188}
189
Jeff Haoc5d824a2014-07-28 18:35:38 -0700190void Trace::MeasureClockOverhead() {
191 if (UseThreadCpuClock()) {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700192 Thread::Current()->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800193 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700194 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800195 MicroTime();
196 }
197}
198
Jeff Hao5ce4b172013-08-16 16:27:18 -0700199// Compute an average time taken to measure clocks.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700200uint32_t Trace::GetClockOverheadNanoSeconds() {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700201 Thread* self = Thread::Current();
202 uint64_t start = self->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800203
204 for (int i = 4000; i > 0; i--) {
Jeff Haoc5d824a2014-07-28 18:35:38 -0700205 MeasureClockOverhead();
206 MeasureClockOverhead();
207 MeasureClockOverhead();
208 MeasureClockOverhead();
209 MeasureClockOverhead();
210 MeasureClockOverhead();
211 MeasureClockOverhead();
212 MeasureClockOverhead();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800213 }
214
Jeff Hao5ce4b172013-08-16 16:27:18 -0700215 uint64_t elapsed_us = self->GetCpuMicroTime() - start;
216 return static_cast<uint32_t>(elapsed_us / 32);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800217}
218
Elliott Hughesffb465f2012-03-01 18:46:05 -0800219// TODO: put this somewhere with the big-endian equivalent used by JDWP.
220static void Append2LE(uint8_t* buf, uint16_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700221 *buf++ = static_cast<uint8_t>(val);
222 *buf++ = static_cast<uint8_t>(val >> 8);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800223}
224
Elliott Hughesffb465f2012-03-01 18:46:05 -0800225// TODO: put this somewhere with the big-endian equivalent used by JDWP.
226static void Append4LE(uint8_t* buf, uint32_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700227 *buf++ = static_cast<uint8_t>(val);
228 *buf++ = static_cast<uint8_t>(val >> 8);
229 *buf++ = static_cast<uint8_t>(val >> 16);
230 *buf++ = static_cast<uint8_t>(val >> 24);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800231}
232
Elliott Hughesffb465f2012-03-01 18:46:05 -0800233// TODO: put this somewhere with the big-endian equivalent used by JDWP.
234static void Append8LE(uint8_t* buf, uint64_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700235 *buf++ = static_cast<uint8_t>(val);
236 *buf++ = static_cast<uint8_t>(val >> 8);
237 *buf++ = static_cast<uint8_t>(val >> 16);
238 *buf++ = static_cast<uint8_t>(val >> 24);
239 *buf++ = static_cast<uint8_t>(val >> 32);
240 *buf++ = static_cast<uint8_t>(val >> 40);
241 *buf++ = static_cast<uint8_t>(val >> 48);
242 *buf++ = static_cast<uint8_t>(val >> 56);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800243}
244
Jeff Hao0abc72e2013-08-13 13:45:14 -0700245static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
246 BuildStackTraceVisitor build_trace_visitor(thread);
247 build_trace_visitor.WalkStack();
Ian Rogerse2f77e72013-08-13 19:19:40 -0700248 std::vector<mirror::ArtMethod*>* stack_trace = build_trace_visitor.GetStackTrace();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700249 Trace* the_trace = reinterpret_cast<Trace*>(arg);
250 the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
251}
252
Andreas Gampeca714582015-04-03 19:41:34 -0700253static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700254 thread->SetTraceClockBase(0);
255 std::vector<mirror::ArtMethod*>* stack_trace = thread->GetStackTraceSample();
Andreas Gampe40da2862015-02-27 12:49:04 -0800256 thread->SetStackTraceSample(nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700257 delete stack_trace;
258}
259
Jeff Hao0abc72e2013-08-13 13:45:14 -0700260void Trace::CompareAndUpdateStackTrace(Thread* thread,
Ian Rogerse2f77e72013-08-13 19:19:40 -0700261 std::vector<mirror::ArtMethod*>* stack_trace) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700262 CHECK_EQ(pthread_self(), sampling_pthread_);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700263 std::vector<mirror::ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
264 // Update the thread's stack trace sample.
265 thread->SetStackTraceSample(stack_trace);
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700266 // Read timer clocks to use for all events in this trace.
267 uint32_t thread_clock_diff = 0;
268 uint32_t wall_clock_diff = 0;
269 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
Andreas Gampe40da2862015-02-27 12:49:04 -0800270 if (old_stack_trace == nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700271 // If there's no previous stack trace sample for this thread, log an entry event for all
Jeff Hao0abc72e2013-08-13 13:45:14 -0700272 // methods in the trace.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700273 for (std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700274 rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700275 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
276 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700277 }
278 } else {
279 // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
280 // events accordingly.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700281 std::vector<mirror::ArtMethod*>::reverse_iterator old_rit = old_stack_trace->rbegin();
282 std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700283 // Iterate bottom-up over both traces until there's a difference between them.
284 while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
285 old_rit++;
286 rit++;
287 }
288 // Iterate top-down over the old trace until the point where they differ, emitting exit events.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700289 for (std::vector<mirror::ArtMethod*>::iterator old_it = old_stack_trace->begin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700290 old_it != old_rit.base(); ++old_it) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700291 LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
292 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700293 }
294 // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
295 for (; rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700296 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
297 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700298 }
Jeff Hao5ce4b172013-08-16 16:27:18 -0700299 FreeStackTrace(old_stack_trace);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700300 }
301}
302
303void* Trace::RunSamplingThread(void* arg) {
304 Runtime* runtime = Runtime::Current();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800305 intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
Jeff Hao4044bda2014-01-06 15:50:45 -0800306 CHECK_GE(interval_us, 0);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700307 CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800308 !runtime->IsAotCompiler()));
Jeff Hao0abc72e2013-08-13 13:45:14 -0700309
310 while (true) {
Jeff Hao23009dc2013-08-22 15:36:42 -0700311 usleep(interval_us);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700312 ATRACE_BEGIN("Profile sampling");
Jeff Hao0abc72e2013-08-13 13:45:14 -0700313 Thread* self = Thread::Current();
314 Trace* the_trace;
315 {
316 MutexLock mu(self, *Locks::trace_lock_);
317 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800318 if (the_trace == nullptr) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700319 break;
320 }
321 }
322
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700323 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700324 {
325 MutexLock mu(self, *Locks::thread_list_lock_);
326 runtime->GetThreadList()->ForEach(GetSample, the_trace);
327 }
328 runtime->GetThreadList()->ResumeAll();
Jeff Hao5ce4b172013-08-16 16:27:18 -0700329 ATRACE_END();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700330 }
331
332 runtime->DetachCurrentThread();
Andreas Gampe40da2862015-02-27 12:49:04 -0800333 return nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700334}
335
Andreas Gampee34a42c2015-04-25 14:44:29 -0700336void Trace::Start(const char* trace_filename, int trace_fd, size_t buffer_size, int flags,
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700337 TraceOutputMode output_mode, TraceMode trace_mode, int interval_us) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800338 Thread* self = Thread::Current();
339 {
340 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800341 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800342 LOG(ERROR) << "Trace already in progress, ignoring this request";
343 return;
344 }
jeffhaoe343b762011-12-05 16:36:44 -0800345 }
Jeff Haod063d912014-09-08 09:38:18 -0700346
347 // Check interval if sampling is enabled
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700348 if (trace_mode == TraceMode::kSampling && interval_us <= 0) {
Jeff Haod063d912014-09-08 09:38:18 -0700349 LOG(ERROR) << "Invalid sampling interval: " << interval_us;
350 ScopedObjectAccess soa(self);
351 ThrowRuntimeException("Invalid sampling interval: %d", interval_us);
352 return;
353 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800354
jeffhao2692b572011-12-16 15:42:28 -0800355 // Open trace file if not going directly to ddms.
Ian Rogers700a4022014-05-19 16:49:03 -0700356 std::unique_ptr<File> trace_file;
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700357 if (output_mode != TraceOutputMode::kDDMS) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800358 if (trace_fd < 0) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700359 trace_file.reset(OS::CreateEmptyFile(trace_filename));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800360 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800361 trace_file.reset(new File(trace_fd, "tracefile"));
Elliott Hughes76160052012-12-12 16:31:20 -0800362 trace_file->DisableAutoClose();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800363 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800364 if (trace_file.get() == nullptr) {
jeffhaob5e81852012-03-12 11:15:45 -0700365 PLOG(ERROR) << "Unable to open trace file '" << trace_filename << "'";
Ian Rogers62d6c772013-02-27 08:32:07 -0800366 ScopedObjectAccess soa(self);
367 ThrowRuntimeException("Unable to open trace file '%s'", trace_filename);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800368 return;
369 }
370 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800371
Jeff Haod063d912014-09-08 09:38:18 -0700372 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700373
374 // Enable count of allocs if specified in the flags.
375 bool enable_stats = false;
376
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700377 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Haod063d912014-09-08 09:38:18 -0700378
jeffhao2692b572011-12-16 15:42:28 -0800379 // Create Trace object.
Ian Rogers62d6c772013-02-27 08:32:07 -0800380 {
381 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800382 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800383 LOG(ERROR) << "Trace already in progress, ignoring this request";
384 } else {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700385 enable_stats = (flags && kTraceCountAllocs) != 0;
Andreas Gampe40da2862015-02-27 12:49:04 -0800386 the_trace_ = new Trace(trace_file.release(), trace_filename, buffer_size, flags, output_mode,
387 trace_mode);
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700388 if (trace_mode == TraceMode::kSampling) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800389 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
Jeff Hao23009dc2013-08-22 15:36:42 -0700390 reinterpret_cast<void*>(interval_us)),
391 "Sampling profiler thread");
Andreas Gampe40da2862015-02-27 12:49:04 -0800392 the_trace_->interval_us_ = interval_us;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700393 } else {
394 runtime->GetInstrumentation()->AddListener(the_trace_,
395 instrumentation::Instrumentation::kMethodEntered |
396 instrumentation::Instrumentation::kMethodExited |
397 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe40da2862015-02-27 12:49:04 -0800398 // TODO: In full-PIC mode, we don't need to fully deopt.
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200399 runtime->GetInstrumentation()->EnableMethodTracing(kTracerInstrumentationKey);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700400 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800401 }
jeffhao0791adc2012-04-04 11:14:32 -0700402 }
Jeff Haod063d912014-09-08 09:38:18 -0700403
Ian Rogers62d6c772013-02-27 08:32:07 -0800404 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700405
406 // Can't call this when holding the mutator lock.
407 if (enable_stats) {
408 runtime->SetStatsEnabled(true);
409 }
jeffhao2692b572011-12-16 15:42:28 -0800410}
411
Andreas Gampe40da2862015-02-27 12:49:04 -0800412void Trace::StopTracing(bool finish_tracing, bool flush_file) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700413 bool stop_alloc_counting = false;
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700414 Runtime* const runtime = Runtime::Current();
415 Trace* the_trace = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700416 pthread_t sampling_pthread = 0U;
Ian Rogers62d6c772013-02-27 08:32:07 -0800417 {
418 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800419 if (the_trace_ == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800420 LOG(ERROR) << "Trace stop requested, but no trace currently running";
421 } else {
422 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800423 the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700424 sampling_pthread = sampling_pthread_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800425 }
jeffhao2692b572011-12-16 15:42:28 -0800426 }
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700427 // Make sure that we join before we delete the trace since we don't want to have
428 // the sampling thread access a stale pointer. This finishes since the sampling thread exits when
429 // the_trace_ is null.
430 if (sampling_pthread != 0U) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800431 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700432 sampling_pthread_ = 0U;
433 }
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700434 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Andreas Gampe40da2862015-02-27 12:49:04 -0800435
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700436 if (the_trace != nullptr) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800437 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
438 if (finish_tracing) {
439 the_trace->FinishTracing();
440 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700441
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700442 if (the_trace->trace_mode_ == TraceMode::kSampling) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700443 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700444 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700445 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200446 runtime->GetInstrumentation()->DisableMethodTracing(kTracerInstrumentationKey);
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700447 runtime->GetInstrumentation()->RemoveListener(
448 the_trace, instrumentation::Instrumentation::kMethodEntered |
449 instrumentation::Instrumentation::kMethodExited |
450 instrumentation::Instrumentation::kMethodUnwind);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700451 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800452 if (the_trace->trace_file_.get() != nullptr) {
453 // Do not try to erase, so flush and close explicitly.
Andreas Gampe40da2862015-02-27 12:49:04 -0800454 if (flush_file) {
455 if (the_trace->trace_file_->Flush() != 0) {
456 PLOG(ERROR) << "Could not flush trace file.";
457 }
458 } else {
459 the_trace->trace_file_->MarkUnchecked(); // Do not trigger guard.
Andreas Gampe4303ba92014-11-06 01:00:46 -0800460 }
461 if (the_trace->trace_file_->Close() != 0) {
462 PLOG(ERROR) << "Could not close trace file.";
463 }
464 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800465 delete the_trace;
466 }
467 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700468 if (stop_alloc_counting) {
469 // Can be racy since SetStatsEnabled is not guarded by any locks.
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700470 runtime->SetStatsEnabled(false);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700471 }
jeffhao2692b572011-12-16 15:42:28 -0800472}
473
Andreas Gampe40da2862015-02-27 12:49:04 -0800474void Trace::Abort() {
475 // Do not write anything anymore.
476 StopTracing(false, false);
477}
478
479void Trace::Stop() {
480 // Finish writing.
481 StopTracing(true, true);
482}
483
jeffhaob5e81852012-03-12 11:15:45 -0700484void Trace::Shutdown() {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700485 if (GetMethodTracingMode() != kTracingInactive) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800486 Stop();
jeffhaob5e81852012-03-12 11:15:45 -0700487 }
jeffhaob5e81852012-03-12 11:15:45 -0700488}
489
Andreas Gampe40da2862015-02-27 12:49:04 -0800490void Trace::Pause() {
491 bool stop_alloc_counting = false;
492 Runtime* runtime = Runtime::Current();
493 Trace* the_trace = nullptr;
494
495 pthread_t sampling_pthread = 0U;
496 {
497 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
498 if (the_trace_ == nullptr) {
499 LOG(ERROR) << "Trace pause requested, but no trace currently running";
500 return;
501 } else {
502 the_trace = the_trace_;
503 sampling_pthread = sampling_pthread_;
504 }
505 }
506
507 if (sampling_pthread != 0U) {
508 {
509 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
510 the_trace_ = nullptr;
511 }
512 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
513 sampling_pthread_ = 0U;
514 {
515 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
516 the_trace_ = the_trace;
517 }
518 }
519
520 if (the_trace != nullptr) {
521 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
522 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
523
524 if (the_trace->trace_mode_ == TraceMode::kSampling) {
525 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
526 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
527 } else {
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200528 runtime->GetInstrumentation()->DisableMethodTracing(kTracerInstrumentationKey);
Andreas Gampe40da2862015-02-27 12:49:04 -0800529 runtime->GetInstrumentation()->RemoveListener(the_trace,
530 instrumentation::Instrumentation::kMethodEntered |
531 instrumentation::Instrumentation::kMethodExited |
532 instrumentation::Instrumentation::kMethodUnwind);
533 }
534 runtime->GetThreadList()->ResumeAll();
535 }
536
537 if (stop_alloc_counting) {
538 // Can be racy since SetStatsEnabled is not guarded by any locks.
539 Runtime::Current()->SetStatsEnabled(false);
540 }
541}
542
543void Trace::Resume() {
544 Thread* self = Thread::Current();
545 Trace* the_trace;
546 {
547 MutexLock mu(self, *Locks::trace_lock_);
548 if (the_trace_ == nullptr) {
549 LOG(ERROR) << "No trace to resume (or sampling mode), ignoring this request";
550 return;
551 }
552 the_trace = the_trace_;
553 }
554
555 Runtime* runtime = Runtime::Current();
556
557 // Enable count of allocs if specified in the flags.
558 bool enable_stats = (the_trace->flags_ && kTraceCountAllocs) != 0;
559
560 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
561
562 // Reenable.
563 if (the_trace->trace_mode_ == TraceMode::kSampling) {
564 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
565 reinterpret_cast<void*>(the_trace->interval_us_)), "Sampling profiler thread");
566 } else {
567 runtime->GetInstrumentation()->AddListener(the_trace,
568 instrumentation::Instrumentation::kMethodEntered |
569 instrumentation::Instrumentation::kMethodExited |
570 instrumentation::Instrumentation::kMethodUnwind);
571 // TODO: In full-PIC mode, we don't need to fully deopt.
Sebastien Hertz0462c4c2015-04-01 16:34:17 +0200572 runtime->GetInstrumentation()->EnableMethodTracing(kTracerInstrumentationKey);
Andreas Gampe40da2862015-02-27 12:49:04 -0800573 }
574
575 runtime->GetThreadList()->ResumeAll();
576
577 // Can't call this when holding the mutator lock.
578 if (enable_stats) {
579 runtime->SetStatsEnabled(true);
580 }
581}
582
Jeff Hao64caa7d2013-08-29 11:18:01 -0700583TracingMode Trace::GetMethodTracingMode() {
Ian Rogers62d6c772013-02-27 08:32:07 -0800584 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800585 if (the_trace_ == nullptr) {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700586 return kTracingInactive;
Jeff Hao64caa7d2013-08-29 11:18:01 -0700587 } else {
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700588 switch (the_trace_->trace_mode_) {
589 case TraceMode::kSampling:
590 return kSampleProfilingActive;
591 case TraceMode::kMethodTracing:
592 return kMethodTracingActive;
593 }
594 LOG(FATAL) << "Unreachable";
595 UNREACHABLE();
Jeff Hao64caa7d2013-08-29 11:18:01 -0700596 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800597}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800598
Andreas Gampee34a42c2015-04-25 14:44:29 -0700599static constexpr size_t kMinBufSize = 18U; // Trace header is up to 18B.
Andreas Gampe40da2862015-02-27 12:49:04 -0800600
Andreas Gampee34a42c2015-04-25 14:44:29 -0700601Trace::Trace(File* trace_file, const char* trace_name, size_t buffer_size, int flags,
Andreas Gampe40da2862015-02-27 12:49:04 -0800602 TraceOutputMode output_mode, TraceMode trace_mode)
603 : trace_file_(trace_file),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700604 buf_(new uint8_t[std::max(kMinBufSize, buffer_size)]()),
Andreas Gampe40da2862015-02-27 12:49:04 -0800605 flags_(flags), trace_output_mode_(output_mode), trace_mode_(trace_mode),
606 clock_source_(default_clock_source_),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700607 buffer_size_(std::max(kMinBufSize, buffer_size)),
Andreas Gampe40da2862015-02-27 12:49:04 -0800608 start_time_(MicroTime()), clock_overhead_ns_(GetClockOverheadNanoSeconds()), cur_offset_(0),
609 overflow_(false), interval_us_(0), streaming_lock_(nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800610 uint16_t trace_version = GetTraceVersion(clock_source_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800611 if (output_mode == TraceOutputMode::kStreaming) {
612 trace_version |= 0xF0U;
613 }
614 // Set up the beginning of the trace.
jeffhao2692b572011-12-16 15:42:28 -0800615 memset(buf_.get(), 0, kTraceHeaderLength);
616 Append4LE(buf_.get(), kTraceMagicValue);
Ian Rogers62d6c772013-02-27 08:32:07 -0800617 Append2LE(buf_.get() + 4, trace_version);
jeffhao2692b572011-12-16 15:42:28 -0800618 Append2LE(buf_.get() + 6, kTraceHeaderLength);
619 Append8LE(buf_.get() + 8, start_time_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800620 if (trace_version >= kTraceVersionDualClock) {
621 uint16_t record_size = GetRecordSize(clock_source_);
622 Append2LE(buf_.get() + 16, record_size);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800623 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700624 static_assert(18 <= kMinBufSize, "Minimum buffer size not large enough for trace header");
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800625
jeffhao2692b572011-12-16 15:42:28 -0800626 // Update current offset.
Ian Rogers8ab25ef2014-07-09 18:00:50 -0700627 cur_offset_.StoreRelaxed(kTraceHeaderLength);
Andreas Gampe40da2862015-02-27 12:49:04 -0800628
629 if (output_mode == TraceOutputMode::kStreaming) {
630 streaming_file_name_ = trace_name;
631 streaming_lock_ = new Mutex("tracing lock");
632 seen_threads_.reset(new ThreadIDBitSet());
633 }
634}
635
636Trace::~Trace() {
637 delete streaming_lock_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800638}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800639
Ian Rogerse63db272014-07-15 15:36:11 -0700640static void DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source)
Ian Rogers62d6c772013-02-27 08:32:07 -0800641 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
642 uint8_t* ptr = buf + kTraceHeaderLength;
643 uint8_t* end = buf + buf_size;
644
645 while (ptr < end) {
646 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700647 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800648 TraceAction action = DecodeTraceAction(tmid);
649 LOG(INFO) << PrettyMethod(method) << " " << static_cast<int>(action);
650 ptr += GetRecordSize(clock_source);
651 }
jeffhaoe343b762011-12-05 16:36:44 -0800652}
653
Andreas Gampe40da2862015-02-27 12:49:04 -0800654static void GetVisitedMethodsFromBitSets(
655 const std::map<mirror::DexCache*, DexIndexBitSet*>& seen_methods,
656 std::set<mirror::ArtMethod*>* visited_methods) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
657 for (auto& e : seen_methods) {
658 DexIndexBitSet* bit_set = e.second;
659 for (uint32_t i = 0; i < bit_set->size(); ++i) {
660 if ((*bit_set)[i]) {
661 visited_methods->insert(e.first->GetResolvedMethod(i));
662 }
663 }
664 }
665}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800666
Andreas Gampe40da2862015-02-27 12:49:04 -0800667void Trace::FinishTracing() {
668 size_t final_offset = 0;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800669
Brian Carlstromea46f952013-07-30 01:26:50 -0700670 std::set<mirror::ArtMethod*> visited_methods;
Andreas Gampe40da2862015-02-27 12:49:04 -0800671 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
672 // Write the secondary file with all the method names.
673 GetVisitedMethodsFromBitSets(seen_methods_, &visited_methods);
674
675 // Clean up.
676 for (auto& e : seen_methods_) {
677 delete e.second;
678 }
679 } else {
680 final_offset = cur_offset_.LoadRelaxed();
681 GetVisitedMethods(final_offset, &visited_methods);
682 }
683
684 // Compute elapsed time.
685 uint64_t elapsed = MicroTime() - start_time_;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800686
687 std::ostringstream os;
688
689 os << StringPrintf("%cversion\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800690 os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800691 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
692 if (UseThreadCpuClock()) {
693 if (UseWallClock()) {
694 os << StringPrintf("clock=dual\n");
695 } else {
696 os << StringPrintf("clock=thread-cpu\n");
697 }
698 } else {
699 os << StringPrintf("clock=wall\n");
700 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800701 os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
Andreas Gampe40da2862015-02-27 12:49:04 -0800702 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
703 size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
704 os << StringPrintf("num-method-calls=%zd\n", num_records);
705 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700706 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800707 os << StringPrintf("vm=art\n");
John Reck0624a272015-03-26 15:47:54 -0700708 os << StringPrintf("pid=%d\n", getpid());
jeffhao0791adc2012-04-04 11:14:32 -0700709 if ((flags_ & kTraceCountAllocs) != 0) {
710 os << StringPrintf("alloc-count=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS));
711 os << StringPrintf("alloc-size=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES));
712 os << StringPrintf("gc-count=%d\n", Runtime::Current()->GetStat(KIND_GC_INVOCATIONS));
713 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800714 os << StringPrintf("%cthreads\n", kTraceTokenChar);
715 DumpThreadList(os);
716 os << StringPrintf("%cmethods\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800717 DumpMethodList(os, visited_methods);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800718 os << StringPrintf("%cend\n", kTraceTokenChar);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800719 std::string header(os.str());
Andreas Gampe40da2862015-02-27 12:49:04 -0800720
721 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
722 File file;
723 if (!file.Open(streaming_file_name_ + ".sec", O_CREAT | O_WRONLY)) {
724 LOG(WARNING) << "Could not open secondary trace file!";
725 return;
Ian Rogers62d6c772013-02-27 08:32:07 -0800726 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800727 if (!file.WriteFully(header.c_str(), header.length())) {
728 file.Erase();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700729 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
730 PLOG(ERROR) << detail;
Ian Rogers62d6c772013-02-27 08:32:07 -0800731 ThrowRuntimeException("%s", detail.c_str());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800732 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800733 if (file.FlushCloseOrErase() != 0) {
734 PLOG(ERROR) << "Could not write secondary file";
735 }
736 } else {
737 if (trace_file_.get() == nullptr) {
738 iovec iov[2];
739 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
740 iov[0].iov_len = header.length();
741 iov[1].iov_base = buf_.get();
742 iov[1].iov_len = final_offset;
743 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
744 const bool kDumpTraceInfo = false;
745 if (kDumpTraceInfo) {
746 LOG(INFO) << "Trace sent:\n" << header;
747 DumpBuf(buf_.get(), final_offset, clock_source_);
748 }
749 } else {
750 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
751 !trace_file_->WriteFully(buf_.get(), final_offset)) {
752 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
753 PLOG(ERROR) << detail;
754 ThrowRuntimeException("%s", detail.c_str());
755 }
756 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800757 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800758}
759
Ian Rogers62d6c772013-02-27 08:32:07 -0800760void Trace::DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800761 mirror::ArtMethod* method, uint32_t new_dex_pc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700762 UNUSED(thread, this_object, method, new_dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800763 // We're not recorded to listen to this kind of event, so complain.
764 LOG(ERROR) << "Unexpected dex PC event in tracing " << PrettyMethod(method) << " " << new_dex_pc;
Andreas Gampec8ccf682014-09-29 20:07:43 -0700765}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800766
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700767void Trace::FieldRead(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700768 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200769 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700770 UNUSED(thread, this_object, method, dex_pc, field);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200771 // We're not recorded to listen to this kind of event, so complain.
772 LOG(ERROR) << "Unexpected field read event in tracing " << PrettyMethod(method) << " " << dex_pc;
773}
774
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700775void Trace::FieldWritten(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700776 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200777 const JValue& field_value)
778 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700779 UNUSED(thread, this_object, method, dex_pc, field, field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200780 // We're not recorded to listen to this kind of event, so complain.
781 LOG(ERROR) << "Unexpected field write event in tracing " << PrettyMethod(method) << " " << dex_pc;
782}
783
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700784void Trace::MethodEntered(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
785 mirror::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::kMethodEntered,
790 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800791}
792
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700793void Trace::MethodExited(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
794 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED,
795 const JValue& return_value ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700796 uint32_t thread_clock_diff = 0;
797 uint32_t wall_clock_diff = 0;
798 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
799 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodExited,
800 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800801}
802
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700803void Trace::MethodUnwind(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
804 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700805 uint32_t thread_clock_diff = 0;
806 uint32_t wall_clock_diff = 0;
807 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
808 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
809 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800810}
811
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000812void Trace::ExceptionCaught(Thread* thread, mirror::Throwable* exception_object)
Ian Rogers62d6c772013-02-27 08:32:07 -0800813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000814 UNUSED(thread, exception_object);
Ian Rogers62d6c772013-02-27 08:32:07 -0800815 LOG(ERROR) << "Unexpected exception caught event in tracing";
816}
817
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800818void Trace::BackwardBranch(Thread* /*thread*/, mirror::ArtMethod* method,
819 int32_t /*dex_pc_offset*/)
820 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
821 LOG(ERROR) << "Unexpected backward branch event in tracing" << PrettyMethod(method);
822}
823
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700824void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
825 if (UseThreadCpuClock()) {
826 uint64_t clock_base = thread->GetTraceClockBase();
827 if (UNLIKELY(clock_base == 0)) {
828 // First event, record the base time in the map.
829 uint64_t time = thread->GetCpuMicroTime();
830 thread->SetTraceClockBase(time);
831 } else {
832 *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
833 }
834 }
835 if (UseWallClock()) {
836 *wall_clock_diff = MicroTime() - start_time_;
837 }
838}
839
Andreas Gampe40da2862015-02-27 12:49:04 -0800840bool Trace::RegisterMethod(mirror::ArtMethod* method) {
841 mirror::DexCache* dex_cache = method->GetDexCache();
842 if (dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) != method) {
843 DCHECK(dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) == nullptr);
844 dex_cache->SetResolvedMethod(method->GetDexMethodIndex(), method);
845 }
846 if (seen_methods_.find(dex_cache) == seen_methods_.end()) {
847 seen_methods_.insert(std::make_pair(dex_cache, new DexIndexBitSet()));
848 }
849 DexIndexBitSet* bit_set = seen_methods_.find(dex_cache)->second;
850 if (!(*bit_set)[method->GetDexMethodIndex()]) {
851 bit_set->set(method->GetDexMethodIndex());
852 return true;
853 }
854 return false;
855}
856
857bool Trace::RegisterThread(Thread* thread) {
858 pid_t tid = thread->GetTid();
859 CHECK_LT(0U, static_cast<uint32_t>(tid));
860 CHECK_LT(static_cast<uint32_t>(tid), 65536U);
861
862 if (!(*seen_threads_)[tid]) {
863 seen_threads_->set(tid);
864 return true;
865 }
866 return false;
867}
868
869static std::string GetMethodLine(mirror::ArtMethod* method)
870 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
871 return StringPrintf("%p\t%s\t%s\t%s\t%s\n", method,
872 PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
873 method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
874}
875
876void Trace::WriteToBuf(const uint8_t* src, size_t src_size) {
877 int32_t old_offset = cur_offset_.LoadRelaxed();
878 int32_t new_offset = old_offset + static_cast<int32_t>(src_size);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700879 if (dchecked_integral_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800880 // Flush buffer.
881 if (!trace_file_->WriteFully(buf_.get(), old_offset)) {
882 PLOG(WARNING) << "Failed streaming a tracing event.";
883 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700884
885 // Check whether the data is too large for the buffer, then write immediately.
886 if (src_size >= buffer_size_) {
887 if (!trace_file_->WriteFully(src, src_size)) {
888 PLOG(WARNING) << "Failed streaming a tracing event.";
889 }
890 cur_offset_.StoreRelease(0); // Buffer is empty now.
891 return;
892 }
893
Andreas Gampe40da2862015-02-27 12:49:04 -0800894 old_offset = 0;
895 new_offset = static_cast<int32_t>(src_size);
896 }
897 cur_offset_.StoreRelease(new_offset);
898 // Fill in data.
899 memcpy(buf_.get() + old_offset, src, src_size);
900}
901
Ian Rogersef7d42f2014-01-06 12:55:46 -0800902void Trace::LogMethodTraceEvent(Thread* thread, mirror::ArtMethod* method,
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700903 instrumentation::Instrumentation::InstrumentationEvent event,
904 uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800905 // Advance cur_offset_ atomically.
906 int32_t new_offset;
Andreas Gampe40da2862015-02-27 12:49:04 -0800907 int32_t old_offset = 0;
908
909 // We do a busy loop here trying to acquire the next offset.
910 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
911 do {
912 old_offset = cur_offset_.LoadRelaxed();
913 new_offset = old_offset + GetRecordSize(clock_source_);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700914 if (static_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800915 overflow_ = true;
916 return;
917 }
918 } while (!cur_offset_.CompareExchangeWeakSequentiallyConsistent(old_offset, new_offset));
919 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800920
Ian Rogers62d6c772013-02-27 08:32:07 -0800921 TraceAction action = kTraceMethodEnter;
922 switch (event) {
923 case instrumentation::Instrumentation::kMethodEntered:
924 action = kTraceMethodEnter;
925 break;
926 case instrumentation::Instrumentation::kMethodExited:
927 action = kTraceMethodExit;
928 break;
929 case instrumentation::Instrumentation::kMethodUnwind:
930 action = kTraceUnroll;
931 break;
932 default:
933 UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
934 }
935
936 uint32_t method_value = EncodeTraceMethodAndAction(method, action);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800937
938 // Write data
Andreas Gampe40da2862015-02-27 12:49:04 -0800939 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
Ian Rogers62d6c772013-02-27 08:32:07 -0800948 Append2LE(ptr, thread->GetTid());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800949 Append4LE(ptr + 2, method_value);
950 ptr += 6;
951
952 if (UseThreadCpuClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800953 Append4LE(ptr, thread_clock_diff);
954 ptr += 4;
955 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800956 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800957 Append4LE(ptr, wall_clock_diff);
958 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800959 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 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800987}
988
Ian Rogers62d6c772013-02-27 08:32:07 -0800989void Trace::GetVisitedMethods(size_t buf_size,
Brian Carlstromea46f952013-07-30 01:26:50 -0700990 std::set<mirror::ArtMethod*>* visited_methods) {
jeffhao2692b572011-12-16 15:42:28 -0800991 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
Ian Rogers62d6c772013-02-27 08:32:07 -0800992 uint8_t* end = buf_.get() + buf_size;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800993
994 while (ptr < end) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800995 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700996 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800997 visited_methods->insert(method);
998 ptr += GetRecordSize(clock_source_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800999 }
1000}
1001
Mathieu Chartier02e25112013-08-14 16:14:24 -07001002void Trace::DumpMethodList(std::ostream& os, const std::set<mirror::ArtMethod*>& visited_methods) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001003 for (const auto& method : visited_methods) {
Andreas Gampe40da2862015-02-27 12:49:04 -08001004 os << GetMethodLine(method);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001005 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001006}
1007
1008static void DumpThread(Thread* t, void* arg) {
Elliott Hughesffb465f2012-03-01 18:46:05 -08001009 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
1010 std::string name;
1011 t->GetThreadName(name);
1012 os << t->GetTid() << "\t" << name << "\n";
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001013}
1014
1015void Trace::DumpThreadList(std::ostream& os) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001016 Thread* self = Thread::Current();
Jeff Haoe094b872014-10-14 13:12:01 -07001017 for (auto it : exited_threads_) {
1018 os << it.first << "\t" << it.second << "\n";
1019 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001020 Locks::thread_list_lock_->AssertNotHeld(self);
1021 MutexLock mu(self, *Locks::thread_list_lock_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001022 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -08001023}
1024
Jeff Haoe094b872014-10-14 13:12:01 -07001025void Trace::StoreExitingThreadInfo(Thread* thread) {
1026 MutexLock mu(thread, *Locks::trace_lock_);
1027 if (the_trace_ != nullptr) {
1028 std::string name;
1029 thread->GetThreadName(name);
Andreas Gampea1785c52014-11-25 20:40:08 -08001030 // 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);
Jeff Haoe094b872014-10-14 13:12:01 -07001033 }
1034}
1035
Andreas Gampe40da2862015-02-27 12:49:04 -08001036Trace::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
1042Trace::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
Andreas Gampee34a42c2015-04-25 14:44:29 -07001048size_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
jeffhaoe343b762011-12-05 16:36:44 -08001054} // namespace art