blob: 951444812b96bf3034f984e6741f51a53c4fd3f8 [file] [log] [blame]
Dave Allison0aded082013-11-07 13:15:11 -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 */
16
17#include "profiler.h"
18
Calin Juravle9dae5b42014-04-07 16:36:21 +030019#include <fstream>
Dave Allison0aded082013-11-07 13:15:11 -080020#include <sys/uio.h>
Dave Allison39c3bfb2014-01-28 18:33:52 -080021#include <sys/file.h>
Dave Allison0aded082013-11-07 13:15:11 -080022
23#include "base/stl_util.h"
24#include "base/unix_file/fd_file.h"
25#include "class_linker.h"
26#include "common_throws.h"
27#include "debugger.h"
28#include "dex_file-inl.h"
29#include "instrumentation.h"
30#include "mirror/art_method-inl.h"
31#include "mirror/class-inl.h"
32#include "mirror/dex_cache.h"
33#include "mirror/object_array-inl.h"
34#include "mirror/object-inl.h"
Dave Allison0aded082013-11-07 13:15:11 -080035#include "os.h"
36#include "scoped_thread_state_change.h"
37#include "ScopedLocalRef.h"
38#include "thread.h"
39#include "thread_list.h"
Dave Allison4a7867b2014-01-30 17:44:12 -080040
41#ifdef HAVE_ANDROID_OS
42#include "cutils/properties.h"
43#endif
44
Dave Allison0aded082013-11-07 13:15:11 -080045#if !defined(ART_USE_PORTABLE_COMPILER)
46#include "entrypoints/quick/quick_entrypoints.h"
47#endif
48
49namespace art {
50
51BackgroundMethodSamplingProfiler* BackgroundMethodSamplingProfiler::profiler_ = nullptr;
52pthread_t BackgroundMethodSamplingProfiler::profiler_pthread_ = 0U;
53volatile bool BackgroundMethodSamplingProfiler::shutting_down_ = false;
54
Dave Allison0aded082013-11-07 13:15:11 -080055// TODO: this profiler runs regardless of the state of the machine. Maybe we should use the
56// wakelock or something to modify the run characteristics. This can be done when we
57// have some performance data after it's been used for a while.
58
Wei Jin445220d2014-06-20 15:56:53 -070059// Walk through the method within depth of max_depth_ on the Java stack
60class BoundedStackVisitor : public StackVisitor {
61 public:
62 BoundedStackVisitor(std::vector<std::pair<mirror::ArtMethod*, uint32_t>>* stack,
63 Thread* thread, uint32_t max_depth)
64 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
65 : StackVisitor(thread, NULL), stack_(stack), max_depth_(max_depth), depth_(0) {
66 }
67
68 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
69 mirror::ArtMethod* m = GetMethod();
70 if (m->IsRuntimeMethod()) {
71 return true;
72 }
73 uint32_t dex_pc_ = GetDexPc();
74 stack_->push_back(std::make_pair(m, dex_pc_));
75 ++depth_;
76 if (depth_ < max_depth_) {
77 return true;
78 } else {
79 return false;
80 }
81 }
82
83 private:
84 std::vector<std::pair<mirror::ArtMethod*, uint32_t>>* stack_;
85 const uint32_t max_depth_;
86 uint32_t depth_;
87};
Dave Allison0aded082013-11-07 13:15:11 -080088
89// This is called from either a thread list traversal or from a checkpoint. Regardless
90// of which caller, the mutator lock must be held.
91static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
92 BackgroundMethodSamplingProfiler* profiler =
93 reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
Wei Jin445220d2014-06-20 15:56:53 -070094 const ProfilerOptions profile_options = profiler->GetProfilerOptions();
95 switch (profile_options.GetProfileType()) {
96 case kProfilerMethod: {
97 mirror::ArtMethod* method = thread->GetCurrentMethod(nullptr);
98 if (false && method == nullptr) {
99 LOG(INFO) << "No current method available";
100 std::ostringstream os;
101 thread->Dump(os);
102 std::string data(os.str());
103 LOG(INFO) << data;
104 }
105 profiler->RecordMethod(method);
106 break;
107 }
108 case kProfilerBoundedStack: {
109 std::vector<InstructionLocation> stack;
110 uint32_t max_depth = profile_options.GetMaxStackDepth();
111 BoundedStackVisitor bounded_stack_visitor(&stack, thread, max_depth);
112 bounded_stack_visitor.WalkStack();
113 profiler->RecordStack(stack);
114 break;
115 }
116 default:
117 LOG(INFO) << "This profile type is not implemented.";
Dave Allison0aded082013-11-07 13:15:11 -0800118 }
Dave Allison0aded082013-11-07 13:15:11 -0800119}
120
Dave Allison0aded082013-11-07 13:15:11 -0800121// A closure that is called by the thread checkpoint code.
122class SampleCheckpoint : public Closure {
123 public:
124 explicit SampleCheckpoint(BackgroundMethodSamplingProfiler* const profiler) :
125 profiler_(profiler) {}
126
127 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
128 Thread* self = Thread::Current();
129 if (thread == nullptr) {
130 LOG(ERROR) << "Checkpoint with nullptr thread";
131 return;
132 }
133
134 // Grab the mutator lock (shared access).
135 ScopedObjectAccess soa(self);
136
137 // Grab a sample.
138 GetSample(thread, this->profiler_);
139
140 // And finally tell the barrier that we're done.
141 this->profiler_->GetBarrier().Pass(self);
142 }
143
144 private:
145 BackgroundMethodSamplingProfiler* const profiler_;
146};
147
148bool BackgroundMethodSamplingProfiler::ShuttingDown(Thread* self) {
149 MutexLock mu(self, *Locks::profiler_lock_);
150 return shutting_down_;
151}
152
153void* BackgroundMethodSamplingProfiler::RunProfilerThread(void* arg) {
154 Runtime* runtime = Runtime::Current();
155 BackgroundMethodSamplingProfiler* profiler =
156 reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
157
158 // Add a random delay for the first time run so that we don't hammer the CPU
159 // with all profiles running at the same time.
160 const int kRandomDelayMaxSecs = 30;
161 const double kMaxBackoffSecs = 24*60*60; // Max backoff time.
162
163 srand(MicroTime() * getpid());
164 int startup_delay = rand() % kRandomDelayMaxSecs; // random delay for startup.
165
166
167 CHECK(runtime->AttachCurrentThread("Profiler", true, runtime->GetSystemThreadGroup(),
168 !runtime->IsCompiler()));
169
170 Thread* self = Thread::Current();
171
Calin Juravlec1b643c2014-05-30 23:44:11 +0100172 double backoff = 1.0;
Dave Allison0aded082013-11-07 13:15:11 -0800173 while (true) {
174 if (ShuttingDown(self)) {
175 break;
176 }
177
178 {
179 // wait until we need to run another profile
Calin Juravlec1b643c2014-05-30 23:44:11 +0100180 uint64_t delay_secs = profiler->options_.GetPeriodS() * backoff;
Dave Allison0aded082013-11-07 13:15:11 -0800181
182 // Add a startup delay to prevent all the profiles running at once.
183 delay_secs += startup_delay;
184
185 // Immediate startup for benchmarking?
Calin Juravlec1b643c2014-05-30 23:44:11 +0100186 if (profiler->options_.GetStartImmediately() && startup_delay > 0) {
Dave Allison0aded082013-11-07 13:15:11 -0800187 delay_secs = 0;
188 }
189
190 startup_delay = 0;
191
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700192 VLOG(profiler) << "Delaying profile start for " << delay_secs << " secs";
Dave Allison0aded082013-11-07 13:15:11 -0800193 MutexLock mu(self, profiler->wait_lock_);
194 profiler->period_condition_.TimedWait(self, delay_secs * 1000, 0);
195
196 // Expand the backoff by its coefficient, but don't go beyond the max.
Calin Juravlec1b643c2014-05-30 23:44:11 +0100197 backoff = std::min(backoff * profiler->options_.GetBackoffCoefficient(), kMaxBackoffSecs);
Dave Allison0aded082013-11-07 13:15:11 -0800198 }
199
200 if (ShuttingDown(self)) {
201 break;
202 }
203
204
205 uint64_t start_us = MicroTime();
Calin Juravlec1b643c2014-05-30 23:44:11 +0100206 uint64_t end_us = start_us + profiler->options_.GetDurationS() * UINT64_C(1000000);
Dave Allison0aded082013-11-07 13:15:11 -0800207 uint64_t now_us = start_us;
208
Calin Juravlec1b643c2014-05-30 23:44:11 +0100209 VLOG(profiler) << "Starting profiling run now for "
210 << PrettyDuration((end_us - start_us) * 1000);
Dave Allison0aded082013-11-07 13:15:11 -0800211
212 SampleCheckpoint check_point(profiler);
213
Dave Allison39c3bfb2014-01-28 18:33:52 -0800214 size_t valid_samples = 0;
Dave Allison0aded082013-11-07 13:15:11 -0800215 while (now_us < end_us) {
216 if (ShuttingDown(self)) {
217 break;
218 }
219
Calin Juravlec1b643c2014-05-30 23:44:11 +0100220 usleep(profiler->options_.GetIntervalUs()); // Non-interruptible sleep.
Dave Allison0aded082013-11-07 13:15:11 -0800221
222 ThreadList* thread_list = runtime->GetThreadList();
223
224 profiler->profiler_barrier_->Init(self, 0);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800225 size_t barrier_count = thread_list->RunCheckpointOnRunnableThreads(&check_point);
226
227 // All threads are suspended, nothing to do.
228 if (barrier_count == 0) {
229 now_us = MicroTime();
230 continue;
231 }
232
233 valid_samples += barrier_count;
Dave Allison0aded082013-11-07 13:15:11 -0800234
Wei Jin6a586912014-05-21 16:07:40 -0700235 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Dave Allison0aded082013-11-07 13:15:11 -0800236
237 // Wait for the barrier to be crossed by all runnable threads. This wait
238 // is done with a timeout so that we can detect problems with the checkpoint
239 // running code. We should never see this.
240 const uint32_t kWaitTimeoutMs = 10000;
241 const uint32_t kWaitTimeoutUs = kWaitTimeoutMs * 1000;
242
243 uint64_t waitstart_us = MicroTime();
244 // Wait for all threads to pass the barrier.
245 profiler->profiler_barrier_->Increment(self, barrier_count, kWaitTimeoutMs);
246 uint64_t waitend_us = MicroTime();
247 uint64_t waitdiff_us = waitend_us - waitstart_us;
248
249 // We should never get a timeout. If we do, it suggests a problem with the checkpoint
250 // code. Crash the process in this case.
251 CHECK_LT(waitdiff_us, kWaitTimeoutUs);
252
Dave Allison0aded082013-11-07 13:15:11 -0800253 // Update the current time.
254 now_us = MicroTime();
255 }
256
Wei Jin6a586912014-05-21 16:07:40 -0700257 if (valid_samples > 0) {
Dave Allison0aded082013-11-07 13:15:11 -0800258 // After the profile has been taken, write it out.
259 ScopedObjectAccess soa(self); // Acquire the mutator lock.
260 uint32_t size = profiler->WriteProfile();
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700261 VLOG(profiler) << "Profile size: " << size;
Dave Allison0aded082013-11-07 13:15:11 -0800262 }
263 }
264
265 LOG(INFO) << "Profiler shutdown";
266 runtime->DetachCurrentThread();
267 return nullptr;
268}
269
270// Write out the profile file if we are generating a profile.
271uint32_t BackgroundMethodSamplingProfiler::WriteProfile() {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100272 std::string full_name = output_filename_;
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700273 VLOG(profiler) << "Saving profile to " << full_name;
Dave Allison0aded082013-11-07 13:15:11 -0800274
Dave Allison39c3bfb2014-01-28 18:33:52 -0800275 int fd = open(full_name.c_str(), O_RDWR);
276 if (fd < 0) {
277 // Open failed.
278 LOG(ERROR) << "Failed to open profile file " << full_name;
Dave Allison0aded082013-11-07 13:15:11 -0800279 return 0;
280 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800281
282 // Lock the file for exclusive access. This will block if another process is using
283 // the file.
284 int err = flock(fd, LOCK_EX);
285 if (err < 0) {
286 LOG(ERROR) << "Failed to lock profile file " << full_name;
287 return 0;
288 }
289
290 // Read the previous profile.
Wei Jina93b0bb2014-06-09 16:19:15 -0700291 profile_table_.ReadPrevious(fd, options_.GetProfileType());
Dave Allison39c3bfb2014-01-28 18:33:52 -0800292
293 // Move back to the start of the file.
294 lseek(fd, 0, SEEK_SET);
295
296 // Format the profile output and write to the file.
Dave Allison0aded082013-11-07 13:15:11 -0800297 std::ostringstream os;
298 uint32_t num_methods = DumpProfile(os);
299 std::string data(os.str());
Dave Allison39c3bfb2014-01-28 18:33:52 -0800300 const char *p = data.c_str();
301 size_t length = data.length();
302 size_t full_length = length;
303 do {
304 int n = ::write(fd, p, length);
305 p += n;
306 length -= n;
307 } while (length > 0);
308
309 // Truncate the file to the new length.
310 ftruncate(fd, full_length);
311
312 // Now unlock the file, allowing another process in.
313 err = flock(fd, LOCK_UN);
314 if (err < 0) {
315 LOG(ERROR) << "Failed to unlock profile file " << full_name;
316 }
317
318 // Done, close the file.
319 ::close(fd);
320
321 // Clean the profile for the next time.
322 CleanProfile();
323
Dave Allison0aded082013-11-07 13:15:11 -0800324 return num_methods;
325}
326
Calin Juravlec1b643c2014-05-30 23:44:11 +0100327bool BackgroundMethodSamplingProfiler::Start(
328 const std::string& output_filename, const ProfilerOptions& options) {
329 if (!options.IsEnabled()) {
330 LOG(INFO) << "Profiler disabled. To enable setprop dalvik.vm.profiler 1.";
331 return false;
332 }
333
334 CHECK(!output_filename.empty());
335
Dave Allison0aded082013-11-07 13:15:11 -0800336 Thread* self = Thread::Current();
337 {
338 MutexLock mu(self, *Locks::profiler_lock_);
339 // Don't start two profiler threads.
340 if (profiler_ != nullptr) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100341 return true;
Dave Allison0aded082013-11-07 13:15:11 -0800342 }
343 }
344
Calin Juravlec1b643c2014-05-30 23:44:11 +0100345 LOG(INFO) << "Starting profiler using output file: " << output_filename
346 << " and options: " << options;
Dave Allison0aded082013-11-07 13:15:11 -0800347 {
348 MutexLock mu(self, *Locks::profiler_lock_);
Calin Juravlec1b643c2014-05-30 23:44:11 +0100349 profiler_ = new BackgroundMethodSamplingProfiler(output_filename, options);
Dave Allison0aded082013-11-07 13:15:11 -0800350
351 CHECK_PTHREAD_CALL(pthread_create, (&profiler_pthread_, nullptr, &RunProfilerThread,
352 reinterpret_cast<void*>(profiler_)),
353 "Profiler thread");
354 }
Calin Juravlec1b643c2014-05-30 23:44:11 +0100355 return true;
Dave Allison0aded082013-11-07 13:15:11 -0800356}
357
358
359
360void BackgroundMethodSamplingProfiler::Stop() {
361 BackgroundMethodSamplingProfiler* profiler = nullptr;
362 pthread_t profiler_pthread = 0U;
363 {
364 MutexLock trace_mu(Thread::Current(), *Locks::profiler_lock_);
Wei Jin6a586912014-05-21 16:07:40 -0700365 CHECK(!shutting_down_);
Dave Allison0aded082013-11-07 13:15:11 -0800366 profiler = profiler_;
367 shutting_down_ = true;
368 profiler_pthread = profiler_pthread_;
369 }
370
371 // Now wake up the sampler thread if it sleeping.
372 {
373 MutexLock profile_mu(Thread::Current(), profiler->wait_lock_);
374 profiler->period_condition_.Signal(Thread::Current());
375 }
376 // Wait for the sample thread to stop.
377 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profiler thread shutdown");
378
379 {
380 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
381 profiler_ = nullptr;
382 }
383 delete profiler;
384}
385
386
387void BackgroundMethodSamplingProfiler::Shutdown() {
388 Stop();
389}
390
Calin Juravlec1b643c2014-05-30 23:44:11 +0100391BackgroundMethodSamplingProfiler::BackgroundMethodSamplingProfiler(
392 const std::string& output_filename, const ProfilerOptions& options)
393 : output_filename_(output_filename),
394 options_(options),
Dave Allison0aded082013-11-07 13:15:11 -0800395 wait_lock_("Profile wait lock"),
396 period_condition_("Profile condition", wait_lock_),
397 profile_table_(wait_lock_),
398 profiler_barrier_(new Barrier(0)) {
399 // Populate the filtered_methods set.
400 // This is empty right now, but to add a method, do this:
401 //
402 // filtered_methods_.insert("void java.lang.Object.wait(long, int)");
403}
404
Wei Jin445220d2014-06-20 15:56:53 -0700405// Filter out methods the profiler doesn't want to record.
406// We require mutator lock since some statistics will be updated here.
407bool BackgroundMethodSamplingProfiler::ProcessMethod(mirror::ArtMethod* method) {
Dave Allison0aded082013-11-07 13:15:11 -0800408 if (method == nullptr) {
409 profile_table_.NullMethod();
410 // Don't record a nullptr method.
Wei Jin445220d2014-06-20 15:56:53 -0700411 return false;
Dave Allison0aded082013-11-07 13:15:11 -0800412 }
413
414 mirror::Class* cls = method->GetDeclaringClass();
415 if (cls != nullptr) {
416 if (cls->GetClassLoader() == nullptr) {
417 // Don't include things in the boot
418 profile_table_.BootMethod();
Wei Jin445220d2014-06-20 15:56:53 -0700419 return false;
Dave Allison0aded082013-11-07 13:15:11 -0800420 }
421 }
422
423 bool is_filtered = false;
424
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700425 if (strcmp(method->GetName(), "<clinit>") == 0) {
Dave Allison0aded082013-11-07 13:15:11 -0800426 // always filter out class init
427 is_filtered = true;
428 }
429
430 // Filter out methods by name if there are any.
431 if (!is_filtered && filtered_methods_.size() > 0) {
432 std::string method_full_name = PrettyMethod(method);
433
434 // Don't include specific filtered methods.
435 is_filtered = filtered_methods_.count(method_full_name) != 0;
436 }
Wei Jin445220d2014-06-20 15:56:53 -0700437 return !is_filtered;
438}
Dave Allison0aded082013-11-07 13:15:11 -0800439
Wei Jin445220d2014-06-20 15:56:53 -0700440// A method has been hit, record its invocation in the method map.
441// The mutator_lock must be held (shared) when this is called.
442void BackgroundMethodSamplingProfiler::RecordMethod(mirror::ArtMethod* method) {
Dave Allison0aded082013-11-07 13:15:11 -0800443 // Add to the profile table unless it is filtered out.
Wei Jin445220d2014-06-20 15:56:53 -0700444 if (ProcessMethod(method)) {
445 profile_table_.Put(method);
446 }
447}
448
449// Record the current bounded stack into sampling results.
450void BackgroundMethodSamplingProfiler::RecordStack(const std::vector<InstructionLocation>& stack) {
451 if (stack.size() == 0) {
452 return;
453 }
454 // Get the method on top of the stack. We use this method to perform filtering.
455 mirror::ArtMethod* method = stack.front().first;
456 if (ProcessMethod(method)) {
457 profile_table_.PutStack(stack);
Dave Allison0aded082013-11-07 13:15:11 -0800458 }
459}
460
461// Clean out any recordings for the method traces.
462void BackgroundMethodSamplingProfiler::CleanProfile() {
463 profile_table_.Clear();
464}
465
466uint32_t BackgroundMethodSamplingProfiler::DumpProfile(std::ostream& os) {
Wei Jina93b0bb2014-06-09 16:19:15 -0700467 return profile_table_.Write(os, options_.GetProfileType());
Dave Allison0aded082013-11-07 13:15:11 -0800468}
469
470// Profile Table.
471// This holds a mapping of mirror::ArtMethod* to a count of how many times a sample
472// hit it at the top of the stack.
473ProfileSampleResults::ProfileSampleResults(Mutex& lock) : lock_(lock), num_samples_(0),
474 num_null_methods_(0),
475 num_boot_methods_(0) {
476 for (int i = 0; i < kHashSize; i++) {
477 table[i] = nullptr;
478 }
Wei Jin445220d2014-06-20 15:56:53 -0700479 method_context_table = nullptr;
480 stack_trie_root_ = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800481}
482
483ProfileSampleResults::~ProfileSampleResults() {
Wei Jina93b0bb2014-06-09 16:19:15 -0700484 Clear();
Dave Allison0aded082013-11-07 13:15:11 -0800485}
486
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100487// Add a method to the profile table. If it's the first time the method
Dave Allison0aded082013-11-07 13:15:11 -0800488// has been seen, add it with count=1, otherwise increment the count.
489void ProfileSampleResults::Put(mirror::ArtMethod* method) {
Wei Jina93b0bb2014-06-09 16:19:15 -0700490 MutexLock mu(Thread::Current(), lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800491 uint32_t index = Hash(method);
492 if (table[index] == nullptr) {
493 table[index] = new Map();
494 }
495 Map::iterator i = table[index]->find(method);
496 if (i == table[index]->end()) {
497 (*table[index])[method] = 1;
498 } else {
499 i->second++;
500 }
501 num_samples_++;
Wei Jina93b0bb2014-06-09 16:19:15 -0700502}
503
Wei Jin445220d2014-06-20 15:56:53 -0700504// Add a bounded stack to the profile table. Only the count of the method on
505// top of the frame will be increased.
506void ProfileSampleResults::PutStack(const std::vector<InstructionLocation>& stack) {
Wei Jina93b0bb2014-06-09 16:19:15 -0700507 MutexLock mu(Thread::Current(), lock_);
Wei Jin445220d2014-06-20 15:56:53 -0700508 ScopedObjectAccess soa(Thread::Current());
509 if (stack_trie_root_ == nullptr) {
510 // The root of the stack trie is a dummy node so that we don't have to maintain
511 // a collection of tries.
512 stack_trie_root_ = new StackTrieNode();
Wei Jina93b0bb2014-06-09 16:19:15 -0700513 }
Wei Jin445220d2014-06-20 15:56:53 -0700514
515 StackTrieNode* current = stack_trie_root_;
516 if (stack.size() == 0) {
517 current->IncreaseCount();
518 return;
519 }
520
521 for (std::vector<InstructionLocation>::const_reverse_iterator iter = stack.rbegin();
522 iter != stack.rend(); ++iter) {
523 InstructionLocation inst_loc = *iter;
524 mirror::ArtMethod* method = inst_loc.first;
525 if (method == nullptr) {
526 // skip null method
527 continue;
528 }
529 uint32_t dex_pc = inst_loc.second;
530 uint32_t method_idx = method->GetDexMethodIndex();
531 const DexFile* dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
532 MethodReference method_ref(dex_file, method_idx);
533 StackTrieNode* child = current->FindChild(method_ref, dex_pc);
534 if (child != nullptr) {
535 current = child;
Wei Jina93b0bb2014-06-09 16:19:15 -0700536 } else {
Wei Jin445220d2014-06-20 15:56:53 -0700537 uint32_t method_size = 0;
538 const DexFile::CodeItem* codeitem = method->GetCodeItem();
539 if (codeitem != nullptr) {
540 method_size = codeitem->insns_size_in_code_units_;
541 }
542 StackTrieNode* new_node = new StackTrieNode(method_ref, dex_pc, method_size, current);
543 current->AppendChild(new_node);
544 current = new_node;
Wei Jina93b0bb2014-06-09 16:19:15 -0700545 }
546 }
Wei Jin445220d2014-06-20 15:56:53 -0700547
548 if (current != stack_trie_root_ && current->GetCount() == 0) {
549 // Insert into method_context table;
550 if (method_context_table == nullptr) {
551 method_context_table = new MethodContextMap();
552 }
553 MethodReference method = current->GetMethod();
554 MethodContextMap::iterator i = method_context_table->find(method);
555 if (i == method_context_table->end()) {
556 TrieNodeSet* node_set = new TrieNodeSet();
557 node_set->insert(current);
558 (*method_context_table)[method] = node_set;
559 } else {
560 TrieNodeSet* node_set = i->second;
561 node_set->insert(current);
562 }
563 }
564 current->IncreaseCount();
Wei Jina93b0bb2014-06-09 16:19:15 -0700565 num_samples_++;
Dave Allison0aded082013-11-07 13:15:11 -0800566}
567
Dave Allison39c3bfb2014-01-28 18:33:52 -0800568// Write the profile table to the output stream. Also merge with the previous profile.
Wei Jina93b0bb2014-06-09 16:19:15 -0700569uint32_t ProfileSampleResults::Write(std::ostream& os, ProfileDataType type) {
Dave Allison0aded082013-11-07 13:15:11 -0800570 ScopedObjectAccess soa(Thread::Current());
Dave Allison39c3bfb2014-01-28 18:33:52 -0800571 num_samples_ += previous_num_samples_;
572 num_null_methods_ += previous_num_null_methods_;
573 num_boot_methods_ += previous_num_boot_methods_;
574
Calin Juravlec1b643c2014-05-30 23:44:11 +0100575 VLOG(profiler) << "Profile: "
576 << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_;
Dave Allison0aded082013-11-07 13:15:11 -0800577 os << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_ << "\n";
578 uint32_t num_methods = 0;
Wei Jina93b0bb2014-06-09 16:19:15 -0700579 if (type == kProfilerMethod) {
580 for (int i = 0 ; i < kHashSize; i++) {
581 Map *map = table[i];
582 if (map != nullptr) {
583 for (const auto &meth_iter : *map) {
584 mirror::ArtMethod *method = meth_iter.first;
585 std::string method_name = PrettyMethod(method);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800586
Wei Jina93b0bb2014-06-09 16:19:15 -0700587 const DexFile::CodeItem* codeitem = method->GetCodeItem();
588 uint32_t method_size = 0;
589 if (codeitem != nullptr) {
590 method_size = codeitem->insns_size_in_code_units_;
591 }
592 uint32_t count = meth_iter.second;
Dave Allison39c3bfb2014-01-28 18:33:52 -0800593
Wei Jina93b0bb2014-06-09 16:19:15 -0700594 // Merge this profile entry with one from a previous run (if present). Also
595 // remove the previous entry.
596 PreviousProfile::iterator pi = previous_.find(method_name);
597 if (pi != previous_.end()) {
598 count += pi->second.count_;
599 previous_.erase(pi);
600 }
601 os << StringPrintf("%s/%u/%u\n", method_name.c_str(), count, method_size);
602 ++num_methods;
Dave Allison39c3bfb2014-01-28 18:33:52 -0800603 }
Wei Jina93b0bb2014-06-09 16:19:15 -0700604 }
605 }
Wei Jin445220d2014-06-20 15:56:53 -0700606 } else if (type == kProfilerBoundedStack) {
607 if (method_context_table != nullptr) {
608 for (const auto &method_iter : *method_context_table) {
609 MethodReference method = method_iter.first;
610 TrieNodeSet* node_set = method_iter.second;
611 std::string method_name = PrettyMethod(method.dex_method_index, *(method.dex_file));
612 uint32_t method_size = 0;
613 uint32_t total_count = 0;
614 PreviousContextMap new_context_map;
615 for (const auto &trie_node_i : *node_set) {
616 StackTrieNode* node = trie_node_i;
617 method_size = node->GetMethodSize();
618 uint32_t count = node->GetCount();
619 uint32_t dexpc = node->GetDexPC();
620 total_count += count;
Wei Jina93b0bb2014-06-09 16:19:15 -0700621
Wei Jin445220d2014-06-20 15:56:53 -0700622 StackTrieNode* current = node->GetParent();
623 // We go backward on the trie to retrieve context and dex_pc until the dummy root.
624 // The format of the context is "method_1@pc_1@method_2@pc_2@..."
625 std::vector<std::string> context_vector;
626 while (current != nullptr && current->GetParent() != nullptr) {
627 context_vector.push_back(StringPrintf("%s@%u",
628 PrettyMethod(current->GetMethod().dex_method_index, *(current->GetMethod().dex_file)).c_str(),
629 current->GetDexPC()));
630 current = current->GetParent();
Wei Jina93b0bb2014-06-09 16:19:15 -0700631 }
Wei Jin445220d2014-06-20 15:56:53 -0700632 std::string context_sig = Join(context_vector, '@');
633 new_context_map[std::make_pair(dexpc, context_sig)] = count;
634 }
Wei Jina93b0bb2014-06-09 16:19:15 -0700635
Wei Jin445220d2014-06-20 15:56:53 -0700636 PreviousProfile::iterator pi = previous_.find(method_name);
637 if (pi != previous_.end()) {
638 total_count += pi->second.count_;
639 PreviousContextMap* previous_context_map = pi->second.context_map_;
640 if (previous_context_map != nullptr) {
641 for (const auto &context_i : *previous_context_map) {
642 uint32_t count = context_i.second;
643 PreviousContextMap::iterator ci = new_context_map.find(context_i.first);
644 if (ci == new_context_map.end()) {
645 new_context_map[context_i.first] = count;
646 } else {
647 ci->second += count;
Wei Jina93b0bb2014-06-09 16:19:15 -0700648 }
649 }
Wei Jina93b0bb2014-06-09 16:19:15 -0700650 }
Wei Jin445220d2014-06-20 15:56:53 -0700651 delete previous_context_map;
652 previous_.erase(pi);
Wei Jina93b0bb2014-06-09 16:19:15 -0700653 }
Wei Jin445220d2014-06-20 15:56:53 -0700654 // We write out profile data with dex pc and context information in the following format:
655 // "method/total_count/size/[pc_1:count_1:context_1#pc_2:count_2:context_2#...]".
656 std::vector<std::string> context_count_vector;
657 for (const auto &context_i : new_context_map) {
658 context_count_vector.push_back(StringPrintf("%u:%u:%s", context_i.first.first,
659 context_i.second, context_i.first.second.c_str()));
660 }
661 os << StringPrintf("%s/%u/%u/[%s]\n", method_name.c_str(), total_count,
662 method_size, Join(context_count_vector, '#').c_str());
663 ++num_methods;
Dave Allison39c3bfb2014-01-28 18:33:52 -0800664 }
Dave Allison0aded082013-11-07 13:15:11 -0800665 }
666 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800667
668 // Now we write out the remaining previous methods.
Wei Jina93b0bb2014-06-09 16:19:15 -0700669 for (const auto &pi : previous_) {
670 if (type == kProfilerMethod) {
671 os << StringPrintf("%s/%u/%u\n", pi.first.c_str(), pi.second.count_, pi.second.method_size_);
Wei Jin445220d2014-06-20 15:56:53 -0700672 } else if (type == kProfilerBoundedStack) {
Wei Jina93b0bb2014-06-09 16:19:15 -0700673 os << StringPrintf("%s/%u/%u/[", pi.first.c_str(), pi.second.count_, pi.second.method_size_);
Wei Jin445220d2014-06-20 15:56:53 -0700674 PreviousContextMap* previous_context_map = pi.second.context_map_;
675 if (previous_context_map != nullptr) {
676 std::vector<std::string> context_count_vector;
677 for (const auto &context_i : *previous_context_map) {
678 context_count_vector.push_back(StringPrintf("%u:%u:%s", context_i.first.first,
679 context_i.second, context_i.first.second.c_str()));
Wei Jina93b0bb2014-06-09 16:19:15 -0700680 }
Wei Jin445220d2014-06-20 15:56:53 -0700681 os << Join(context_count_vector, '#');
Wei Jina93b0bb2014-06-09 16:19:15 -0700682 }
683 os << "]\n";
684 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800685 ++num_methods;
686 }
Dave Allison0aded082013-11-07 13:15:11 -0800687 return num_methods;
688}
689
690void ProfileSampleResults::Clear() {
691 num_samples_ = 0;
692 num_null_methods_ = 0;
693 num_boot_methods_ = 0;
694 for (int i = 0; i < kHashSize; i++) {
Wei Jina93b0bb2014-06-09 16:19:15 -0700695 delete table[i];
696 table[i] = nullptr;
Wei Jin445220d2014-06-20 15:56:53 -0700697 }
698 if (stack_trie_root_ != nullptr) {
699 stack_trie_root_->DeleteChildren();
700 delete stack_trie_root_;
701 stack_trie_root_ = nullptr;
702 if (method_context_table != nullptr) {
703 delete method_context_table;
704 method_context_table = nullptr;
Wei Jina93b0bb2014-06-09 16:19:15 -0700705 }
Wei Jina93b0bb2014-06-09 16:19:15 -0700706 }
707 for (auto &pi : previous_) {
Wei Jin445220d2014-06-20 15:56:53 -0700708 if (pi.second.context_map_ != nullptr) {
709 delete pi.second.context_map_;
710 pi.second.context_map_ = nullptr;
711 }
Dave Allison0aded082013-11-07 13:15:11 -0800712 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800713 previous_.clear();
Dave Allison0aded082013-11-07 13:15:11 -0800714}
715
716uint32_t ProfileSampleResults::Hash(mirror::ArtMethod* method) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800717 return (PointerToLowMemUInt32(method) >> 3) % kHashSize;
Dave Allison0aded082013-11-07 13:15:11 -0800718}
719
Dave Allison39c3bfb2014-01-28 18:33:52 -0800720// Read a single line into the given string. Returns true if everything OK, false
721// on EOF or error.
722static bool ReadProfileLine(int fd, std::string& line) {
723 char buf[4];
724 line.clear();
725 while (true) {
726 int n = read(fd, buf, 1); // TODO: could speed this up but is it worth it?
727 if (n != 1) {
728 return false;
729 }
730 if (buf[0] == '\n') {
731 break;
732 }
733 line += buf[0];
734 }
735 return true;
736}
737
Wei Jina93b0bb2014-06-09 16:19:15 -0700738void ProfileSampleResults::ReadPrevious(int fd, ProfileDataType type) {
Dave Allison39c3bfb2014-01-28 18:33:52 -0800739 // Reset counters.
740 previous_num_samples_ = previous_num_null_methods_ = previous_num_boot_methods_ = 0;
741
742 std::string line;
743
744 // The first line contains summary information.
745 if (!ReadProfileLine(fd, line)) {
746 return;
747 }
748 std::vector<std::string> summary_info;
749 Split(line, '/', summary_info);
750 if (summary_info.size() != 3) {
751 // Bad summary info. It should be count/nullcount/bootcount
752 return;
753 }
Wei Jinf21f0a92014-06-27 17:44:18 -0700754 previous_num_samples_ = strtoul(summary_info[0].c_str(), nullptr, 10);
755 previous_num_null_methods_ = strtoul(summary_info[1].c_str(), nullptr, 10);
756 previous_num_boot_methods_ = strtoul(summary_info[2].c_str(), nullptr, 10);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800757
Wei Jina93b0bb2014-06-09 16:19:15 -0700758 // Now read each line until the end of file. Each line consists of 3 or 4 fields separated by /
Dave Allison39c3bfb2014-01-28 18:33:52 -0800759 while (true) {
760 if (!ReadProfileLine(fd, line)) {
761 break;
762 }
763 std::vector<std::string> info;
764 Split(line, '/', info);
Wei Jina93b0bb2014-06-09 16:19:15 -0700765 if (info.size() != 3 && info.size() != 4) {
Dave Allison39c3bfb2014-01-28 18:33:52 -0800766 // Malformed.
767 break;
768 }
769 std::string methodname = info[0];
Wei Jinf21f0a92014-06-27 17:44:18 -0700770 uint32_t total_count = strtoul(info[1].c_str(), nullptr, 10);
771 uint32_t size = strtoul(info[2].c_str(), nullptr, 10);
Wei Jin445220d2014-06-20 15:56:53 -0700772 PreviousContextMap* context_map = nullptr;
773 if (type == kProfilerBoundedStack && info.size() == 4) {
774 context_map = new PreviousContextMap();
775 std::string context_counts_str = info[3].substr(1, info[3].size() - 2);
776 std::vector<std::string> context_count_pairs;
777 Split(context_counts_str, '#', context_count_pairs);
778 for (uint32_t i = 0; i < context_count_pairs.size(); ++i) {
779 std::vector<std::string> context_count;
780 Split(context_count_pairs[i], ':', context_count);
781 if (context_count.size() == 2) {
782 // Handles the situtation when the profile file doesn't contain context information.
Wei Jinf21f0a92014-06-27 17:44:18 -0700783 uint32_t dexpc = strtoul(context_count[0].c_str(), nullptr, 10);
784 uint32_t count = strtoul(context_count[1].c_str(), nullptr, 10);
Wei Jin445220d2014-06-20 15:56:53 -0700785 (*context_map)[std::make_pair(dexpc, "")] = count;
786 } else {
787 // Handles the situtation when the profile file contains context information.
Wei Jinf21f0a92014-06-27 17:44:18 -0700788 uint32_t dexpc = strtoul(context_count[0].c_str(), nullptr, 10);
789 uint32_t count = strtoul(context_count[1].c_str(), nullptr, 10);
Wei Jin445220d2014-06-20 15:56:53 -0700790 std::string context = context_count[2];
791 (*context_map)[std::make_pair(dexpc, context)] = count;
792 }
Wei Jina93b0bb2014-06-09 16:19:15 -0700793 }
794 }
Wei Jin445220d2014-06-20 15:56:53 -0700795 previous_[methodname] = PreviousValue(total_count, size, context_map);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800796 }
797}
Dave Allison0aded082013-11-07 13:15:11 -0800798
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100799bool ProfileFile::LoadFile(const std::string& fileName) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300800 LOG(VERBOSE) << "reading profile file " << fileName;
801 struct stat st;
802 int err = stat(fileName.c_str(), &st);
803 if (err == -1) {
804 LOG(VERBOSE) << "not found";
805 return false;
806 }
807 if (st.st_size == 0) {
Dave Allison644789f2014-04-10 13:06:10 -0700808 return false; // Empty profiles are invalid.
Calin Juravle9dae5b42014-04-07 16:36:21 +0300809 }
810 std::ifstream in(fileName.c_str());
811 if (!in) {
812 LOG(VERBOSE) << "profile file " << fileName << " exists but can't be opened";
813 LOG(VERBOSE) << "file owner: " << st.st_uid << ":" << st.st_gid;
814 LOG(VERBOSE) << "me: " << getuid() << ":" << getgid();
815 LOG(VERBOSE) << "file permissions: " << std::oct << st.st_mode;
816 LOG(VERBOSE) << "errno: " << errno;
817 return false;
818 }
819 // The first line contains summary information.
820 std::string line;
821 std::getline(in, line);
822 if (in.eof()) {
823 return false;
824 }
825 std::vector<std::string> summary_info;
826 Split(line, '/', summary_info);
827 if (summary_info.size() != 3) {
Calin Juravle19477a82014-06-06 12:24:21 +0100828 // Bad summary info. It should be total/null/boot.
Calin Juravle9dae5b42014-04-07 16:36:21 +0300829 return false;
830 }
Calin Juravle19477a82014-06-06 12:24:21 +0100831 // This is the number of hits in all profiled methods (without nullptr or boot methods)
Wei Jinf21f0a92014-06-27 17:44:18 -0700832 uint32_t total_count = strtoul(summary_info[0].c_str(), nullptr, 10);
Calin Juravle9dae5b42014-04-07 16:36:21 +0300833
834 // Now read each line until the end of file. Each line consists of 3 fields separated by '/'.
835 // Store the info in descending order given by the most used methods.
836 typedef std::set<std::pair<int, std::vector<std::string>>> ProfileSet;
837 ProfileSet countSet;
838 while (!in.eof()) {
839 std::getline(in, line);
840 if (in.eof()) {
841 break;
842 }
843 std::vector<std::string> info;
844 Split(line, '/', info);
Wei Jina93b0bb2014-06-09 16:19:15 -0700845 if (info.size() != 3 && info.size() != 4) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300846 // Malformed.
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100847 return false;
Calin Juravle9dae5b42014-04-07 16:36:21 +0300848 }
849 int count = atoi(info[1].c_str());
850 countSet.insert(std::make_pair(-count, info));
851 }
852
853 uint32_t curTotalCount = 0;
854 ProfileSet::iterator end = countSet.end();
855 const ProfileData* prevData = nullptr;
856 for (ProfileSet::iterator it = countSet.begin(); it != end ; it++) {
857 const std::string& methodname = it->second[0];
858 uint32_t count = -it->first;
Wei Jinf21f0a92014-06-27 17:44:18 -0700859 uint32_t size = strtoul(it->second[2].c_str(), nullptr, 10);
Calin Juravle9dae5b42014-04-07 16:36:21 +0300860 double usedPercent = (count * 100.0) / total_count;
861
862 curTotalCount += count;
863 // Methods with the same count should be part of the same top K percentage bucket.
864 double topKPercentage = (prevData != nullptr) && (prevData->GetCount() == count)
865 ? prevData->GetTopKUsedPercentage()
866 : 100 * static_cast<double>(curTotalCount) / static_cast<double>(total_count);
867
868 // Add it to the profile map.
869 ProfileData curData = ProfileData(methodname, count, size, usedPercent, topKPercentage);
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100870 profile_map_[methodname] = curData;
Calin Juravle9dae5b42014-04-07 16:36:21 +0300871 prevData = &curData;
872 }
873 return true;
874}
875
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100876bool ProfileFile::GetProfileData(ProfileFile::ProfileData* data, const std::string& method_name) {
877 ProfileMap::iterator i = profile_map_.find(method_name);
878 if (i == profile_map_.end()) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300879 return false;
880 }
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100881 *data = i->second;
882 return true;
883}
884
885bool ProfileFile::GetTopKSamples(std::set<std::string>& topKSamples, double topKPercentage) {
886 ProfileMap::iterator end = profile_map_.end();
887 for (ProfileMap::iterator it = profile_map_.begin(); it != end; it++) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300888 if (it->second.GetTopKUsedPercentage() < topKPercentage) {
889 topKSamples.insert(it->first);
890 }
891 }
892 return true;
893}
894
Wei Jin445220d2014-06-20 15:56:53 -0700895StackTrieNode* StackTrieNode::FindChild(MethodReference method, uint32_t dex_pc) {
896 if (children_.size() == 0) {
897 return nullptr;
898 }
899 // Create a dummy node for searching.
900 StackTrieNode* node = new StackTrieNode(method, dex_pc, 0, nullptr);
901 std::set<StackTrieNode*, StackTrieNodeComparator>::iterator i = children_.find(node);
902 delete node;
903 return (i == children_.end()) ? nullptr : *i;
904}
905
906void StackTrieNode::DeleteChildren() {
907 for (auto &child : children_) {
908 if (child != nullptr) {
909 child->DeleteChildren();
910 delete child;
911 }
912 }
913}
914
Calin Juravle9dae5b42014-04-07 16:36:21 +0300915} // namespace art