blob: 5322f9fc1fdee8fb0f7d13ed6c605c9c6e004496 [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
Jeff Hao0abc72e2013-08-13 13:45:14 -070025#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080026#include "base/unix_file/fd_file.h"
jeffhaoe343b762011-12-05 16:36:44 -080027#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080028#include "common_throws.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080029#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "dex_file-inl.h"
jeffhao725a9572012-11-13 18:20:12 -080031#include "instrumentation.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "mirror/class-inl.h"
Andreas Gampe40da2862015-02-27 12:49:04 -080034#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/object_array-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "mirror/object-inl.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080037#include "os.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Jeff Hao0abc72e2013-08-13 13:45:14 -070039#include "ScopedLocalRef.h"
jeffhaoe343b762011-12-05 16:36:44 -080040#include "thread.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070041#include "thread_list.h"
Ian Rogers166db042013-07-26 12:05:57 -070042#include "entrypoints/quick/quick_entrypoints.h"
jeffhao2692b572011-12-16 15:42:28 -080043
44namespace art {
45
Elliott Hughese119a362012-05-22 17:37:06 -070046// File format:
47// header
48// record 0
49// record 1
50// ...
51//
52// Header format:
53// u4 magic ('SLOW')
54// u2 version
55// u2 offset to data
56// u8 start date/time in usec
57// u2 record size in bytes (version >= 2 only)
58// ... padding to 32 bytes
59//
60// Record format v1:
61// u1 thread ID
62// u4 method ID | method action
63// u4 time delta since start, in usec
64//
65// Record format v2:
66// u2 thread ID
67// u4 method ID | method action
68// u4 time delta since start, in usec
69//
70// Record format v3:
71// u2 thread ID
72// u4 method ID | method action
73// u4 time delta since start, in usec
74// u4 wall time since start, in usec (when clock == "dual" only)
75//
76// 32 bits of microseconds is 70 minutes.
77//
78// All values are stored in little-endian order.
79
Ian Rogers62d6c772013-02-27 08:32:07 -080080enum TraceAction {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070081 kTraceMethodEnter = 0x00, // method entry
82 kTraceMethodExit = 0x01, // method exit
83 kTraceUnroll = 0x02, // method exited by exception unrolling
Ian Rogers62d6c772013-02-27 08:32:07 -080084 // 0x03 currently unused
Brian Carlstrom7934ac22013-07-26 10:54:15 -070085 kTraceMethodActionMask = 0x03, // two bits
Ian Rogers62d6c772013-02-27 08:32:07 -080086};
87
Andreas Gampe40da2862015-02-27 12:49:04 -080088static constexpr uint8_t kOpNewMethod = 1U;
89static constexpr uint8_t kOpNewThread = 2U;
90
Jeff Hao0abc72e2013-08-13 13:45:14 -070091class BuildStackTraceVisitor : public StackVisitor {
92 public:
Andreas Gampe40da2862015-02-27 12:49:04 -080093 explicit BuildStackTraceVisitor(Thread* thread) : StackVisitor(thread, nullptr),
Jeff Hao5ce4b172013-08-16 16:27:18 -070094 method_trace_(Trace::AllocStackTrace()) {}
Jeff Hao0abc72e2013-08-13 13:45:14 -070095
Ian Rogersef7d42f2014-01-06 12:55:46 -080096 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogerse2f77e72013-08-13 19:19:40 -070097 mirror::ArtMethod* m = GetMethod();
Jeff Hao0abc72e2013-08-13 13:45:14 -070098 // Ignore runtime frames (in particular callee save).
99 if (!m->IsRuntimeMethod()) {
100 method_trace_->push_back(m);
101 }
102 return true;
103 }
104
105 // Returns a stack trace where the topmost frame corresponds with the first element of the vector.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700106 std::vector<mirror::ArtMethod*>* GetStackTrace() const {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700107 return method_trace_;
108 }
109
110 private:
Ian Rogerse2f77e72013-08-13 19:19:40 -0700111 std::vector<mirror::ArtMethod*>* const method_trace_;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700112};
113
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800114static const char kTraceTokenChar = '*';
115static const uint16_t kTraceHeaderLength = 32;
116static const uint32_t kTraceMagicValue = 0x574f4c53;
117static const uint16_t kTraceVersionSingleClock = 2;
118static const uint16_t kTraceVersionDualClock = 3;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700119static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
120static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800121
Ian Rogerse63db272014-07-15 15:36:11 -0700122TraceClockSource Trace::default_clock_source_ = kDefaultTraceClockSource;
Elliott Hughese119a362012-05-22 17:37:06 -0700123
Andreas Gampe40da2862015-02-27 12:49:04 -0800124Trace* volatile Trace::the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700125pthread_t Trace::sampling_pthread_ = 0U;
Ian Rogers700a4022014-05-19 16:49:03 -0700126std::unique_ptr<std::vector<mirror::ArtMethod*>> Trace::temp_stack_trace_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800127
Brian Carlstromea46f952013-07-30 01:26:50 -0700128static mirror::ArtMethod* DecodeTraceMethodId(uint32_t tmid) {
129 return reinterpret_cast<mirror::ArtMethod*>(tmid & ~kTraceMethodActionMask);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800130}
Elliott Hughese119a362012-05-22 17:37:06 -0700131
Ian Rogers62d6c772013-02-27 08:32:07 -0800132static TraceAction DecodeTraceAction(uint32_t tmid) {
133 return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
134}
135
Ian Rogersef7d42f2014-01-06 12:55:46 -0800136static uint32_t EncodeTraceMethodAndAction(mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800137 TraceAction action) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800138 uint32_t tmid = PointerToLowMemUInt32(method) | action;
Ian Rogers62d6c772013-02-27 08:32:07 -0800139 DCHECK_EQ(method, DecodeTraceMethodId(tmid));
140 return tmid;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800141}
142
Jeff Hao5ce4b172013-08-16 16:27:18 -0700143std::vector<mirror::ArtMethod*>* Trace::AllocStackTrace() {
Andreas Gampe40da2862015-02-27 12:49:04 -0800144 if (temp_stack_trace_.get() != nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700145 return temp_stack_trace_.release();
146 } else {
147 return new std::vector<mirror::ArtMethod*>();
148 }
149}
150
151void Trace::FreeStackTrace(std::vector<mirror::ArtMethod*>* stack_trace) {
152 stack_trace->clear();
153 temp_stack_trace_.reset(stack_trace);
154}
155
Ian Rogerse63db272014-07-15 15:36:11 -0700156void Trace::SetDefaultClockSource(TraceClockSource clock_source) {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800157#if defined(__linux__)
Ian Rogers62d6c772013-02-27 08:32:07 -0800158 default_clock_source_ = clock_source;
159#else
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800160 if (clock_source != TraceClockSource::kWall) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700161 LOG(WARNING) << "Ignoring tracing request to use CPU time.";
Ian Rogers62d6c772013-02-27 08:32:07 -0800162 }
163#endif
164}
165
Ian Rogerse63db272014-07-15 15:36:11 -0700166static uint16_t GetTraceVersion(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800167 return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800168 : kTraceVersionSingleClock;
169}
170
Ian Rogerse63db272014-07-15 15:36:11 -0700171static uint16_t GetRecordSize(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800172 return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800173 : kTraceRecordSizeSingleClock;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800174}
175
Elliott Hughese119a362012-05-22 17:37:06 -0700176bool Trace::UseThreadCpuClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800177 return (clock_source_ == TraceClockSource::kThreadCpu) ||
178 (clock_source_ == TraceClockSource::kDual);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800179}
180
Elliott Hughese119a362012-05-22 17:37:06 -0700181bool Trace::UseWallClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800182 return (clock_source_ == TraceClockSource::kWall) ||
183 (clock_source_ == TraceClockSource::kDual);
Elliott Hughese119a362012-05-22 17:37:06 -0700184}
185
Jeff Haoc5d824a2014-07-28 18:35:38 -0700186void Trace::MeasureClockOverhead() {
187 if (UseThreadCpuClock()) {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700188 Thread::Current()->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800189 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700190 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800191 MicroTime();
192 }
193}
194
Jeff Hao5ce4b172013-08-16 16:27:18 -0700195// Compute an average time taken to measure clocks.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700196uint32_t Trace::GetClockOverheadNanoSeconds() {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700197 Thread* self = Thread::Current();
198 uint64_t start = self->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800199
200 for (int i = 4000; i > 0; i--) {
Jeff Haoc5d824a2014-07-28 18:35:38 -0700201 MeasureClockOverhead();
202 MeasureClockOverhead();
203 MeasureClockOverhead();
204 MeasureClockOverhead();
205 MeasureClockOverhead();
206 MeasureClockOverhead();
207 MeasureClockOverhead();
208 MeasureClockOverhead();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800209 }
210
Jeff Hao5ce4b172013-08-16 16:27:18 -0700211 uint64_t elapsed_us = self->GetCpuMicroTime() - start;
212 return static_cast<uint32_t>(elapsed_us / 32);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800213}
214
Elliott Hughesffb465f2012-03-01 18:46:05 -0800215// TODO: put this somewhere with the big-endian equivalent used by JDWP.
216static void Append2LE(uint8_t* buf, uint16_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700217 *buf++ = static_cast<uint8_t>(val);
218 *buf++ = static_cast<uint8_t>(val >> 8);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800219}
220
Elliott Hughesffb465f2012-03-01 18:46:05 -0800221// TODO: put this somewhere with the big-endian equivalent used by JDWP.
222static void Append4LE(uint8_t* buf, uint32_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700223 *buf++ = static_cast<uint8_t>(val);
224 *buf++ = static_cast<uint8_t>(val >> 8);
225 *buf++ = static_cast<uint8_t>(val >> 16);
226 *buf++ = static_cast<uint8_t>(val >> 24);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800227}
228
Elliott Hughesffb465f2012-03-01 18:46:05 -0800229// TODO: put this somewhere with the big-endian equivalent used by JDWP.
230static void Append8LE(uint8_t* buf, uint64_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700231 *buf++ = static_cast<uint8_t>(val);
232 *buf++ = static_cast<uint8_t>(val >> 8);
233 *buf++ = static_cast<uint8_t>(val >> 16);
234 *buf++ = static_cast<uint8_t>(val >> 24);
235 *buf++ = static_cast<uint8_t>(val >> 32);
236 *buf++ = static_cast<uint8_t>(val >> 40);
237 *buf++ = static_cast<uint8_t>(val >> 48);
238 *buf++ = static_cast<uint8_t>(val >> 56);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800239}
240
Jeff Hao0abc72e2013-08-13 13:45:14 -0700241static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
242 BuildStackTraceVisitor build_trace_visitor(thread);
243 build_trace_visitor.WalkStack();
Ian Rogerse2f77e72013-08-13 19:19:40 -0700244 std::vector<mirror::ArtMethod*>* stack_trace = build_trace_visitor.GetStackTrace();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700245 Trace* the_trace = reinterpret_cast<Trace*>(arg);
246 the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
247}
248
Andreas Gampeca714582015-04-03 19:41:34 -0700249static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700250 thread->SetTraceClockBase(0);
251 std::vector<mirror::ArtMethod*>* stack_trace = thread->GetStackTraceSample();
Andreas Gampe40da2862015-02-27 12:49:04 -0800252 thread->SetStackTraceSample(nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700253 delete stack_trace;
254}
255
Jeff Hao0abc72e2013-08-13 13:45:14 -0700256void Trace::CompareAndUpdateStackTrace(Thread* thread,
Ian Rogerse2f77e72013-08-13 19:19:40 -0700257 std::vector<mirror::ArtMethod*>* stack_trace) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700258 CHECK_EQ(pthread_self(), sampling_pthread_);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700259 std::vector<mirror::ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
260 // Update the thread's stack trace sample.
261 thread->SetStackTraceSample(stack_trace);
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700262 // Read timer clocks to use for all events in this trace.
263 uint32_t thread_clock_diff = 0;
264 uint32_t wall_clock_diff = 0;
265 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
Andreas Gampe40da2862015-02-27 12:49:04 -0800266 if (old_stack_trace == nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700267 // If there's no previous stack trace sample for this thread, log an entry event for all
Jeff Hao0abc72e2013-08-13 13:45:14 -0700268 // methods in the trace.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700269 for (std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700270 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 }
274 } else {
275 // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
276 // events accordingly.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700277 std::vector<mirror::ArtMethod*>::reverse_iterator old_rit = old_stack_trace->rbegin();
278 std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700279 // Iterate bottom-up over both traces until there's a difference between them.
280 while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
281 old_rit++;
282 rit++;
283 }
284 // Iterate top-down over the old trace until the point where they differ, emitting exit events.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700285 for (std::vector<mirror::ArtMethod*>::iterator old_it = old_stack_trace->begin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700286 old_it != old_rit.base(); ++old_it) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700287 LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
288 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700289 }
290 // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
291 for (; rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700292 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
293 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700294 }
Jeff Hao5ce4b172013-08-16 16:27:18 -0700295 FreeStackTrace(old_stack_trace);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700296 }
297}
298
299void* Trace::RunSamplingThread(void* arg) {
300 Runtime* runtime = Runtime::Current();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800301 intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
Jeff Hao4044bda2014-01-06 15:50:45 -0800302 CHECK_GE(interval_us, 0);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700303 CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800304 !runtime->IsAotCompiler()));
Jeff Hao0abc72e2013-08-13 13:45:14 -0700305
306 while (true) {
Jeff Hao23009dc2013-08-22 15:36:42 -0700307 usleep(interval_us);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700308 ATRACE_BEGIN("Profile sampling");
Jeff Hao0abc72e2013-08-13 13:45:14 -0700309 Thread* self = Thread::Current();
310 Trace* the_trace;
311 {
312 MutexLock mu(self, *Locks::trace_lock_);
313 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800314 if (the_trace == nullptr) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700315 break;
316 }
317 }
318
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700319 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700320 {
321 MutexLock mu(self, *Locks::thread_list_lock_);
322 runtime->GetThreadList()->ForEach(GetSample, the_trace);
323 }
324 runtime->GetThreadList()->ResumeAll();
Jeff Hao5ce4b172013-08-16 16:27:18 -0700325 ATRACE_END();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700326 }
327
328 runtime->DetachCurrentThread();
Andreas Gampe40da2862015-02-27 12:49:04 -0800329 return nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700330}
331
Ian Rogers62d6c772013-02-27 08:32:07 -0800332void Trace::Start(const char* trace_filename, int trace_fd, int buffer_size, int flags,
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700333 TraceOutputMode output_mode, TraceMode trace_mode, int interval_us) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800334 Thread* self = Thread::Current();
335 {
336 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800337 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800338 LOG(ERROR) << "Trace already in progress, ignoring this request";
339 return;
340 }
jeffhaoe343b762011-12-05 16:36:44 -0800341 }
Jeff Haod063d912014-09-08 09:38:18 -0700342
343 // Check interval if sampling is enabled
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700344 if (trace_mode == TraceMode::kSampling && interval_us <= 0) {
Jeff Haod063d912014-09-08 09:38:18 -0700345 LOG(ERROR) << "Invalid sampling interval: " << interval_us;
346 ScopedObjectAccess soa(self);
347 ThrowRuntimeException("Invalid sampling interval: %d", interval_us);
348 return;
349 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800350
jeffhao2692b572011-12-16 15:42:28 -0800351 // Open trace file if not going directly to ddms.
Ian Rogers700a4022014-05-19 16:49:03 -0700352 std::unique_ptr<File> trace_file;
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700353 if (output_mode != TraceOutputMode::kDDMS) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800354 if (trace_fd < 0) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700355 trace_file.reset(OS::CreateEmptyFile(trace_filename));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800356 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800357 trace_file.reset(new File(trace_fd, "tracefile"));
Elliott Hughes76160052012-12-12 16:31:20 -0800358 trace_file->DisableAutoClose();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800359 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800360 if (trace_file.get() == nullptr) {
jeffhaob5e81852012-03-12 11:15:45 -0700361 PLOG(ERROR) << "Unable to open trace file '" << trace_filename << "'";
Ian Rogers62d6c772013-02-27 08:32:07 -0800362 ScopedObjectAccess soa(self);
363 ThrowRuntimeException("Unable to open trace file '%s'", trace_filename);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800364 return;
365 }
366 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800367
Jeff Haod063d912014-09-08 09:38:18 -0700368 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700369
370 // Enable count of allocs if specified in the flags.
371 bool enable_stats = false;
372
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700373 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Haod063d912014-09-08 09:38:18 -0700374
jeffhao2692b572011-12-16 15:42:28 -0800375 // Create Trace object.
Ian Rogers62d6c772013-02-27 08:32:07 -0800376 {
377 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800378 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800379 LOG(ERROR) << "Trace already in progress, ignoring this request";
380 } else {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700381 enable_stats = (flags && kTraceCountAllocs) != 0;
Andreas Gampe40da2862015-02-27 12:49:04 -0800382 the_trace_ = new Trace(trace_file.release(), trace_filename, buffer_size, flags, output_mode,
383 trace_mode);
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700384 if (trace_mode == TraceMode::kSampling) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800385 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
Jeff Hao23009dc2013-08-22 15:36:42 -0700386 reinterpret_cast<void*>(interval_us)),
387 "Sampling profiler thread");
Andreas Gampe40da2862015-02-27 12:49:04 -0800388 the_trace_->interval_us_ = interval_us;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700389 } else {
390 runtime->GetInstrumentation()->AddListener(the_trace_,
391 instrumentation::Instrumentation::kMethodEntered |
392 instrumentation::Instrumentation::kMethodExited |
393 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe40da2862015-02-27 12:49:04 -0800394 // TODO: In full-PIC mode, we don't need to fully deopt.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100395 runtime->GetInstrumentation()->EnableMethodTracing();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700396 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800397 }
jeffhao0791adc2012-04-04 11:14:32 -0700398 }
Jeff Haod063d912014-09-08 09:38:18 -0700399
Ian Rogers62d6c772013-02-27 08:32:07 -0800400 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700401
402 // Can't call this when holding the mutator lock.
403 if (enable_stats) {
404 runtime->SetStatsEnabled(true);
405 }
jeffhao2692b572011-12-16 15:42:28 -0800406}
407
Andreas Gampe40da2862015-02-27 12:49:04 -0800408void Trace::StopTracing(bool finish_tracing, bool flush_file) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700409 bool stop_alloc_counting = false;
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700410 Runtime* const runtime = Runtime::Current();
411 Trace* the_trace = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700412 pthread_t sampling_pthread = 0U;
Ian Rogers62d6c772013-02-27 08:32:07 -0800413 {
414 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800415 if (the_trace_ == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800416 LOG(ERROR) << "Trace stop requested, but no trace currently running";
417 } else {
418 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800419 the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700420 sampling_pthread = sampling_pthread_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800421 }
jeffhao2692b572011-12-16 15:42:28 -0800422 }
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700423 // Make sure that we join before we delete the trace since we don't want to have
424 // the sampling thread access a stale pointer. This finishes since the sampling thread exits when
425 // the_trace_ is null.
426 if (sampling_pthread != 0U) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800427 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700428 sampling_pthread_ = 0U;
429 }
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700430 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Andreas Gampe40da2862015-02-27 12:49:04 -0800431
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700432 if (the_trace != nullptr) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800433 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
434 if (finish_tracing) {
435 the_trace->FinishTracing();
436 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700437
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700438 if (the_trace->trace_mode_ == TraceMode::kSampling) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700439 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700440 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700441 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100442 runtime->GetInstrumentation()->DisableMethodTracing();
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700443 runtime->GetInstrumentation()->RemoveListener(
444 the_trace, instrumentation::Instrumentation::kMethodEntered |
445 instrumentation::Instrumentation::kMethodExited |
446 instrumentation::Instrumentation::kMethodUnwind);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700447 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800448 if (the_trace->trace_file_.get() != nullptr) {
449 // Do not try to erase, so flush and close explicitly.
Andreas Gampe40da2862015-02-27 12:49:04 -0800450 if (flush_file) {
451 if (the_trace->trace_file_->Flush() != 0) {
452 PLOG(ERROR) << "Could not flush trace file.";
453 }
454 } else {
455 the_trace->trace_file_->MarkUnchecked(); // Do not trigger guard.
Andreas Gampe4303ba92014-11-06 01:00:46 -0800456 }
457 if (the_trace->trace_file_->Close() != 0) {
458 PLOG(ERROR) << "Could not close trace file.";
459 }
460 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800461 delete the_trace;
462 }
463 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700464 if (stop_alloc_counting) {
465 // Can be racy since SetStatsEnabled is not guarded by any locks.
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700466 runtime->SetStatsEnabled(false);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700467 }
jeffhao2692b572011-12-16 15:42:28 -0800468}
469
Andreas Gampe40da2862015-02-27 12:49:04 -0800470void Trace::Abort() {
471 // Do not write anything anymore.
472 StopTracing(false, false);
473}
474
475void Trace::Stop() {
476 // Finish writing.
477 StopTracing(true, true);
478}
479
jeffhaob5e81852012-03-12 11:15:45 -0700480void Trace::Shutdown() {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700481 if (GetMethodTracingMode() != kTracingInactive) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800482 Stop();
jeffhaob5e81852012-03-12 11:15:45 -0700483 }
jeffhaob5e81852012-03-12 11:15:45 -0700484}
485
Andreas Gampe40da2862015-02-27 12:49:04 -0800486void Trace::Pause() {
487 bool stop_alloc_counting = false;
488 Runtime* runtime = Runtime::Current();
489 Trace* the_trace = nullptr;
490
491 pthread_t sampling_pthread = 0U;
492 {
493 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
494 if (the_trace_ == nullptr) {
495 LOG(ERROR) << "Trace pause requested, but no trace currently running";
496 return;
497 } else {
498 the_trace = the_trace_;
499 sampling_pthread = sampling_pthread_;
500 }
501 }
502
503 if (sampling_pthread != 0U) {
504 {
505 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
506 the_trace_ = nullptr;
507 }
508 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
509 sampling_pthread_ = 0U;
510 {
511 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
512 the_trace_ = the_trace;
513 }
514 }
515
516 if (the_trace != nullptr) {
517 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
518 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
519
520 if (the_trace->trace_mode_ == TraceMode::kSampling) {
521 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
522 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
523 } else {
524 runtime->GetInstrumentation()->DisableMethodTracing();
525 runtime->GetInstrumentation()->RemoveListener(the_trace,
526 instrumentation::Instrumentation::kMethodEntered |
527 instrumentation::Instrumentation::kMethodExited |
528 instrumentation::Instrumentation::kMethodUnwind);
529 }
530 runtime->GetThreadList()->ResumeAll();
531 }
532
533 if (stop_alloc_counting) {
534 // Can be racy since SetStatsEnabled is not guarded by any locks.
535 Runtime::Current()->SetStatsEnabled(false);
536 }
537}
538
539void Trace::Resume() {
540 Thread* self = Thread::Current();
541 Trace* the_trace;
542 {
543 MutexLock mu(self, *Locks::trace_lock_);
544 if (the_trace_ == nullptr) {
545 LOG(ERROR) << "No trace to resume (or sampling mode), ignoring this request";
546 return;
547 }
548 the_trace = the_trace_;
549 }
550
551 Runtime* runtime = Runtime::Current();
552
553 // Enable count of allocs if specified in the flags.
554 bool enable_stats = (the_trace->flags_ && kTraceCountAllocs) != 0;
555
556 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
557
558 // Reenable.
559 if (the_trace->trace_mode_ == TraceMode::kSampling) {
560 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
561 reinterpret_cast<void*>(the_trace->interval_us_)), "Sampling profiler thread");
562 } else {
563 runtime->GetInstrumentation()->AddListener(the_trace,
564 instrumentation::Instrumentation::kMethodEntered |
565 instrumentation::Instrumentation::kMethodExited |
566 instrumentation::Instrumentation::kMethodUnwind);
567 // TODO: In full-PIC mode, we don't need to fully deopt.
568 runtime->GetInstrumentation()->EnableMethodTracing();
569 }
570
571 runtime->GetThreadList()->ResumeAll();
572
573 // Can't call this when holding the mutator lock.
574 if (enable_stats) {
575 runtime->SetStatsEnabled(true);
576 }
577}
578
Jeff Hao64caa7d2013-08-29 11:18:01 -0700579TracingMode Trace::GetMethodTracingMode() {
Ian Rogers62d6c772013-02-27 08:32:07 -0800580 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800581 if (the_trace_ == nullptr) {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700582 return kTracingInactive;
Jeff Hao64caa7d2013-08-29 11:18:01 -0700583 } else {
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700584 switch (the_trace_->trace_mode_) {
585 case TraceMode::kSampling:
586 return kSampleProfilingActive;
587 case TraceMode::kMethodTracing:
588 return kMethodTracingActive;
589 }
590 LOG(FATAL) << "Unreachable";
591 UNREACHABLE();
Jeff Hao64caa7d2013-08-29 11:18:01 -0700592 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800593}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800594
Andreas Gampe40da2862015-02-27 12:49:04 -0800595static constexpr size_t kStreamingBufferSize = 16 * KB;
596
597Trace::Trace(File* trace_file, const char* trace_name, int buffer_size, int flags,
598 TraceOutputMode output_mode, TraceMode trace_mode)
599 : trace_file_(trace_file),
600 buf_(new uint8_t[output_mode == TraceOutputMode::kStreaming ?
601 kStreamingBufferSize :
602 buffer_size]()),
603 flags_(flags), trace_output_mode_(output_mode), trace_mode_(trace_mode),
604 clock_source_(default_clock_source_),
605 buffer_size_(output_mode == TraceOutputMode::kStreaming ?
606 kStreamingBufferSize :
607 buffer_size),
608 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 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800624
jeffhao2692b572011-12-16 15:42:28 -0800625 // Update current offset.
Ian Rogers8ab25ef2014-07-09 18:00:50 -0700626 cur_offset_.StoreRelaxed(kTraceHeaderLength);
Andreas Gampe40da2862015-02-27 12:49:04 -0800627
628 if (output_mode == TraceOutputMode::kStreaming) {
629 streaming_file_name_ = trace_name;
630 streaming_lock_ = new Mutex("tracing lock");
631 seen_threads_.reset(new ThreadIDBitSet());
632 }
633}
634
635Trace::~Trace() {
636 delete streaming_lock_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800637}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800638
Ian Rogerse63db272014-07-15 15:36:11 -0700639static void DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source)
Ian Rogers62d6c772013-02-27 08:32:07 -0800640 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
641 uint8_t* ptr = buf + kTraceHeaderLength;
642 uint8_t* end = buf + buf_size;
643
644 while (ptr < end) {
645 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700646 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800647 TraceAction action = DecodeTraceAction(tmid);
648 LOG(INFO) << PrettyMethod(method) << " " << static_cast<int>(action);
649 ptr += GetRecordSize(clock_source);
650 }
jeffhaoe343b762011-12-05 16:36:44 -0800651}
652
Andreas Gampe40da2862015-02-27 12:49:04 -0800653static void GetVisitedMethodsFromBitSets(
654 const std::map<mirror::DexCache*, DexIndexBitSet*>& seen_methods,
655 std::set<mirror::ArtMethod*>* visited_methods) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
656 for (auto& e : seen_methods) {
657 DexIndexBitSet* bit_set = e.second;
658 for (uint32_t i = 0; i < bit_set->size(); ++i) {
659 if ((*bit_set)[i]) {
660 visited_methods->insert(e.first->GetResolvedMethod(i));
661 }
662 }
663 }
664}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800665
Andreas Gampe40da2862015-02-27 12:49:04 -0800666void Trace::FinishTracing() {
667 size_t final_offset = 0;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800668
Brian Carlstromea46f952013-07-30 01:26:50 -0700669 std::set<mirror::ArtMethod*> visited_methods;
Andreas Gampe40da2862015-02-27 12:49:04 -0800670 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
671 // Write the secondary file with all the method names.
672 GetVisitedMethodsFromBitSets(seen_methods_, &visited_methods);
673
674 // Clean up.
675 for (auto& e : seen_methods_) {
676 delete e.second;
677 }
678 } else {
679 final_offset = cur_offset_.LoadRelaxed();
680 GetVisitedMethods(final_offset, &visited_methods);
681 }
682
683 // Compute elapsed time.
684 uint64_t elapsed = MicroTime() - start_time_;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800685
686 std::ostringstream os;
687
688 os << StringPrintf("%cversion\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800689 os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800690 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
691 if (UseThreadCpuClock()) {
692 if (UseWallClock()) {
693 os << StringPrintf("clock=dual\n");
694 } else {
695 os << StringPrintf("clock=thread-cpu\n");
696 }
697 } else {
698 os << StringPrintf("clock=wall\n");
699 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800700 os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
Andreas Gampe40da2862015-02-27 12:49:04 -0800701 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
702 size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
703 os << StringPrintf("num-method-calls=%zd\n", num_records);
704 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700705 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800706 os << StringPrintf("vm=art\n");
John Reck0624a272015-03-26 15:47:54 -0700707 os << StringPrintf("pid=%d\n", getpid());
jeffhao0791adc2012-04-04 11:14:32 -0700708 if ((flags_ & kTraceCountAllocs) != 0) {
709 os << StringPrintf("alloc-count=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS));
710 os << StringPrintf("alloc-size=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES));
711 os << StringPrintf("gc-count=%d\n", Runtime::Current()->GetStat(KIND_GC_INVOCATIONS));
712 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800713 os << StringPrintf("%cthreads\n", kTraceTokenChar);
714 DumpThreadList(os);
715 os << StringPrintf("%cmethods\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800716 DumpMethodList(os, visited_methods);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800717 os << StringPrintf("%cend\n", kTraceTokenChar);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800718 std::string header(os.str());
Andreas Gampe40da2862015-02-27 12:49:04 -0800719
720 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
721 File file;
722 if (!file.Open(streaming_file_name_ + ".sec", O_CREAT | O_WRONLY)) {
723 LOG(WARNING) << "Could not open secondary trace file!";
724 return;
Ian Rogers62d6c772013-02-27 08:32:07 -0800725 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800726 if (!file.WriteFully(header.c_str(), header.length())) {
727 file.Erase();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700728 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
729 PLOG(ERROR) << detail;
Ian Rogers62d6c772013-02-27 08:32:07 -0800730 ThrowRuntimeException("%s", detail.c_str());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800731 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800732 if (file.FlushCloseOrErase() != 0) {
733 PLOG(ERROR) << "Could not write secondary file";
734 }
735 } else {
736 if (trace_file_.get() == nullptr) {
737 iovec iov[2];
738 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
739 iov[0].iov_len = header.length();
740 iov[1].iov_base = buf_.get();
741 iov[1].iov_len = final_offset;
742 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
743 const bool kDumpTraceInfo = false;
744 if (kDumpTraceInfo) {
745 LOG(INFO) << "Trace sent:\n" << header;
746 DumpBuf(buf_.get(), final_offset, clock_source_);
747 }
748 } else {
749 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
750 !trace_file_->WriteFully(buf_.get(), final_offset)) {
751 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
752 PLOG(ERROR) << detail;
753 ThrowRuntimeException("%s", detail.c_str());
754 }
755 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800756 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800757}
758
Ian Rogers62d6c772013-02-27 08:32:07 -0800759void Trace::DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800760 mirror::ArtMethod* method, uint32_t new_dex_pc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700761 UNUSED(thread, this_object, method, new_dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800762 // We're not recorded to listen to this kind of event, so complain.
763 LOG(ERROR) << "Unexpected dex PC event in tracing " << PrettyMethod(method) << " " << new_dex_pc;
Andreas Gampec8ccf682014-09-29 20:07:43 -0700764}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800765
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700766void Trace::FieldRead(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700767 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200768 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700769 UNUSED(thread, this_object, method, dex_pc, field);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200770 // We're not recorded to listen to this kind of event, so complain.
771 LOG(ERROR) << "Unexpected field read event in tracing " << PrettyMethod(method) << " " << dex_pc;
772}
773
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700774void Trace::FieldWritten(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700775 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200776 const JValue& field_value)
777 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700778 UNUSED(thread, this_object, method, dex_pc, field, field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200779 // We're not recorded to listen to this kind of event, so complain.
780 LOG(ERROR) << "Unexpected field write event in tracing " << PrettyMethod(method) << " " << dex_pc;
781}
782
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700783void Trace::MethodEntered(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
784 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700785 uint32_t thread_clock_diff = 0;
786 uint32_t wall_clock_diff = 0;
787 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
788 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodEntered,
789 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800790}
791
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700792void Trace::MethodExited(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
793 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED,
794 const JValue& return_value ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700795 uint32_t thread_clock_diff = 0;
796 uint32_t wall_clock_diff = 0;
797 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
798 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodExited,
799 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800800}
801
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700802void Trace::MethodUnwind(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
803 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700804 uint32_t thread_clock_diff = 0;
805 uint32_t wall_clock_diff = 0;
806 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
807 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
808 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800809}
810
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000811void Trace::ExceptionCaught(Thread* thread, mirror::Throwable* exception_object)
Ian Rogers62d6c772013-02-27 08:32:07 -0800812 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000813 UNUSED(thread, exception_object);
Ian Rogers62d6c772013-02-27 08:32:07 -0800814 LOG(ERROR) << "Unexpected exception caught event in tracing";
815}
816
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800817void Trace::BackwardBranch(Thread* /*thread*/, mirror::ArtMethod* method,
818 int32_t /*dex_pc_offset*/)
819 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
820 LOG(ERROR) << "Unexpected backward branch event in tracing" << PrettyMethod(method);
821}
822
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700823void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
824 if (UseThreadCpuClock()) {
825 uint64_t clock_base = thread->GetTraceClockBase();
826 if (UNLIKELY(clock_base == 0)) {
827 // First event, record the base time in the map.
828 uint64_t time = thread->GetCpuMicroTime();
829 thread->SetTraceClockBase(time);
830 } else {
831 *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
832 }
833 }
834 if (UseWallClock()) {
835 *wall_clock_diff = MicroTime() - start_time_;
836 }
837}
838
Andreas Gampe40da2862015-02-27 12:49:04 -0800839bool Trace::RegisterMethod(mirror::ArtMethod* method) {
840 mirror::DexCache* dex_cache = method->GetDexCache();
841 if (dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) != method) {
842 DCHECK(dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) == nullptr);
843 dex_cache->SetResolvedMethod(method->GetDexMethodIndex(), method);
844 }
845 if (seen_methods_.find(dex_cache) == seen_methods_.end()) {
846 seen_methods_.insert(std::make_pair(dex_cache, new DexIndexBitSet()));
847 }
848 DexIndexBitSet* bit_set = seen_methods_.find(dex_cache)->second;
849 if (!(*bit_set)[method->GetDexMethodIndex()]) {
850 bit_set->set(method->GetDexMethodIndex());
851 return true;
852 }
853 return false;
854}
855
856bool Trace::RegisterThread(Thread* thread) {
857 pid_t tid = thread->GetTid();
858 CHECK_LT(0U, static_cast<uint32_t>(tid));
859 CHECK_LT(static_cast<uint32_t>(tid), 65536U);
860
861 if (!(*seen_threads_)[tid]) {
862 seen_threads_->set(tid);
863 return true;
864 }
865 return false;
866}
867
868static std::string GetMethodLine(mirror::ArtMethod* method)
869 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
870 return StringPrintf("%p\t%s\t%s\t%s\t%s\n", method,
871 PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
872 method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
873}
874
875void Trace::WriteToBuf(const uint8_t* src, size_t src_size) {
876 int32_t old_offset = cur_offset_.LoadRelaxed();
877 int32_t new_offset = old_offset + static_cast<int32_t>(src_size);
878 if (new_offset > buffer_size_) {
879 // Flush buffer.
880 if (!trace_file_->WriteFully(buf_.get(), old_offset)) {
881 PLOG(WARNING) << "Failed streaming a tracing event.";
882 }
883 old_offset = 0;
884 new_offset = static_cast<int32_t>(src_size);
885 }
886 cur_offset_.StoreRelease(new_offset);
887 // Fill in data.
888 memcpy(buf_.get() + old_offset, src, src_size);
889}
890
Ian Rogersef7d42f2014-01-06 12:55:46 -0800891void Trace::LogMethodTraceEvent(Thread* thread, mirror::ArtMethod* method,
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700892 instrumentation::Instrumentation::InstrumentationEvent event,
893 uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800894 // Advance cur_offset_ atomically.
895 int32_t new_offset;
Andreas Gampe40da2862015-02-27 12:49:04 -0800896 int32_t old_offset = 0;
897
898 // We do a busy loop here trying to acquire the next offset.
899 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
900 do {
901 old_offset = cur_offset_.LoadRelaxed();
902 new_offset = old_offset + GetRecordSize(clock_source_);
903 if (new_offset > buffer_size_) {
904 overflow_ = true;
905 return;
906 }
907 } while (!cur_offset_.CompareExchangeWeakSequentiallyConsistent(old_offset, new_offset));
908 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800909
Ian Rogers62d6c772013-02-27 08:32:07 -0800910 TraceAction action = kTraceMethodEnter;
911 switch (event) {
912 case instrumentation::Instrumentation::kMethodEntered:
913 action = kTraceMethodEnter;
914 break;
915 case instrumentation::Instrumentation::kMethodExited:
916 action = kTraceMethodExit;
917 break;
918 case instrumentation::Instrumentation::kMethodUnwind:
919 action = kTraceUnroll;
920 break;
921 default:
922 UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
923 }
924
925 uint32_t method_value = EncodeTraceMethodAndAction(method, action);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800926
927 // Write data
Andreas Gampe40da2862015-02-27 12:49:04 -0800928 uint8_t* ptr;
929 static constexpr size_t kPacketSize = 14U; // The maximum size of data in a packet.
930 uint8_t stack_buf[kPacketSize]; // Space to store a packet when in streaming mode.
931 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
932 ptr = stack_buf;
933 } else {
934 ptr = buf_.get() + old_offset;
935 }
936
Ian Rogers62d6c772013-02-27 08:32:07 -0800937 Append2LE(ptr, thread->GetTid());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800938 Append4LE(ptr + 2, method_value);
939 ptr += 6;
940
941 if (UseThreadCpuClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800942 Append4LE(ptr, thread_clock_diff);
943 ptr += 4;
944 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800945 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800946 Append4LE(ptr, wall_clock_diff);
947 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800948 static_assert(kPacketSize == 2 + 4 + 4 + 4, "Packet size incorrect.");
949
950 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
951 MutexLock mu(Thread::Current(), *streaming_lock_); // To serialize writing.
952 if (RegisterMethod(method)) {
953 // Write a special block with the name.
954 std::string method_line(GetMethodLine(method));
955 uint8_t buf2[5];
956 Append2LE(buf2, 0);
957 buf2[2] = kOpNewMethod;
958 Append2LE(buf2 + 3, static_cast<uint16_t>(method_line.length()));
959 WriteToBuf(buf2, sizeof(buf2));
960 WriteToBuf(reinterpret_cast<const uint8_t*>(method_line.c_str()), method_line.length());
961 }
962 if (RegisterThread(thread)) {
963 // It might be better to postpone this. Threads might not have received names...
964 std::string thread_name;
965 thread->GetThreadName(thread_name);
966 uint8_t buf2[7];
967 Append2LE(buf2, 0);
968 buf2[2] = kOpNewThread;
969 Append2LE(buf2 + 3, static_cast<uint16_t>(thread->GetTid()));
970 Append2LE(buf2 + 5, static_cast<uint16_t>(thread_name.length()));
971 WriteToBuf(buf2, sizeof(buf2));
972 WriteToBuf(reinterpret_cast<const uint8_t*>(thread_name.c_str()), thread_name.length());
973 }
974 WriteToBuf(stack_buf, sizeof(stack_buf));
975 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800976}
977
Ian Rogers62d6c772013-02-27 08:32:07 -0800978void Trace::GetVisitedMethods(size_t buf_size,
Brian Carlstromea46f952013-07-30 01:26:50 -0700979 std::set<mirror::ArtMethod*>* visited_methods) {
jeffhao2692b572011-12-16 15:42:28 -0800980 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
Ian Rogers62d6c772013-02-27 08:32:07 -0800981 uint8_t* end = buf_.get() + buf_size;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800982
983 while (ptr < end) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800984 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700985 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800986 visited_methods->insert(method);
987 ptr += GetRecordSize(clock_source_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800988 }
989}
990
Mathieu Chartier02e25112013-08-14 16:14:24 -0700991void Trace::DumpMethodList(std::ostream& os, const std::set<mirror::ArtMethod*>& visited_methods) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700992 for (const auto& method : visited_methods) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800993 os << GetMethodLine(method);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800994 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800995}
996
997static void DumpThread(Thread* t, void* arg) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800998 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
999 std::string name;
1000 t->GetThreadName(name);
1001 os << t->GetTid() << "\t" << name << "\n";
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001002}
1003
1004void Trace::DumpThreadList(std::ostream& os) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001005 Thread* self = Thread::Current();
Jeff Haoe094b872014-10-14 13:12:01 -07001006 for (auto it : exited_threads_) {
1007 os << it.first << "\t" << it.second << "\n";
1008 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001009 Locks::thread_list_lock_->AssertNotHeld(self);
1010 MutexLock mu(self, *Locks::thread_list_lock_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001011 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -08001012}
1013
Jeff Haoe094b872014-10-14 13:12:01 -07001014void Trace::StoreExitingThreadInfo(Thread* thread) {
1015 MutexLock mu(thread, *Locks::trace_lock_);
1016 if (the_trace_ != nullptr) {
1017 std::string name;
1018 thread->GetThreadName(name);
Andreas Gampea1785c52014-11-25 20:40:08 -08001019 // The same thread/tid may be used multiple times. As SafeMap::Put does not allow to override
1020 // a previous mapping, use SafeMap::Overwrite.
1021 the_trace_->exited_threads_.Overwrite(thread->GetTid(), name);
Jeff Haoe094b872014-10-14 13:12:01 -07001022 }
1023}
1024
Andreas Gampe40da2862015-02-27 12:49:04 -08001025Trace::TraceOutputMode Trace::GetOutputMode() {
1026 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1027 CHECK(the_trace_ != nullptr) << "Trace output mode requested, but no trace currently running";
1028 return the_trace_->trace_output_mode_;
1029}
1030
1031Trace::TraceMode Trace::GetMode() {
1032 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1033 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1034 return the_trace_->trace_mode_;
1035}
1036
jeffhaoe343b762011-12-05 16:36:44 -08001037} // namespace art