blob: 9eca517dca2666d7adbc91338d139789fb0f3166 [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
Brian Carlstromea46f952013-07-30 01:26:50 -0700129static mirror::ArtMethod* DecodeTraceMethodId(uint32_t tmid) {
130 return reinterpret_cast<mirror::ArtMethod*>(tmid & ~kTraceMethodActionMask);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800131}
Elliott Hughese119a362012-05-22 17:37:06 -0700132
Ian Rogers62d6c772013-02-27 08:32:07 -0800133static TraceAction DecodeTraceAction(uint32_t tmid) {
134 return static_cast<TraceAction>(tmid & kTraceMethodActionMask);
135}
136
Ian Rogersef7d42f2014-01-06 12:55:46 -0800137static uint32_t EncodeTraceMethodAndAction(mirror::ArtMethod* method,
Ian Rogers62d6c772013-02-27 08:32:07 -0800138 TraceAction action) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800139 uint32_t tmid = PointerToLowMemUInt32(method) | action;
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 DCHECK_EQ(method, DecodeTraceMethodId(tmid));
141 return tmid;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800142}
143
Jeff Hao5ce4b172013-08-16 16:27:18 -0700144std::vector<mirror::ArtMethod*>* Trace::AllocStackTrace() {
Andreas Gampe40da2862015-02-27 12:49:04 -0800145 if (temp_stack_trace_.get() != nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700146 return temp_stack_trace_.release();
147 } else {
148 return new std::vector<mirror::ArtMethod*>();
149 }
150}
151
152void Trace::FreeStackTrace(std::vector<mirror::ArtMethod*>* stack_trace) {
153 stack_trace->clear();
154 temp_stack_trace_.reset(stack_trace);
155}
156
Ian Rogerse63db272014-07-15 15:36:11 -0700157void Trace::SetDefaultClockSource(TraceClockSource clock_source) {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800158#if defined(__linux__)
Ian Rogers62d6c772013-02-27 08:32:07 -0800159 default_clock_source_ = clock_source;
160#else
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800161 if (clock_source != TraceClockSource::kWall) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700162 LOG(WARNING) << "Ignoring tracing request to use CPU time.";
Ian Rogers62d6c772013-02-27 08:32:07 -0800163 }
164#endif
165}
166
Ian Rogerse63db272014-07-15 15:36:11 -0700167static uint16_t GetTraceVersion(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800168 return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800169 : kTraceVersionSingleClock;
170}
171
Ian Rogerse63db272014-07-15 15:36:11 -0700172static uint16_t GetRecordSize(TraceClockSource clock_source) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800173 return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
Ian Rogers62d6c772013-02-27 08:32:07 -0800174 : kTraceRecordSizeSingleClock;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800175}
176
Elliott Hughese119a362012-05-22 17:37:06 -0700177bool Trace::UseThreadCpuClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800178 return (clock_source_ == TraceClockSource::kThreadCpu) ||
179 (clock_source_ == TraceClockSource::kDual);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800180}
181
Elliott Hughese119a362012-05-22 17:37:06 -0700182bool Trace::UseWallClock() {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800183 return (clock_source_ == TraceClockSource::kWall) ||
184 (clock_source_ == TraceClockSource::kDual);
Elliott Hughese119a362012-05-22 17:37:06 -0700185}
186
Jeff Haoc5d824a2014-07-28 18:35:38 -0700187void Trace::MeasureClockOverhead() {
188 if (UseThreadCpuClock()) {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700189 Thread::Current()->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800190 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700191 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800192 MicroTime();
193 }
194}
195
Jeff Hao5ce4b172013-08-16 16:27:18 -0700196// Compute an average time taken to measure clocks.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700197uint32_t Trace::GetClockOverheadNanoSeconds() {
Jeff Hao57dac6e2013-08-15 16:36:24 -0700198 Thread* self = Thread::Current();
199 uint64_t start = self->GetCpuMicroTime();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800200
201 for (int i = 4000; i > 0; i--) {
Jeff Haoc5d824a2014-07-28 18:35:38 -0700202 MeasureClockOverhead();
203 MeasureClockOverhead();
204 MeasureClockOverhead();
205 MeasureClockOverhead();
206 MeasureClockOverhead();
207 MeasureClockOverhead();
208 MeasureClockOverhead();
209 MeasureClockOverhead();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800210 }
211
Jeff Hao5ce4b172013-08-16 16:27:18 -0700212 uint64_t elapsed_us = self->GetCpuMicroTime() - start;
213 return static_cast<uint32_t>(elapsed_us / 32);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800214}
215
Elliott Hughesffb465f2012-03-01 18:46:05 -0800216// TODO: put this somewhere with the big-endian equivalent used by JDWP.
217static void Append2LE(uint8_t* buf, uint16_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700218 *buf++ = static_cast<uint8_t>(val);
219 *buf++ = static_cast<uint8_t>(val >> 8);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800220}
221
Elliott Hughesffb465f2012-03-01 18:46:05 -0800222// TODO: put this somewhere with the big-endian equivalent used by JDWP.
223static void Append4LE(uint8_t* buf, uint32_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700224 *buf++ = static_cast<uint8_t>(val);
225 *buf++ = static_cast<uint8_t>(val >> 8);
226 *buf++ = static_cast<uint8_t>(val >> 16);
227 *buf++ = static_cast<uint8_t>(val >> 24);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800228}
229
Elliott Hughesffb465f2012-03-01 18:46:05 -0800230// TODO: put this somewhere with the big-endian equivalent used by JDWP.
231static void Append8LE(uint8_t* buf, uint64_t val) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700232 *buf++ = static_cast<uint8_t>(val);
233 *buf++ = static_cast<uint8_t>(val >> 8);
234 *buf++ = static_cast<uint8_t>(val >> 16);
235 *buf++ = static_cast<uint8_t>(val >> 24);
236 *buf++ = static_cast<uint8_t>(val >> 32);
237 *buf++ = static_cast<uint8_t>(val >> 40);
238 *buf++ = static_cast<uint8_t>(val >> 48);
239 *buf++ = static_cast<uint8_t>(val >> 56);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800240}
241
Jeff Hao0abc72e2013-08-13 13:45:14 -0700242static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
243 BuildStackTraceVisitor build_trace_visitor(thread);
244 build_trace_visitor.WalkStack();
Ian Rogerse2f77e72013-08-13 19:19:40 -0700245 std::vector<mirror::ArtMethod*>* stack_trace = build_trace_visitor.GetStackTrace();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700246 Trace* the_trace = reinterpret_cast<Trace*>(arg);
247 the_trace->CompareAndUpdateStackTrace(thread, stack_trace);
248}
249
Andreas Gampeca714582015-04-03 19:41:34 -0700250static void ClearThreadStackTraceAndClockBase(Thread* thread, void* arg ATTRIBUTE_UNUSED) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700251 thread->SetTraceClockBase(0);
252 std::vector<mirror::ArtMethod*>* stack_trace = thread->GetStackTraceSample();
Andreas Gampe40da2862015-02-27 12:49:04 -0800253 thread->SetStackTraceSample(nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700254 delete stack_trace;
255}
256
Jeff Hao0abc72e2013-08-13 13:45:14 -0700257void Trace::CompareAndUpdateStackTrace(Thread* thread,
Ian Rogerse2f77e72013-08-13 19:19:40 -0700258 std::vector<mirror::ArtMethod*>* stack_trace) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700259 CHECK_EQ(pthread_self(), sampling_pthread_);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700260 std::vector<mirror::ArtMethod*>* old_stack_trace = thread->GetStackTraceSample();
261 // Update the thread's stack trace sample.
262 thread->SetStackTraceSample(stack_trace);
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700263 // Read timer clocks to use for all events in this trace.
264 uint32_t thread_clock_diff = 0;
265 uint32_t wall_clock_diff = 0;
266 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
Andreas Gampe40da2862015-02-27 12:49:04 -0800267 if (old_stack_trace == nullptr) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700268 // If there's no previous stack trace sample for this thread, log an entry event for all
Jeff Hao0abc72e2013-08-13 13:45:14 -0700269 // methods in the trace.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700270 for (std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700271 rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700272 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
273 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700274 }
275 } else {
276 // If there's a previous stack trace for this thread, diff the traces and emit entry and exit
277 // events accordingly.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700278 std::vector<mirror::ArtMethod*>::reverse_iterator old_rit = old_stack_trace->rbegin();
279 std::vector<mirror::ArtMethod*>::reverse_iterator rit = stack_trace->rbegin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700280 // Iterate bottom-up over both traces until there's a difference between them.
281 while (old_rit != old_stack_trace->rend() && rit != stack_trace->rend() && *old_rit == *rit) {
282 old_rit++;
283 rit++;
284 }
285 // Iterate top-down over the old trace until the point where they differ, emitting exit events.
Ian Rogerse2f77e72013-08-13 19:19:40 -0700286 for (std::vector<mirror::ArtMethod*>::iterator old_it = old_stack_trace->begin();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700287 old_it != old_rit.base(); ++old_it) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700288 LogMethodTraceEvent(thread, *old_it, instrumentation::Instrumentation::kMethodExited,
289 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700290 }
291 // Iterate bottom-up over the new trace from the point where they differ, emitting entry events.
292 for (; rit != stack_trace->rend(); ++rit) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700293 LogMethodTraceEvent(thread, *rit, instrumentation::Instrumentation::kMethodEntered,
294 thread_clock_diff, wall_clock_diff);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700295 }
Jeff Hao5ce4b172013-08-16 16:27:18 -0700296 FreeStackTrace(old_stack_trace);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700297 }
298}
299
300void* Trace::RunSamplingThread(void* arg) {
301 Runtime* runtime = Runtime::Current();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800302 intptr_t interval_us = reinterpret_cast<intptr_t>(arg);
Jeff Hao4044bda2014-01-06 15:50:45 -0800303 CHECK_GE(interval_us, 0);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700304 CHECK(runtime->AttachCurrentThread("Sampling Profiler", true, runtime->GetSystemThreadGroup(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800305 !runtime->IsAotCompiler()));
Jeff Hao0abc72e2013-08-13 13:45:14 -0700306
307 while (true) {
Jeff Hao23009dc2013-08-22 15:36:42 -0700308 usleep(interval_us);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700309 ATRACE_BEGIN("Profile sampling");
Jeff Hao0abc72e2013-08-13 13:45:14 -0700310 Thread* self = Thread::Current();
311 Trace* the_trace;
312 {
313 MutexLock mu(self, *Locks::trace_lock_);
314 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800315 if (the_trace == nullptr) {
Jeff Hao0abc72e2013-08-13 13:45:14 -0700316 break;
317 }
318 }
319
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700320 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700321 {
322 MutexLock mu(self, *Locks::thread_list_lock_);
323 runtime->GetThreadList()->ForEach(GetSample, the_trace);
324 }
325 runtime->GetThreadList()->ResumeAll();
Jeff Hao5ce4b172013-08-16 16:27:18 -0700326 ATRACE_END();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700327 }
328
329 runtime->DetachCurrentThread();
Andreas Gampe40da2862015-02-27 12:49:04 -0800330 return nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700331}
332
Andreas Gampee34a42c2015-04-25 14:44:29 -0700333void Trace::Start(const char* trace_filename, int trace_fd, size_t buffer_size, int flags,
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700334 TraceOutputMode output_mode, TraceMode trace_mode, int interval_us) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800335 Thread* self = Thread::Current();
336 {
337 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800338 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800339 LOG(ERROR) << "Trace already in progress, ignoring this request";
340 return;
341 }
jeffhaoe343b762011-12-05 16:36:44 -0800342 }
Jeff Haod063d912014-09-08 09:38:18 -0700343
344 // Check interval if sampling is enabled
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700345 if (trace_mode == TraceMode::kSampling && interval_us <= 0) {
Jeff Haod063d912014-09-08 09:38:18 -0700346 LOG(ERROR) << "Invalid sampling interval: " << interval_us;
347 ScopedObjectAccess soa(self);
348 ThrowRuntimeException("Invalid sampling interval: %d", interval_us);
349 return;
350 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800351
jeffhao2692b572011-12-16 15:42:28 -0800352 // Open trace file if not going directly to ddms.
Ian Rogers700a4022014-05-19 16:49:03 -0700353 std::unique_ptr<File> trace_file;
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700354 if (output_mode != TraceOutputMode::kDDMS) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800355 if (trace_fd < 0) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700356 trace_file.reset(OS::CreateEmptyFile(trace_filename));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800357 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800358 trace_file.reset(new File(trace_fd, "tracefile"));
Elliott Hughes76160052012-12-12 16:31:20 -0800359 trace_file->DisableAutoClose();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800360 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800361 if (trace_file.get() == nullptr) {
jeffhaob5e81852012-03-12 11:15:45 -0700362 PLOG(ERROR) << "Unable to open trace file '" << trace_filename << "'";
Ian Rogers62d6c772013-02-27 08:32:07 -0800363 ScopedObjectAccess soa(self);
364 ThrowRuntimeException("Unable to open trace file '%s'", trace_filename);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800365 return;
366 }
367 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800368
Jeff Haod063d912014-09-08 09:38:18 -0700369 Runtime* runtime = Runtime::Current();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700370
371 // Enable count of allocs if specified in the flags.
372 bool enable_stats = false;
373
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700374 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Jeff Haod063d912014-09-08 09:38:18 -0700375
jeffhao2692b572011-12-16 15:42:28 -0800376 // Create Trace object.
Ian Rogers62d6c772013-02-27 08:32:07 -0800377 {
378 MutexLock mu(self, *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800379 if (the_trace_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800380 LOG(ERROR) << "Trace already in progress, ignoring this request";
381 } else {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700382 enable_stats = (flags && kTraceCountAllocs) != 0;
Andreas Gampe40da2862015-02-27 12:49:04 -0800383 the_trace_ = new Trace(trace_file.release(), trace_filename, buffer_size, flags, output_mode,
384 trace_mode);
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700385 if (trace_mode == TraceMode::kSampling) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800386 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
Jeff Hao23009dc2013-08-22 15:36:42 -0700387 reinterpret_cast<void*>(interval_us)),
388 "Sampling profiler thread");
Andreas Gampe40da2862015-02-27 12:49:04 -0800389 the_trace_->interval_us_ = interval_us;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700390 } else {
391 runtime->GetInstrumentation()->AddListener(the_trace_,
392 instrumentation::Instrumentation::kMethodEntered |
393 instrumentation::Instrumentation::kMethodExited |
394 instrumentation::Instrumentation::kMethodUnwind);
Andreas Gampe40da2862015-02-27 12:49:04 -0800395 // TODO: In full-PIC mode, we don't need to fully deopt.
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100396 runtime->GetInstrumentation()->EnableMethodTracing();
Jeff Hao0abc72e2013-08-13 13:45:14 -0700397 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800398 }
jeffhao0791adc2012-04-04 11:14:32 -0700399 }
Jeff Haod063d912014-09-08 09:38:18 -0700400
Ian Rogers62d6c772013-02-27 08:32:07 -0800401 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700402
403 // Can't call this when holding the mutator lock.
404 if (enable_stats) {
405 runtime->SetStatsEnabled(true);
406 }
jeffhao2692b572011-12-16 15:42:28 -0800407}
408
Andreas Gampe40da2862015-02-27 12:49:04 -0800409void Trace::StopTracing(bool finish_tracing, bool flush_file) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700410 bool stop_alloc_counting = false;
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700411 Runtime* const runtime = Runtime::Current();
412 Trace* the_trace = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700413 pthread_t sampling_pthread = 0U;
Ian Rogers62d6c772013-02-27 08:32:07 -0800414 {
415 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800416 if (the_trace_ == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800417 LOG(ERROR) << "Trace stop requested, but no trace currently running";
418 } else {
419 the_trace = the_trace_;
Andreas Gampe40da2862015-02-27 12:49:04 -0800420 the_trace_ = nullptr;
Jeff Hao0abc72e2013-08-13 13:45:14 -0700421 sampling_pthread = sampling_pthread_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800422 }
jeffhao2692b572011-12-16 15:42:28 -0800423 }
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700424 // Make sure that we join before we delete the trace since we don't want to have
425 // the sampling thread access a stale pointer. This finishes since the sampling thread exits when
426 // the_trace_ is null.
427 if (sampling_pthread != 0U) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800428 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700429 sampling_pthread_ = 0U;
430 }
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700431 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
Andreas Gampe40da2862015-02-27 12:49:04 -0800432
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700433 if (the_trace != nullptr) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800434 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
435 if (finish_tracing) {
436 the_trace->FinishTracing();
437 }
Jeff Hao0abc72e2013-08-13 13:45:14 -0700438
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700439 if (the_trace->trace_mode_ == TraceMode::kSampling) {
Jeff Hao5ce4b172013-08-16 16:27:18 -0700440 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700441 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
Jeff Hao5ce4b172013-08-16 16:27:18 -0700442 } else {
Sebastien Hertz138dbfc2013-12-04 18:15:25 +0100443 runtime->GetInstrumentation()->DisableMethodTracing();
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700444 runtime->GetInstrumentation()->RemoveListener(
445 the_trace, instrumentation::Instrumentation::kMethodEntered |
446 instrumentation::Instrumentation::kMethodExited |
447 instrumentation::Instrumentation::kMethodUnwind);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700448 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800449 if (the_trace->trace_file_.get() != nullptr) {
450 // Do not try to erase, so flush and close explicitly.
Andreas Gampe40da2862015-02-27 12:49:04 -0800451 if (flush_file) {
452 if (the_trace->trace_file_->Flush() != 0) {
453 PLOG(ERROR) << "Could not flush trace file.";
454 }
455 } else {
456 the_trace->trace_file_->MarkUnchecked(); // Do not trigger guard.
Andreas Gampe4303ba92014-11-06 01:00:46 -0800457 }
458 if (the_trace->trace_file_->Close() != 0) {
459 PLOG(ERROR) << "Could not close trace file.";
460 }
461 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800462 delete the_trace;
463 }
464 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700465 if (stop_alloc_counting) {
466 // Can be racy since SetStatsEnabled is not guarded by any locks.
Mathieu Chartier02e5f162015-03-11 09:54:22 -0700467 runtime->SetStatsEnabled(false);
Jeff Hao0abc72e2013-08-13 13:45:14 -0700468 }
jeffhao2692b572011-12-16 15:42:28 -0800469}
470
Andreas Gampe40da2862015-02-27 12:49:04 -0800471void Trace::Abort() {
472 // Do not write anything anymore.
473 StopTracing(false, false);
474}
475
476void Trace::Stop() {
477 // Finish writing.
478 StopTracing(true, true);
479}
480
jeffhaob5e81852012-03-12 11:15:45 -0700481void Trace::Shutdown() {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700482 if (GetMethodTracingMode() != kTracingInactive) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800483 Stop();
jeffhaob5e81852012-03-12 11:15:45 -0700484 }
jeffhaob5e81852012-03-12 11:15:45 -0700485}
486
Andreas Gampe40da2862015-02-27 12:49:04 -0800487void Trace::Pause() {
488 bool stop_alloc_counting = false;
489 Runtime* runtime = Runtime::Current();
490 Trace* the_trace = nullptr;
491
492 pthread_t sampling_pthread = 0U;
493 {
494 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
495 if (the_trace_ == nullptr) {
496 LOG(ERROR) << "Trace pause requested, but no trace currently running";
497 return;
498 } else {
499 the_trace = the_trace_;
500 sampling_pthread = sampling_pthread_;
501 }
502 }
503
504 if (sampling_pthread != 0U) {
505 {
506 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
507 the_trace_ = nullptr;
508 }
509 CHECK_PTHREAD_CALL(pthread_join, (sampling_pthread, nullptr), "sampling thread shutdown");
510 sampling_pthread_ = 0U;
511 {
512 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
513 the_trace_ = the_trace;
514 }
515 }
516
517 if (the_trace != nullptr) {
518 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
519 stop_alloc_counting = (the_trace->flags_ & Trace::kTraceCountAllocs) != 0;
520
521 if (the_trace->trace_mode_ == TraceMode::kSampling) {
522 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
523 runtime->GetThreadList()->ForEach(ClearThreadStackTraceAndClockBase, nullptr);
524 } else {
525 runtime->GetInstrumentation()->DisableMethodTracing();
526 runtime->GetInstrumentation()->RemoveListener(the_trace,
527 instrumentation::Instrumentation::kMethodEntered |
528 instrumentation::Instrumentation::kMethodExited |
529 instrumentation::Instrumentation::kMethodUnwind);
530 }
531 runtime->GetThreadList()->ResumeAll();
532 }
533
534 if (stop_alloc_counting) {
535 // Can be racy since SetStatsEnabled is not guarded by any locks.
536 Runtime::Current()->SetStatsEnabled(false);
537 }
538}
539
540void Trace::Resume() {
541 Thread* self = Thread::Current();
542 Trace* the_trace;
543 {
544 MutexLock mu(self, *Locks::trace_lock_);
545 if (the_trace_ == nullptr) {
546 LOG(ERROR) << "No trace to resume (or sampling mode), ignoring this request";
547 return;
548 }
549 the_trace = the_trace_;
550 }
551
552 Runtime* runtime = Runtime::Current();
553
554 // Enable count of allocs if specified in the flags.
555 bool enable_stats = (the_trace->flags_ && kTraceCountAllocs) != 0;
556
557 runtime->GetThreadList()->SuspendAll(__FUNCTION__);
558
559 // Reenable.
560 if (the_trace->trace_mode_ == TraceMode::kSampling) {
561 CHECK_PTHREAD_CALL(pthread_create, (&sampling_pthread_, nullptr, &RunSamplingThread,
562 reinterpret_cast<void*>(the_trace->interval_us_)), "Sampling profiler thread");
563 } else {
564 runtime->GetInstrumentation()->AddListener(the_trace,
565 instrumentation::Instrumentation::kMethodEntered |
566 instrumentation::Instrumentation::kMethodExited |
567 instrumentation::Instrumentation::kMethodUnwind);
568 // TODO: In full-PIC mode, we don't need to fully deopt.
569 runtime->GetInstrumentation()->EnableMethodTracing();
570 }
571
572 runtime->GetThreadList()->ResumeAll();
573
574 // Can't call this when holding the mutator lock.
575 if (enable_stats) {
576 runtime->SetStatsEnabled(true);
577 }
578}
579
Jeff Hao64caa7d2013-08-29 11:18:01 -0700580TracingMode Trace::GetMethodTracingMode() {
Ian Rogers62d6c772013-02-27 08:32:07 -0800581 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800582 if (the_trace_ == nullptr) {
Jeff Hao64caa7d2013-08-29 11:18:01 -0700583 return kTracingInactive;
Jeff Hao64caa7d2013-08-29 11:18:01 -0700584 } else {
Andreas Gampe7e7e0f42015-03-29 15:26:23 -0700585 switch (the_trace_->trace_mode_) {
586 case TraceMode::kSampling:
587 return kSampleProfilingActive;
588 case TraceMode::kMethodTracing:
589 return kMethodTracingActive;
590 }
591 LOG(FATAL) << "Unreachable";
592 UNREACHABLE();
Jeff Hao64caa7d2013-08-29 11:18:01 -0700593 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800594}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800595
Andreas Gampee34a42c2015-04-25 14:44:29 -0700596static constexpr size_t kMinBufSize = 18U; // Trace header is up to 18B.
Andreas Gampe40da2862015-02-27 12:49:04 -0800597
Andreas Gampee34a42c2015-04-25 14:44:29 -0700598Trace::Trace(File* trace_file, const char* trace_name, size_t buffer_size, int flags,
Andreas Gampe40da2862015-02-27 12:49:04 -0800599 TraceOutputMode output_mode, TraceMode trace_mode)
600 : trace_file_(trace_file),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700601 buf_(new uint8_t[std::max(kMinBufSize, buffer_size)]()),
Andreas Gampe40da2862015-02-27 12:49:04 -0800602 flags_(flags), trace_output_mode_(output_mode), trace_mode_(trace_mode),
603 clock_source_(default_clock_source_),
Andreas Gampee34a42c2015-04-25 14:44:29 -0700604 buffer_size_(std::max(kMinBufSize, buffer_size)),
Andreas Gampe40da2862015-02-27 12:49:04 -0800605 start_time_(MicroTime()), clock_overhead_ns_(GetClockOverheadNanoSeconds()), cur_offset_(0),
606 overflow_(false), interval_us_(0), streaming_lock_(nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800607 uint16_t trace_version = GetTraceVersion(clock_source_);
Andreas Gampe40da2862015-02-27 12:49:04 -0800608 if (output_mode == TraceOutputMode::kStreaming) {
609 trace_version |= 0xF0U;
610 }
611 // Set up the beginning of the trace.
jeffhao2692b572011-12-16 15:42:28 -0800612 memset(buf_.get(), 0, kTraceHeaderLength);
613 Append4LE(buf_.get(), kTraceMagicValue);
Ian Rogers62d6c772013-02-27 08:32:07 -0800614 Append2LE(buf_.get() + 4, trace_version);
jeffhao2692b572011-12-16 15:42:28 -0800615 Append2LE(buf_.get() + 6, kTraceHeaderLength);
616 Append8LE(buf_.get() + 8, start_time_);
Ian Rogers62d6c772013-02-27 08:32:07 -0800617 if (trace_version >= kTraceVersionDualClock) {
618 uint16_t record_size = GetRecordSize(clock_source_);
619 Append2LE(buf_.get() + 16, record_size);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800620 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700621 static_assert(18 <= kMinBufSize, "Minimum buffer size not large enough for trace header");
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800622
jeffhao2692b572011-12-16 15:42:28 -0800623 // Update current offset.
Ian Rogers8ab25ef2014-07-09 18:00:50 -0700624 cur_offset_.StoreRelaxed(kTraceHeaderLength);
Andreas Gampe40da2862015-02-27 12:49:04 -0800625
626 if (output_mode == TraceOutputMode::kStreaming) {
627 streaming_file_name_ = trace_name;
628 streaming_lock_ = new Mutex("tracing lock");
629 seen_threads_.reset(new ThreadIDBitSet());
630 }
631}
632
633Trace::~Trace() {
634 delete streaming_lock_;
Ian Rogers62d6c772013-02-27 08:32:07 -0800635}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800636
Ian Rogerse63db272014-07-15 15:36:11 -0700637static void DumpBuf(uint8_t* buf, size_t buf_size, TraceClockSource clock_source)
Ian Rogers62d6c772013-02-27 08:32:07 -0800638 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
639 uint8_t* ptr = buf + kTraceHeaderLength;
640 uint8_t* end = buf + buf_size;
641
642 while (ptr < end) {
643 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700644 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800645 TraceAction action = DecodeTraceAction(tmid);
646 LOG(INFO) << PrettyMethod(method) << " " << static_cast<int>(action);
647 ptr += GetRecordSize(clock_source);
648 }
jeffhaoe343b762011-12-05 16:36:44 -0800649}
650
Andreas Gampe40da2862015-02-27 12:49:04 -0800651static void GetVisitedMethodsFromBitSets(
652 const std::map<mirror::DexCache*, DexIndexBitSet*>& seen_methods,
653 std::set<mirror::ArtMethod*>* visited_methods) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
654 for (auto& e : seen_methods) {
655 DexIndexBitSet* bit_set = e.second;
656 for (uint32_t i = 0; i < bit_set->size(); ++i) {
657 if ((*bit_set)[i]) {
658 visited_methods->insert(e.first->GetResolvedMethod(i));
659 }
660 }
661 }
662}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800663
Andreas Gampe40da2862015-02-27 12:49:04 -0800664void Trace::FinishTracing() {
665 size_t final_offset = 0;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800666
Brian Carlstromea46f952013-07-30 01:26:50 -0700667 std::set<mirror::ArtMethod*> visited_methods;
Andreas Gampe40da2862015-02-27 12:49:04 -0800668 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
669 // Write the secondary file with all the method names.
670 GetVisitedMethodsFromBitSets(seen_methods_, &visited_methods);
671
672 // Clean up.
673 for (auto& e : seen_methods_) {
674 delete e.second;
675 }
676 } else {
677 final_offset = cur_offset_.LoadRelaxed();
678 GetVisitedMethods(final_offset, &visited_methods);
679 }
680
681 // Compute elapsed time.
682 uint64_t elapsed = MicroTime() - start_time_;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800683
684 std::ostringstream os;
685
686 os << StringPrintf("%cversion\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800687 os << StringPrintf("%d\n", GetTraceVersion(clock_source_));
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800688 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
689 if (UseThreadCpuClock()) {
690 if (UseWallClock()) {
691 os << StringPrintf("clock=dual\n");
692 } else {
693 os << StringPrintf("clock=thread-cpu\n");
694 }
695 } else {
696 os << StringPrintf("clock=wall\n");
697 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800698 os << StringPrintf("elapsed-time-usec=%" PRIu64 "\n", elapsed);
Andreas Gampe40da2862015-02-27 12:49:04 -0800699 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
700 size_t num_records = (final_offset - kTraceHeaderLength) / GetRecordSize(clock_source_);
701 os << StringPrintf("num-method-calls=%zd\n", num_records);
702 }
Jeff Haoc5d824a2014-07-28 18:35:38 -0700703 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead_ns_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800704 os << StringPrintf("vm=art\n");
John Reck0624a272015-03-26 15:47:54 -0700705 os << StringPrintf("pid=%d\n", getpid());
jeffhao0791adc2012-04-04 11:14:32 -0700706 if ((flags_ & kTraceCountAllocs) != 0) {
707 os << StringPrintf("alloc-count=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_OBJECTS));
708 os << StringPrintf("alloc-size=%d\n", Runtime::Current()->GetStat(KIND_ALLOCATED_BYTES));
709 os << StringPrintf("gc-count=%d\n", Runtime::Current()->GetStat(KIND_GC_INVOCATIONS));
710 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800711 os << StringPrintf("%cthreads\n", kTraceTokenChar);
712 DumpThreadList(os);
713 os << StringPrintf("%cmethods\n", kTraceTokenChar);
Ian Rogers62d6c772013-02-27 08:32:07 -0800714 DumpMethodList(os, visited_methods);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800715 os << StringPrintf("%cend\n", kTraceTokenChar);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800716 std::string header(os.str());
Andreas Gampe40da2862015-02-27 12:49:04 -0800717
718 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
719 File file;
720 if (!file.Open(streaming_file_name_ + ".sec", O_CREAT | O_WRONLY)) {
721 LOG(WARNING) << "Could not open secondary trace file!";
722 return;
Ian Rogers62d6c772013-02-27 08:32:07 -0800723 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800724 if (!file.WriteFully(header.c_str(), header.length())) {
725 file.Erase();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700726 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
727 PLOG(ERROR) << detail;
Ian Rogers62d6c772013-02-27 08:32:07 -0800728 ThrowRuntimeException("%s", detail.c_str());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800729 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800730 if (file.FlushCloseOrErase() != 0) {
731 PLOG(ERROR) << "Could not write secondary file";
732 }
733 } else {
734 if (trace_file_.get() == nullptr) {
735 iovec iov[2];
736 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
737 iov[0].iov_len = header.length();
738 iov[1].iov_base = buf_.get();
739 iov[1].iov_len = final_offset;
740 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
741 const bool kDumpTraceInfo = false;
742 if (kDumpTraceInfo) {
743 LOG(INFO) << "Trace sent:\n" << header;
744 DumpBuf(buf_.get(), final_offset, clock_source_);
745 }
746 } else {
747 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
748 !trace_file_->WriteFully(buf_.get(), final_offset)) {
749 std::string detail(StringPrintf("Trace data write failed: %s", strerror(errno)));
750 PLOG(ERROR) << detail;
751 ThrowRuntimeException("%s", detail.c_str());
752 }
753 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800754 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800755}
756
Ian Rogers62d6c772013-02-27 08:32:07 -0800757void Trace::DexPcMoved(Thread* thread, mirror::Object* this_object,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800758 mirror::ArtMethod* method, uint32_t new_dex_pc) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700759 UNUSED(thread, this_object, method, new_dex_pc);
Ian Rogers62d6c772013-02-27 08:32:07 -0800760 // We're not recorded to listen to this kind of event, so complain.
761 LOG(ERROR) << "Unexpected dex PC event in tracing " << PrettyMethod(method) << " " << new_dex_pc;
Andreas Gampec8ccf682014-09-29 20:07:43 -0700762}
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800763
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700764void Trace::FieldRead(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700765 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field)
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200766 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700767 UNUSED(thread, this_object, method, dex_pc, field);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200768 // We're not recorded to listen to this kind of event, so complain.
769 LOG(ERROR) << "Unexpected field read event in tracing " << PrettyMethod(method) << " " << dex_pc;
770}
771
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700772void Trace::FieldWritten(Thread* thread, mirror::Object* this_object,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700773 mirror::ArtMethod* method, uint32_t dex_pc, ArtField* field,
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200774 const JValue& field_value)
775 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700776 UNUSED(thread, this_object, method, dex_pc, field, field_value);
Sebastien Hertz3f52eaf2014-04-04 17:50:18 +0200777 // We're not recorded to listen to this kind of event, so complain.
778 LOG(ERROR) << "Unexpected field write event in tracing " << PrettyMethod(method) << " " << dex_pc;
779}
780
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700781void Trace::MethodEntered(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
782 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700783 uint32_t thread_clock_diff = 0;
784 uint32_t wall_clock_diff = 0;
785 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
786 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodEntered,
787 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800788}
789
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700790void Trace::MethodExited(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
791 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED,
792 const JValue& return_value ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700793 uint32_t thread_clock_diff = 0;
794 uint32_t wall_clock_diff = 0;
795 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
796 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodExited,
797 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800798}
799
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700800void Trace::MethodUnwind(Thread* thread, mirror::Object* this_object ATTRIBUTE_UNUSED,
801 mirror::ArtMethod* method, uint32_t dex_pc ATTRIBUTE_UNUSED) {
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700802 uint32_t thread_clock_diff = 0;
803 uint32_t wall_clock_diff = 0;
804 ReadClocks(thread, &thread_clock_diff, &wall_clock_diff);
805 LogMethodTraceEvent(thread, method, instrumentation::Instrumentation::kMethodUnwind,
806 thread_clock_diff, wall_clock_diff);
Ian Rogers62d6c772013-02-27 08:32:07 -0800807}
808
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000809void Trace::ExceptionCaught(Thread* thread, mirror::Throwable* exception_object)
Ian Rogers62d6c772013-02-27 08:32:07 -0800810 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000811 UNUSED(thread, exception_object);
Ian Rogers62d6c772013-02-27 08:32:07 -0800812 LOG(ERROR) << "Unexpected exception caught event in tracing";
813}
814
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800815void Trace::BackwardBranch(Thread* /*thread*/, mirror::ArtMethod* method,
816 int32_t /*dex_pc_offset*/)
817 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
818 LOG(ERROR) << "Unexpected backward branch event in tracing" << PrettyMethod(method);
819}
820
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700821void Trace::ReadClocks(Thread* thread, uint32_t* thread_clock_diff, uint32_t* wall_clock_diff) {
822 if (UseThreadCpuClock()) {
823 uint64_t clock_base = thread->GetTraceClockBase();
824 if (UNLIKELY(clock_base == 0)) {
825 // First event, record the base time in the map.
826 uint64_t time = thread->GetCpuMicroTime();
827 thread->SetTraceClockBase(time);
828 } else {
829 *thread_clock_diff = thread->GetCpuMicroTime() - clock_base;
830 }
831 }
832 if (UseWallClock()) {
833 *wall_clock_diff = MicroTime() - start_time_;
834 }
835}
836
Andreas Gampe40da2862015-02-27 12:49:04 -0800837bool Trace::RegisterMethod(mirror::ArtMethod* method) {
838 mirror::DexCache* dex_cache = method->GetDexCache();
839 if (dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) != method) {
840 DCHECK(dex_cache->GetResolvedMethod(method->GetDexMethodIndex()) == nullptr);
841 dex_cache->SetResolvedMethod(method->GetDexMethodIndex(), method);
842 }
843 if (seen_methods_.find(dex_cache) == seen_methods_.end()) {
844 seen_methods_.insert(std::make_pair(dex_cache, new DexIndexBitSet()));
845 }
846 DexIndexBitSet* bit_set = seen_methods_.find(dex_cache)->second;
847 if (!(*bit_set)[method->GetDexMethodIndex()]) {
848 bit_set->set(method->GetDexMethodIndex());
849 return true;
850 }
851 return false;
852}
853
854bool Trace::RegisterThread(Thread* thread) {
855 pid_t tid = thread->GetTid();
856 CHECK_LT(0U, static_cast<uint32_t>(tid));
857 CHECK_LT(static_cast<uint32_t>(tid), 65536U);
858
859 if (!(*seen_threads_)[tid]) {
860 seen_threads_->set(tid);
861 return true;
862 }
863 return false;
864}
865
866static std::string GetMethodLine(mirror::ArtMethod* method)
867 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
868 return StringPrintf("%p\t%s\t%s\t%s\t%s\n", method,
869 PrettyDescriptor(method->GetDeclaringClassDescriptor()).c_str(), method->GetName(),
870 method->GetSignature().ToString().c_str(), method->GetDeclaringClassSourceFile());
871}
872
873void Trace::WriteToBuf(const uint8_t* src, size_t src_size) {
874 int32_t old_offset = cur_offset_.LoadRelaxed();
875 int32_t new_offset = old_offset + static_cast<int32_t>(src_size);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700876 if (dchecked_integral_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800877 // Flush buffer.
878 if (!trace_file_->WriteFully(buf_.get(), old_offset)) {
879 PLOG(WARNING) << "Failed streaming a tracing event.";
880 }
Andreas Gampee34a42c2015-04-25 14:44:29 -0700881
882 // Check whether the data is too large for the buffer, then write immediately.
883 if (src_size >= buffer_size_) {
884 if (!trace_file_->WriteFully(src, src_size)) {
885 PLOG(WARNING) << "Failed streaming a tracing event.";
886 }
887 cur_offset_.StoreRelease(0); // Buffer is empty now.
888 return;
889 }
890
Andreas Gampe40da2862015-02-27 12:49:04 -0800891 old_offset = 0;
892 new_offset = static_cast<int32_t>(src_size);
893 }
894 cur_offset_.StoreRelease(new_offset);
895 // Fill in data.
896 memcpy(buf_.get() + old_offset, src, src_size);
897}
898
Ian Rogersef7d42f2014-01-06 12:55:46 -0800899void Trace::LogMethodTraceEvent(Thread* thread, mirror::ArtMethod* method,
Jeff Haoc1ff4b72013-08-19 11:33:10 -0700900 instrumentation::Instrumentation::InstrumentationEvent event,
901 uint32_t thread_clock_diff, uint32_t wall_clock_diff) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800902 // Advance cur_offset_ atomically.
903 int32_t new_offset;
Andreas Gampe40da2862015-02-27 12:49:04 -0800904 int32_t old_offset = 0;
905
906 // We do a busy loop here trying to acquire the next offset.
907 if (trace_output_mode_ != TraceOutputMode::kStreaming) {
908 do {
909 old_offset = cur_offset_.LoadRelaxed();
910 new_offset = old_offset + GetRecordSize(clock_source_);
Andreas Gampee34a42c2015-04-25 14:44:29 -0700911 if (static_cast<size_t>(new_offset) > buffer_size_) {
Andreas Gampe40da2862015-02-27 12:49:04 -0800912 overflow_ = true;
913 return;
914 }
915 } while (!cur_offset_.CompareExchangeWeakSequentiallyConsistent(old_offset, new_offset));
916 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800917
Ian Rogers62d6c772013-02-27 08:32:07 -0800918 TraceAction action = kTraceMethodEnter;
919 switch (event) {
920 case instrumentation::Instrumentation::kMethodEntered:
921 action = kTraceMethodEnter;
922 break;
923 case instrumentation::Instrumentation::kMethodExited:
924 action = kTraceMethodExit;
925 break;
926 case instrumentation::Instrumentation::kMethodUnwind:
927 action = kTraceUnroll;
928 break;
929 default:
930 UNIMPLEMENTED(FATAL) << "Unexpected event: " << event;
931 }
932
933 uint32_t method_value = EncodeTraceMethodAndAction(method, action);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800934
935 // Write data
Andreas Gampe40da2862015-02-27 12:49:04 -0800936 uint8_t* ptr;
937 static constexpr size_t kPacketSize = 14U; // The maximum size of data in a packet.
938 uint8_t stack_buf[kPacketSize]; // Space to store a packet when in streaming mode.
939 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
940 ptr = stack_buf;
941 } else {
942 ptr = buf_.get() + old_offset;
943 }
944
Ian Rogers62d6c772013-02-27 08:32:07 -0800945 Append2LE(ptr, thread->GetTid());
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800946 Append4LE(ptr + 2, method_value);
947 ptr += 6;
948
949 if (UseThreadCpuClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800950 Append4LE(ptr, thread_clock_diff);
951 ptr += 4;
952 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800953 if (UseWallClock()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800954 Append4LE(ptr, wall_clock_diff);
955 }
Andreas Gampe40da2862015-02-27 12:49:04 -0800956 static_assert(kPacketSize == 2 + 4 + 4 + 4, "Packet size incorrect.");
957
958 if (trace_output_mode_ == TraceOutputMode::kStreaming) {
959 MutexLock mu(Thread::Current(), *streaming_lock_); // To serialize writing.
960 if (RegisterMethod(method)) {
961 // Write a special block with the name.
962 std::string method_line(GetMethodLine(method));
963 uint8_t buf2[5];
964 Append2LE(buf2, 0);
965 buf2[2] = kOpNewMethod;
966 Append2LE(buf2 + 3, static_cast<uint16_t>(method_line.length()));
967 WriteToBuf(buf2, sizeof(buf2));
968 WriteToBuf(reinterpret_cast<const uint8_t*>(method_line.c_str()), method_line.length());
969 }
970 if (RegisterThread(thread)) {
971 // It might be better to postpone this. Threads might not have received names...
972 std::string thread_name;
973 thread->GetThreadName(thread_name);
974 uint8_t buf2[7];
975 Append2LE(buf2, 0);
976 buf2[2] = kOpNewThread;
977 Append2LE(buf2 + 3, static_cast<uint16_t>(thread->GetTid()));
978 Append2LE(buf2 + 5, static_cast<uint16_t>(thread_name.length()));
979 WriteToBuf(buf2, sizeof(buf2));
980 WriteToBuf(reinterpret_cast<const uint8_t*>(thread_name.c_str()), thread_name.length());
981 }
982 WriteToBuf(stack_buf, sizeof(stack_buf));
983 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800984}
985
Ian Rogers62d6c772013-02-27 08:32:07 -0800986void Trace::GetVisitedMethods(size_t buf_size,
Brian Carlstromea46f952013-07-30 01:26:50 -0700987 std::set<mirror::ArtMethod*>* visited_methods) {
jeffhao2692b572011-12-16 15:42:28 -0800988 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
Ian Rogers62d6c772013-02-27 08:32:07 -0800989 uint8_t* end = buf_.get() + buf_size;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800990
991 while (ptr < end) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800992 uint32_t tmid = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
Brian Carlstromea46f952013-07-30 01:26:50 -0700993 mirror::ArtMethod* method = DecodeTraceMethodId(tmid);
Ian Rogers62d6c772013-02-27 08:32:07 -0800994 visited_methods->insert(method);
995 ptr += GetRecordSize(clock_source_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800996 }
997}
998
Mathieu Chartier02e25112013-08-14 16:14:24 -0700999void Trace::DumpMethodList(std::ostream& os, const std::set<mirror::ArtMethod*>& visited_methods) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001000 for (const auto& method : visited_methods) {
Andreas Gampe40da2862015-02-27 12:49:04 -08001001 os << GetMethodLine(method);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001002 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001003}
1004
1005static void DumpThread(Thread* t, void* arg) {
Elliott Hughesffb465f2012-03-01 18:46:05 -08001006 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
1007 std::string name;
1008 t->GetThreadName(name);
1009 os << t->GetTid() << "\t" << name << "\n";
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001010}
1011
1012void Trace::DumpThreadList(std::ostream& os) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001013 Thread* self = Thread::Current();
Jeff Haoe094b872014-10-14 13:12:01 -07001014 for (auto it : exited_threads_) {
1015 os << it.first << "\t" << it.second << "\n";
1016 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001017 Locks::thread_list_lock_->AssertNotHeld(self);
1018 MutexLock mu(self, *Locks::thread_list_lock_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001019 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -08001020}
1021
Jeff Haoe094b872014-10-14 13:12:01 -07001022void Trace::StoreExitingThreadInfo(Thread* thread) {
1023 MutexLock mu(thread, *Locks::trace_lock_);
1024 if (the_trace_ != nullptr) {
1025 std::string name;
1026 thread->GetThreadName(name);
Andreas Gampea1785c52014-11-25 20:40:08 -08001027 // The same thread/tid may be used multiple times. As SafeMap::Put does not allow to override
1028 // a previous mapping, use SafeMap::Overwrite.
1029 the_trace_->exited_threads_.Overwrite(thread->GetTid(), name);
Jeff Haoe094b872014-10-14 13:12:01 -07001030 }
1031}
1032
Andreas Gampe40da2862015-02-27 12:49:04 -08001033Trace::TraceOutputMode Trace::GetOutputMode() {
1034 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1035 CHECK(the_trace_ != nullptr) << "Trace output mode requested, but no trace currently running";
1036 return the_trace_->trace_output_mode_;
1037}
1038
1039Trace::TraceMode Trace::GetMode() {
1040 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1041 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1042 return the_trace_->trace_mode_;
1043}
1044
Andreas Gampee34a42c2015-04-25 14:44:29 -07001045size_t Trace::GetBufferSize() {
1046 MutexLock mu(Thread::Current(), *Locks::trace_lock_);
1047 CHECK(the_trace_ != nullptr) << "Trace mode requested, but no trace currently running";
1048 return the_trace_->buffer_size_;
1049}
1050
jeffhaoe343b762011-12-05 16:36:44 -08001051} // namespace art