blob: b481b744fa8a698d7763b05acdb1709d881bd204 [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>
20
jeffhaoe343b762011-12-05 16:36:44 -080021#include "class_linker.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080022#include "debugger.h"
jeffhaoe343b762011-12-05 16:36:44 -080023#include "dex_cache.h"
jeffhaoa9ef3fd2011-12-13 18:33:43 -080024#include "object_utils.h"
25#include "os.h"
jeffhaoe343b762011-12-05 16:36:44 -080026#include "runtime_support.h"
27#include "thread.h"
28
jeffhao2692b572011-12-16 15:42:28 -080029
30namespace art {
31
jeffhaoa9ef3fd2011-12-13 18:33:43 -080032static const uint32_t kTraceMethodActionMask = 0x03; // two bits
33static const char kTraceTokenChar = '*';
34static const uint16_t kTraceHeaderLength = 32;
35static const uint32_t kTraceMagicValue = 0x574f4c53;
36static const uint16_t kTraceVersionSingleClock = 2;
37static const uint16_t kTraceVersionDualClock = 3;
38static const uint16_t kTraceRecordSizeSingleClock = 10; // using v2
39static const uint16_t kTraceRecordSizeDualClock = 14; // using v3 with two timestamps
40
41static inline uint32_t TraceMethodId(uint32_t methodValue) {
42 return (methodValue & ~kTraceMethodActionMask);
43}
44static inline uint32_t TraceMethodCombine(uint32_t method, uint8_t traceEvent) {
45 return (method | traceEvent);
46}
47
Elliott Hughesffb465f2012-03-01 18:46:05 -080048static bool UseThreadCpuClock() {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080049 // TODO: Allow control over which clock is used
50 return true;
51}
52
Elliott Hughesffb465f2012-03-01 18:46:05 -080053static bool UseWallClock() {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080054 // TODO: Allow control over which clock is used
55 return true;
56}
57
Elliott Hughesffb465f2012-03-01 18:46:05 -080058static void MeasureClockOverhead() {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080059 if (UseThreadCpuClock()) {
60 ThreadCpuMicroTime();
61 }
62 if (UseWallClock()) {
63 MicroTime();
64 }
65}
66
Elliott Hughesffb465f2012-03-01 18:46:05 -080067static uint32_t GetClockOverhead() {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080068 uint64_t start = ThreadCpuMicroTime();
69
70 for (int i = 4000; i > 0; i--) {
71 MeasureClockOverhead();
72 MeasureClockOverhead();
73 MeasureClockOverhead();
74 MeasureClockOverhead();
75 MeasureClockOverhead();
76 MeasureClockOverhead();
77 MeasureClockOverhead();
78 MeasureClockOverhead();
79 }
80
81 uint64_t elapsed = ThreadCpuMicroTime() - start;
82 return uint32_t (elapsed / 32);
83}
84
Elliott Hughesffb465f2012-03-01 18:46:05 -080085// TODO: put this somewhere with the big-endian equivalent used by JDWP.
86static void Append2LE(uint8_t* buf, uint16_t val) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080087 *buf++ = (uint8_t) val;
88 *buf++ = (uint8_t) (val >> 8);
89}
90
Elliott Hughesffb465f2012-03-01 18:46:05 -080091// TODO: put this somewhere with the big-endian equivalent used by JDWP.
92static void Append4LE(uint8_t* buf, uint32_t val) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -080093 *buf++ = (uint8_t) val;
94 *buf++ = (uint8_t) (val >> 8);
95 *buf++ = (uint8_t) (val >> 16);
96 *buf++ = (uint8_t) (val >> 24);
97}
98
Elliott Hughesffb465f2012-03-01 18:46:05 -080099// TODO: put this somewhere with the big-endian equivalent used by JDWP.
100static void Append8LE(uint8_t* buf, uint64_t val) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800101 *buf++ = (uint8_t) val;
102 *buf++ = (uint8_t) (val >> 8);
103 *buf++ = (uint8_t) (val >> 16);
104 *buf++ = (uint8_t) (val >> 24);
105 *buf++ = (uint8_t) (val >> 32);
106 *buf++ = (uint8_t) (val >> 40);
107 *buf++ = (uint8_t) (val >> 48);
108 *buf++ = (uint8_t) (val >> 56);
109}
110
jeffhaoe343b762011-12-05 16:36:44 -0800111#if defined(__arm__)
112static bool InstallStubsClassVisitor(Class* klass, void* trace_stub) {
jeffhao2692b572011-12-16 15:42:28 -0800113 Trace* tracer = Runtime::Current()->GetTracer();
jeffhaoe343b762011-12-05 16:36:44 -0800114 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
115 Method* method = klass->GetDirectMethod(i);
116 if (method->GetCode() != trace_stub) {
jeffhao2692b572011-12-16 15:42:28 -0800117 tracer->SaveAndUpdateCode(method, trace_stub);
jeffhaoe343b762011-12-05 16:36:44 -0800118 }
119 }
120
121 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
122 Method* method = klass->GetVirtualMethod(i);
123 if (method->GetCode() != trace_stub) {
jeffhao2692b572011-12-16 15:42:28 -0800124 tracer->SaveAndUpdateCode(method, trace_stub);
jeffhaoe343b762011-12-05 16:36:44 -0800125 }
126 }
jeffhaoe343b762011-12-05 16:36:44 -0800127 return true;
128}
129
130static bool UninstallStubsClassVisitor(Class* klass, void* trace_stub) {
jeffhao2692b572011-12-16 15:42:28 -0800131 Trace* tracer = Runtime::Current()->GetTracer();
jeffhaoe343b762011-12-05 16:36:44 -0800132 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
133 Method* method = klass->GetDirectMethod(i);
jeffhao2692b572011-12-16 15:42:28 -0800134 if (tracer->GetSavedCodeFromMap(method) != NULL) {
135 tracer->ResetSavedCode(method);
jeffhaoe343b762011-12-05 16:36:44 -0800136 }
137 }
138
139 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
140 Method* method = klass->GetVirtualMethod(i);
jeffhao2692b572011-12-16 15:42:28 -0800141 if (tracer->GetSavedCodeFromMap(method) != NULL) {
142 tracer->ResetSavedCode(method);
jeffhaoe343b762011-12-05 16:36:44 -0800143 }
144 }
jeffhaoe343b762011-12-05 16:36:44 -0800145 return true;
146}
147
148static void TraceRestoreStack(Thread* t, void*) {
149 uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
150
151 Frame frame = t->GetTopOfStack();
152 if (frame.GetSP() != 0) {
153 for ( ; frame.GetMethod() != 0; frame.Next()) {
154 if (t->IsTraceStackEmpty()) {
155 break;
156 }
157 uintptr_t pc = frame.GetReturnPC();
158 Method* method = frame.GetMethod();
159 if (trace_exit == pc) {
160 TraceStackFrame trace_frame = t->PopTraceStackFrame();
161 frame.SetReturnPC(trace_frame.return_pc_);
162 CHECK(method == trace_frame.method_);
163 }
164 }
165 }
166}
167#endif
168
jeffhaoe343b762011-12-05 16:36:44 -0800169void Trace::AddSavedCodeToMap(const Method* method, const void* code) {
170 saved_code_map_.insert(std::make_pair(method, code));
171}
172
173void Trace::RemoveSavedCodeFromMap(const Method* method) {
174 saved_code_map_.erase(method);
175}
176
177const void* Trace::GetSavedCodeFromMap(const Method* method) {
jeffhao2692b572011-12-16 15:42:28 -0800178 typedef std::map<const Method*, const void*>::const_iterator It; // TODO: C++0x auto
179 It it = saved_code_map_.find(method);
180 if (it == saved_code_map_.end()) {
181 return NULL;
182 } else {
183 return it->second;
184 }
jeffhaoe343b762011-12-05 16:36:44 -0800185}
186
187void Trace::SaveAndUpdateCode(Method* method, const void* new_code) {
188 CHECK(GetSavedCodeFromMap(method) == NULL);
189 AddSavedCodeToMap(method, method->GetCode());
190 method->SetCode(new_code);
191}
192
193void Trace::ResetSavedCode(Method* method) {
194 CHECK(GetSavedCodeFromMap(method) != NULL);
195 method->SetCode(GetSavedCodeFromMap(method));
196 RemoveSavedCodeFromMap(method);
197}
198
jeffhaoe343b762011-12-05 16:36:44 -0800199void Trace::Start(const char* trace_filename, int trace_fd, int buffer_size, int flags, bool direct_to_ddms) {
jeffhao2692b572011-12-16 15:42:28 -0800200 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800201 LOG(INFO) << "Trace already in progress, ignoring this request";
jeffhaoe343b762011-12-05 16:36:44 -0800202 return;
203 }
204
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800205 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
206 Runtime::Current()->GetThreadList()->SuspendAll(false);
207
jeffhao2692b572011-12-16 15:42:28 -0800208 // Open trace file if not going directly to ddms.
209 File* trace_file = NULL;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800210 if (!direct_to_ddms) {
211 if (trace_fd < 0) {
jeffhao2692b572011-12-16 15:42:28 -0800212 trace_file = OS::OpenFile(trace_filename, true);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800213 } else {
jeffhao2692b572011-12-16 15:42:28 -0800214 trace_file = OS::FileFromFd("tracefile", trace_fd);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800215 }
jeffhao2692b572011-12-16 15:42:28 -0800216 if (trace_file == NULL) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800217 PLOG(ERROR) << "Unable to open trace file '" << trace_filename;
218 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
219 StringPrintf("Unable to open trace file '%s'", trace_filename).c_str());
220 Runtime::Current()->GetThreadList()->ResumeAll(false);
221 return;
222 }
223 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800224
jeffhao2692b572011-12-16 15:42:28 -0800225 // Create Trace object.
226 Trace* tracer(new Trace(trace_file, buffer_size));
227 Runtime::Current()->EnableMethodTracing(tracer);
228 tracer->BeginTracing();
229
230 Runtime::Current()->GetThreadList()->ResumeAll(false);
231}
232
233void Trace::Stop() {
234 if (!Runtime::Current()->IsMethodTracingActive()) {
235 LOG(INFO) << "Trace stop requested, but no trace currently running";
236 return;
237 }
238
239 ScopedThreadStateChange tsc(Thread::Current(), Thread::kRunnable);
240 Runtime::Current()->GetThreadList()->SuspendAll(false);
241
242 Runtime::Current()->GetTracer()->FinishTracing();
243 Runtime::Current()->DisableMethodTracing();
244
245 Runtime::Current()->GetThreadList()->ResumeAll(false);
246}
247
248void Trace::BeginTracing() {
249 // Set the start time of tracing.
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800250 start_time_ = MicroTime();
251
jeffhao2692b572011-12-16 15:42:28 -0800252 // Set trace version and record size.
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800253 if (UseThreadCpuClock() && UseWallClock()) {
254 trace_version_ = kTraceVersionDualClock;
255 record_size_ = kTraceRecordSizeDualClock;
256 } else {
257 trace_version_ = kTraceVersionSingleClock;
258 record_size_ = kTraceRecordSizeSingleClock;
259 }
260
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800261 // Set up the beginning of the trace.
jeffhao2692b572011-12-16 15:42:28 -0800262 memset(buf_.get(), 0, kTraceHeaderLength);
263 Append4LE(buf_.get(), kTraceMagicValue);
264 Append2LE(buf_.get() + 4, trace_version_);
265 Append2LE(buf_.get() + 6, kTraceHeaderLength);
266 Append8LE(buf_.get() + 8, start_time_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800267 if (trace_version_ >= kTraceVersionDualClock) {
jeffhao2692b572011-12-16 15:42:28 -0800268 Append2LE(buf_.get() + 16, record_size_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800269 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800270
jeffhao2692b572011-12-16 15:42:28 -0800271 // Update current offset.
272 cur_offset_ = kTraceHeaderLength;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800273
274 // Install all method tracing stubs.
jeffhaoe343b762011-12-05 16:36:44 -0800275 InstallStubs();
jeffhaoe343b762011-12-05 16:36:44 -0800276}
277
jeffhao2692b572011-12-16 15:42:28 -0800278void Trace::FinishTracing() {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800279 // Uninstall all method tracing stubs.
jeffhaoe343b762011-12-05 16:36:44 -0800280 UninstallStubs();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800281
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800282 // Compute elapsed time.
283 uint64_t elapsed = MicroTime() - start_time_;
284
285 size_t final_offset = cur_offset_;
286 uint32_t clock_overhead = GetClockOverhead();
287
288 GetVisitedMethods(final_offset);
289
290 std::ostringstream os;
291
292 os << StringPrintf("%cversion\n", kTraceTokenChar);
293 os << StringPrintf("%d\n", trace_version_);
294 os << StringPrintf("data-file-overflow=%s\n", overflow_ ? "true" : "false");
295 if (UseThreadCpuClock()) {
296 if (UseWallClock()) {
297 os << StringPrintf("clock=dual\n");
298 } else {
299 os << StringPrintf("clock=thread-cpu\n");
300 }
301 } else {
302 os << StringPrintf("clock=wall\n");
303 }
304 os << StringPrintf("elapsed-time-usec=%llu\n", elapsed);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800305 os << StringPrintf("num-method-calls=%zd\n", (final_offset - kTraceHeaderLength) / record_size_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800306 os << StringPrintf("clock-call-overhead-nsec=%d\n", clock_overhead);
307 os << StringPrintf("vm=art\n");
308 os << StringPrintf("%cthreads\n", kTraceTokenChar);
309 DumpThreadList(os);
310 os << StringPrintf("%cmethods\n", kTraceTokenChar);
311 DumpMethodList(os);
312 os << StringPrintf("%cend\n", kTraceTokenChar);
313
314 std::string header(os.str());
jeffhao2692b572011-12-16 15:42:28 -0800315 if (trace_file_.get() == NULL) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800316 struct iovec iov[2];
317 iov[0].iov_base = reinterpret_cast<void*>(const_cast<char*>(header.c_str()));
318 iov[0].iov_len = header.length();
jeffhao2692b572011-12-16 15:42:28 -0800319 iov[1].iov_base = buf_.get();
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800320 iov[1].iov_len = final_offset;
321 Dbg::DdmSendChunkV(CHUNK_TYPE("MPSE"), iov, 2);
322 } else {
323 if (!trace_file_->WriteFully(header.c_str(), header.length()) ||
jeffhao2692b572011-12-16 15:42:28 -0800324 !trace_file_->WriteFully(buf_.get(), final_offset)) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800325 int err = errno;
326 LOG(ERROR) << "Trace data write failed: " << strerror(err);
327 Thread::Current()->ThrowNewException("Ljava/lang/RuntimeException;",
328 StringPrintf("Trace data write failed: %s", strerror(err)).c_str());
329 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800330 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800331}
332
333void Trace::LogMethodTraceEvent(Thread* self, const Method* method, Trace::TraceEvent event) {
334 if (thread_clock_base_map_.find(self) == thread_clock_base_map_.end()) {
335 uint64_t time = ThreadCpuMicroTime();
336 thread_clock_base_map_.insert(std::make_pair(self, time));
337 }
338
339 // Advance cur_offset_ atomically.
340 int32_t new_offset;
341 int32_t old_offset;
342 do {
343 old_offset = cur_offset_;
344 new_offset = old_offset + record_size_;
345 if (new_offset > buffer_size_) {
346 overflow_ = true;
347 return;
348 }
349 } while (android_atomic_release_cas(old_offset, new_offset, &cur_offset_) != 0);
350
351 uint32_t method_value = TraceMethodCombine(reinterpret_cast<uint32_t>(method), event);
352
353 // Write data
jeffhao2692b572011-12-16 15:42:28 -0800354 uint8_t* ptr = buf_.get() + old_offset;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800355 Append2LE(ptr, self->GetTid());
356 Append4LE(ptr + 2, method_value);
357 ptr += 6;
358
359 if (UseThreadCpuClock()) {
360 uint64_t thread_clock_base = thread_clock_base_map_.find(self)->second;
361 uint32_t thread_clock_diff = ThreadCpuMicroTime() - thread_clock_base;
362 Append4LE(ptr, thread_clock_diff);
363 ptr += 4;
364 }
365
366 if (UseWallClock()) {
367 uint32_t wall_clock_diff = MicroTime() - start_time_;
368 Append4LE(ptr, wall_clock_diff);
369 }
370}
371
372void Trace::GetVisitedMethods(size_t end_offset) {
jeffhao2692b572011-12-16 15:42:28 -0800373 uint8_t* ptr = buf_.get() + kTraceHeaderLength;
374 uint8_t* end = buf_.get() + end_offset;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800375
376 while (ptr < end) {
377 uint32_t method_value = ptr[2] | (ptr[3] << 8) | (ptr[4] << 16) | (ptr[5] << 24);
378 Method* method = reinterpret_cast<Method*>(TraceMethodId(method_value));
379 visited_methods_.insert(method);
380 ptr += record_size_;
381 }
382}
383
384void Trace::DumpMethodList(std::ostream& os) {
385 typedef std::set<const Method*>::const_iterator It; // TODO: C++0x auto
386 for (It it = visited_methods_.begin(); it != visited_methods_.end(); ++it) {
387 const Method* method = *it;
388 MethodHelper mh(method);
Elliott Hughesba8eee12012-01-24 20:25:24 -0800389 os << StringPrintf("%p\t%s\t%s\t%s\t%s\t%d\n", method,
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800390 PrettyDescriptor(mh.GetDeclaringClassDescriptor()).c_str(), mh.GetName(),
391 mh.GetSignature().c_str(), mh.GetDeclaringClassSourceFile(),
392 mh.GetLineNumFromNativePC(0));
393 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800394}
395
396static void DumpThread(Thread* t, void* arg) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800397 std::ostream& os = *reinterpret_cast<std::ostream*>(arg);
398 std::string name;
399 t->GetThreadName(name);
400 os << t->GetTid() << "\t" << name << "\n";
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800401}
402
403void Trace::DumpThreadList(std::ostream& os) {
404 ScopedThreadListLock thread_list_lock;
405 Runtime::Current()->GetThreadList()->ForEach(DumpThread, &os);
jeffhaoe343b762011-12-05 16:36:44 -0800406}
407
408void Trace::InstallStubs() {
409#if defined(__arm__)
jeffhaoe343b762011-12-05 16:36:44 -0800410 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
411 Runtime::Current()->GetClassLinker()->VisitClasses(InstallStubsClassVisitor, trace_stub);
jeffhaoe343b762011-12-05 16:36:44 -0800412#else
413 UNIMPLEMENTED(WARNING);
414#endif
415}
416
417void Trace::UninstallStubs() {
418#if defined(__arm__)
jeffhaoe343b762011-12-05 16:36:44 -0800419 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
420 Runtime::Current()->GetClassLinker()->VisitClasses(UninstallStubsClassVisitor, trace_stub);
421
422 // Restore stacks of all threads
423 {
424 ScopedThreadListLock thread_list_lock;
425 Runtime::Current()->GetThreadList()->ForEach(TraceRestoreStack, NULL);
426 }
jeffhaoe343b762011-12-05 16:36:44 -0800427#else
428 UNIMPLEMENTED(WARNING);
429#endif
430}
431
432} // namespace art