blob: bad79b3a3ba924882734b026d42285d0a471b1aa [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"
35#include "object_utils.h"
36#include "os.h"
37#include "scoped_thread_state_change.h"
38#include "ScopedLocalRef.h"
39#include "thread.h"
40#include "thread_list.h"
Dave Allison4a7867b2014-01-30 17:44:12 -080041
42#ifdef HAVE_ANDROID_OS
43#include "cutils/properties.h"
44#endif
45
Dave Allison0aded082013-11-07 13:15:11 -080046#if !defined(ART_USE_PORTABLE_COMPILER)
47#include "entrypoints/quick/quick_entrypoints.h"
48#endif
49
50namespace art {
51
52BackgroundMethodSamplingProfiler* BackgroundMethodSamplingProfiler::profiler_ = nullptr;
53pthread_t BackgroundMethodSamplingProfiler::profiler_pthread_ = 0U;
54volatile bool BackgroundMethodSamplingProfiler::shutting_down_ = false;
55
Dave Allison0aded082013-11-07 13:15:11 -080056// TODO: this profiler runs regardless of the state of the machine. Maybe we should use the
57// wakelock or something to modify the run characteristics. This can be done when we
58// have some performance data after it's been used for a while.
59
60
61// This is called from either a thread list traversal or from a checkpoint. Regardless
62// of which caller, the mutator lock must be held.
63static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
64 BackgroundMethodSamplingProfiler* profiler =
65 reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
66 mirror::ArtMethod* method = thread->GetCurrentMethod(nullptr);
67 if (false && method == nullptr) {
68 LOG(INFO) << "No current method available";
69 std::ostringstream os;
70 thread->Dump(os);
71 std::string data(os.str());
72 LOG(INFO) << data;
73 }
74 profiler->RecordMethod(method);
75}
76
Dave Allison0aded082013-11-07 13:15:11 -080077// A closure that is called by the thread checkpoint code.
78class SampleCheckpoint : public Closure {
79 public:
80 explicit SampleCheckpoint(BackgroundMethodSamplingProfiler* const profiler) :
81 profiler_(profiler) {}
82
83 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
84 Thread* self = Thread::Current();
85 if (thread == nullptr) {
86 LOG(ERROR) << "Checkpoint with nullptr thread";
87 return;
88 }
89
90 // Grab the mutator lock (shared access).
91 ScopedObjectAccess soa(self);
92
93 // Grab a sample.
94 GetSample(thread, this->profiler_);
95
96 // And finally tell the barrier that we're done.
97 this->profiler_->GetBarrier().Pass(self);
98 }
99
100 private:
101 BackgroundMethodSamplingProfiler* const profiler_;
102};
103
104bool BackgroundMethodSamplingProfiler::ShuttingDown(Thread* self) {
105 MutexLock mu(self, *Locks::profiler_lock_);
106 return shutting_down_;
107}
108
109void* BackgroundMethodSamplingProfiler::RunProfilerThread(void* arg) {
110 Runtime* runtime = Runtime::Current();
111 BackgroundMethodSamplingProfiler* profiler =
112 reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
113
114 // Add a random delay for the first time run so that we don't hammer the CPU
115 // with all profiles running at the same time.
116 const int kRandomDelayMaxSecs = 30;
117 const double kMaxBackoffSecs = 24*60*60; // Max backoff time.
118
119 srand(MicroTime() * getpid());
120 int startup_delay = rand() % kRandomDelayMaxSecs; // random delay for startup.
121
122
123 CHECK(runtime->AttachCurrentThread("Profiler", true, runtime->GetSystemThreadGroup(),
124 !runtime->IsCompiler()));
125
126 Thread* self = Thread::Current();
127
Calin Juravlec1b643c2014-05-30 23:44:11 +0100128 double backoff = 1.0;
Dave Allison0aded082013-11-07 13:15:11 -0800129 while (true) {
130 if (ShuttingDown(self)) {
131 break;
132 }
133
134 {
135 // wait until we need to run another profile
Calin Juravlec1b643c2014-05-30 23:44:11 +0100136 uint64_t delay_secs = profiler->options_.GetPeriodS() * backoff;
Dave Allison0aded082013-11-07 13:15:11 -0800137
138 // Add a startup delay to prevent all the profiles running at once.
139 delay_secs += startup_delay;
140
141 // Immediate startup for benchmarking?
Calin Juravlec1b643c2014-05-30 23:44:11 +0100142 if (profiler->options_.GetStartImmediately() && startup_delay > 0) {
Dave Allison0aded082013-11-07 13:15:11 -0800143 delay_secs = 0;
144 }
145
146 startup_delay = 0;
147
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700148 VLOG(profiler) << "Delaying profile start for " << delay_secs << " secs";
Dave Allison0aded082013-11-07 13:15:11 -0800149 MutexLock mu(self, profiler->wait_lock_);
150 profiler->period_condition_.TimedWait(self, delay_secs * 1000, 0);
151
152 // Expand the backoff by its coefficient, but don't go beyond the max.
Calin Juravlec1b643c2014-05-30 23:44:11 +0100153 backoff = std::min(backoff * profiler->options_.GetBackoffCoefficient(), kMaxBackoffSecs);
Dave Allison0aded082013-11-07 13:15:11 -0800154 }
155
156 if (ShuttingDown(self)) {
157 break;
158 }
159
160
161 uint64_t start_us = MicroTime();
Calin Juravlec1b643c2014-05-30 23:44:11 +0100162 uint64_t end_us = start_us + profiler->options_.GetDurationS() * UINT64_C(1000000);
Dave Allison0aded082013-11-07 13:15:11 -0800163 uint64_t now_us = start_us;
164
Calin Juravlec1b643c2014-05-30 23:44:11 +0100165 VLOG(profiler) << "Starting profiling run now for "
166 << PrettyDuration((end_us - start_us) * 1000);
Dave Allison0aded082013-11-07 13:15:11 -0800167
168 SampleCheckpoint check_point(profiler);
169
Dave Allison39c3bfb2014-01-28 18:33:52 -0800170 size_t valid_samples = 0;
Dave Allison0aded082013-11-07 13:15:11 -0800171 while (now_us < end_us) {
172 if (ShuttingDown(self)) {
173 break;
174 }
175
Calin Juravlec1b643c2014-05-30 23:44:11 +0100176 usleep(profiler->options_.GetIntervalUs()); // Non-interruptible sleep.
Dave Allison0aded082013-11-07 13:15:11 -0800177
178 ThreadList* thread_list = runtime->GetThreadList();
179
180 profiler->profiler_barrier_->Init(self, 0);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800181 size_t barrier_count = thread_list->RunCheckpointOnRunnableThreads(&check_point);
182
183 // All threads are suspended, nothing to do.
184 if (barrier_count == 0) {
185 now_us = MicroTime();
186 continue;
187 }
188
189 valid_samples += barrier_count;
Dave Allison0aded082013-11-07 13:15:11 -0800190
Wei Jin6a586912014-05-21 16:07:40 -0700191 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Dave Allison0aded082013-11-07 13:15:11 -0800192
193 // Wait for the barrier to be crossed by all runnable threads. This wait
194 // is done with a timeout so that we can detect problems with the checkpoint
195 // running code. We should never see this.
196 const uint32_t kWaitTimeoutMs = 10000;
197 const uint32_t kWaitTimeoutUs = kWaitTimeoutMs * 1000;
198
199 uint64_t waitstart_us = MicroTime();
200 // Wait for all threads to pass the barrier.
201 profiler->profiler_barrier_->Increment(self, barrier_count, kWaitTimeoutMs);
202 uint64_t waitend_us = MicroTime();
203 uint64_t waitdiff_us = waitend_us - waitstart_us;
204
205 // We should never get a timeout. If we do, it suggests a problem with the checkpoint
206 // code. Crash the process in this case.
207 CHECK_LT(waitdiff_us, kWaitTimeoutUs);
208
Dave Allison0aded082013-11-07 13:15:11 -0800209 // Update the current time.
210 now_us = MicroTime();
211 }
212
Wei Jin6a586912014-05-21 16:07:40 -0700213 if (valid_samples > 0) {
Dave Allison0aded082013-11-07 13:15:11 -0800214 // After the profile has been taken, write it out.
215 ScopedObjectAccess soa(self); // Acquire the mutator lock.
216 uint32_t size = profiler->WriteProfile();
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700217 VLOG(profiler) << "Profile size: " << size;
Dave Allison0aded082013-11-07 13:15:11 -0800218 }
219 }
220
221 LOG(INFO) << "Profiler shutdown";
222 runtime->DetachCurrentThread();
223 return nullptr;
224}
225
226// Write out the profile file if we are generating a profile.
227uint32_t BackgroundMethodSamplingProfiler::WriteProfile() {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100228 std::string full_name = output_filename_;
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700229 VLOG(profiler) << "Saving profile to " << full_name;
Dave Allison0aded082013-11-07 13:15:11 -0800230
Dave Allison39c3bfb2014-01-28 18:33:52 -0800231 int fd = open(full_name.c_str(), O_RDWR);
232 if (fd < 0) {
233 // Open failed.
234 LOG(ERROR) << "Failed to open profile file " << full_name;
Dave Allison0aded082013-11-07 13:15:11 -0800235 return 0;
236 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800237
238 // Lock the file for exclusive access. This will block if another process is using
239 // the file.
240 int err = flock(fd, LOCK_EX);
241 if (err < 0) {
242 LOG(ERROR) << "Failed to lock profile file " << full_name;
243 return 0;
244 }
245
246 // Read the previous profile.
247 profile_table_.ReadPrevious(fd);
248
249 // Move back to the start of the file.
250 lseek(fd, 0, SEEK_SET);
251
252 // Format the profile output and write to the file.
Dave Allison0aded082013-11-07 13:15:11 -0800253 std::ostringstream os;
254 uint32_t num_methods = DumpProfile(os);
255 std::string data(os.str());
Dave Allison39c3bfb2014-01-28 18:33:52 -0800256 const char *p = data.c_str();
257 size_t length = data.length();
258 size_t full_length = length;
259 do {
260 int n = ::write(fd, p, length);
261 p += n;
262 length -= n;
263 } while (length > 0);
264
265 // Truncate the file to the new length.
266 ftruncate(fd, full_length);
267
268 // Now unlock the file, allowing another process in.
269 err = flock(fd, LOCK_UN);
270 if (err < 0) {
271 LOG(ERROR) << "Failed to unlock profile file " << full_name;
272 }
273
274 // Done, close the file.
275 ::close(fd);
276
277 // Clean the profile for the next time.
278 CleanProfile();
279
Dave Allison0aded082013-11-07 13:15:11 -0800280 return num_methods;
281}
282
Calin Juravlec1b643c2014-05-30 23:44:11 +0100283bool BackgroundMethodSamplingProfiler::Start(
284 const std::string& output_filename, const ProfilerOptions& options) {
285 if (!options.IsEnabled()) {
286 LOG(INFO) << "Profiler disabled. To enable setprop dalvik.vm.profiler 1.";
287 return false;
288 }
289
290 CHECK(!output_filename.empty());
291
Dave Allison0aded082013-11-07 13:15:11 -0800292 Thread* self = Thread::Current();
293 {
294 MutexLock mu(self, *Locks::profiler_lock_);
295 // Don't start two profiler threads.
296 if (profiler_ != nullptr) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100297 return true;
Dave Allison0aded082013-11-07 13:15:11 -0800298 }
299 }
300
Calin Juravlec1b643c2014-05-30 23:44:11 +0100301 LOG(INFO) << "Starting profiler using output file: " << output_filename
302 << " and options: " << options;
Dave Allison0aded082013-11-07 13:15:11 -0800303 {
304 MutexLock mu(self, *Locks::profiler_lock_);
Calin Juravlec1b643c2014-05-30 23:44:11 +0100305 profiler_ = new BackgroundMethodSamplingProfiler(output_filename, options);
Dave Allison0aded082013-11-07 13:15:11 -0800306
307 CHECK_PTHREAD_CALL(pthread_create, (&profiler_pthread_, nullptr, &RunProfilerThread,
308 reinterpret_cast<void*>(profiler_)),
309 "Profiler thread");
310 }
Calin Juravlec1b643c2014-05-30 23:44:11 +0100311 return true;
Dave Allison0aded082013-11-07 13:15:11 -0800312}
313
314
315
316void BackgroundMethodSamplingProfiler::Stop() {
317 BackgroundMethodSamplingProfiler* profiler = nullptr;
318 pthread_t profiler_pthread = 0U;
319 {
320 MutexLock trace_mu(Thread::Current(), *Locks::profiler_lock_);
Wei Jin6a586912014-05-21 16:07:40 -0700321 CHECK(!shutting_down_);
Dave Allison0aded082013-11-07 13:15:11 -0800322 profiler = profiler_;
323 shutting_down_ = true;
324 profiler_pthread = profiler_pthread_;
325 }
326
327 // Now wake up the sampler thread if it sleeping.
328 {
329 MutexLock profile_mu(Thread::Current(), profiler->wait_lock_);
330 profiler->period_condition_.Signal(Thread::Current());
331 }
332 // Wait for the sample thread to stop.
333 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profiler thread shutdown");
334
335 {
336 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
337 profiler_ = nullptr;
338 }
339 delete profiler;
340}
341
342
343void BackgroundMethodSamplingProfiler::Shutdown() {
344 Stop();
345}
346
Calin Juravlec1b643c2014-05-30 23:44:11 +0100347BackgroundMethodSamplingProfiler::BackgroundMethodSamplingProfiler(
348 const std::string& output_filename, const ProfilerOptions& options)
349 : output_filename_(output_filename),
350 options_(options),
Dave Allison0aded082013-11-07 13:15:11 -0800351 wait_lock_("Profile wait lock"),
352 period_condition_("Profile condition", wait_lock_),
353 profile_table_(wait_lock_),
354 profiler_barrier_(new Barrier(0)) {
355 // Populate the filtered_methods set.
356 // This is empty right now, but to add a method, do this:
357 //
358 // filtered_methods_.insert("void java.lang.Object.wait(long, int)");
359}
360
361// A method has been hit, record its invocation in the method map.
362// The mutator_lock must be held (shared) when this is called.
363void BackgroundMethodSamplingProfiler::RecordMethod(mirror::ArtMethod* method) {
364 if (method == nullptr) {
365 profile_table_.NullMethod();
366 // Don't record a nullptr method.
367 return;
368 }
369
370 mirror::Class* cls = method->GetDeclaringClass();
371 if (cls != nullptr) {
372 if (cls->GetClassLoader() == nullptr) {
373 // Don't include things in the boot
374 profile_table_.BootMethod();
375 return;
376 }
377 }
378
379 bool is_filtered = false;
380
381 MethodHelper mh(method);
382 if (strcmp(mh.GetName(), "<clinit>") == 0) {
383 // always filter out class init
384 is_filtered = true;
385 }
386
387 // Filter out methods by name if there are any.
388 if (!is_filtered && filtered_methods_.size() > 0) {
389 std::string method_full_name = PrettyMethod(method);
390
391 // Don't include specific filtered methods.
392 is_filtered = filtered_methods_.count(method_full_name) != 0;
393 }
394
395 // Add to the profile table unless it is filtered out.
396 if (!is_filtered) {
397 profile_table_.Put(method);
398 }
399}
400
401// Clean out any recordings for the method traces.
402void BackgroundMethodSamplingProfiler::CleanProfile() {
403 profile_table_.Clear();
404}
405
406uint32_t BackgroundMethodSamplingProfiler::DumpProfile(std::ostream& os) {
407 return profile_table_.Write(os);
408}
409
410// Profile Table.
411// This holds a mapping of mirror::ArtMethod* to a count of how many times a sample
412// hit it at the top of the stack.
413ProfileSampleResults::ProfileSampleResults(Mutex& lock) : lock_(lock), num_samples_(0),
414 num_null_methods_(0),
415 num_boot_methods_(0) {
416 for (int i = 0; i < kHashSize; i++) {
417 table[i] = nullptr;
418 }
419}
420
421ProfileSampleResults::~ProfileSampleResults() {
422 for (int i = 0; i < kHashSize; i++) {
423 delete table[i];
424 }
425}
426
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100427// Add a method to the profile table. If it's the first time the method
Dave Allison0aded082013-11-07 13:15:11 -0800428// has been seen, add it with count=1, otherwise increment the count.
429void ProfileSampleResults::Put(mirror::ArtMethod* method) {
430 lock_.Lock(Thread::Current());
431 uint32_t index = Hash(method);
432 if (table[index] == nullptr) {
433 table[index] = new Map();
434 }
435 Map::iterator i = table[index]->find(method);
436 if (i == table[index]->end()) {
437 (*table[index])[method] = 1;
438 } else {
439 i->second++;
440 }
441 num_samples_++;
442 lock_.Unlock(Thread::Current());
443}
444
Dave Allison39c3bfb2014-01-28 18:33:52 -0800445// Write the profile table to the output stream. Also merge with the previous profile.
Dave Allison0aded082013-11-07 13:15:11 -0800446uint32_t ProfileSampleResults::Write(std::ostream &os) {
447 ScopedObjectAccess soa(Thread::Current());
Dave Allison39c3bfb2014-01-28 18:33:52 -0800448 num_samples_ += previous_num_samples_;
449 num_null_methods_ += previous_num_null_methods_;
450 num_boot_methods_ += previous_num_boot_methods_;
451
Calin Juravlec1b643c2014-05-30 23:44:11 +0100452 VLOG(profiler) << "Profile: "
453 << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_;
Dave Allison0aded082013-11-07 13:15:11 -0800454 os << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_ << "\n";
455 uint32_t num_methods = 0;
456 for (int i = 0 ; i < kHashSize; i++) {
457 Map *map = table[i];
458 if (map != nullptr) {
459 for (const auto &meth_iter : *map) {
Dave Allison39c3bfb2014-01-28 18:33:52 -0800460 mirror::ArtMethod *method = meth_iter.first;
461 std::string method_name = PrettyMethod(method);
462
463 MethodHelper mh(method);
464 const DexFile::CodeItem* codeitem = mh.GetCodeItem();
465 uint32_t method_size = 0;
466 if (codeitem != nullptr) {
467 method_size = codeitem->insns_size_in_code_units_;
468 }
469 uint32_t count = meth_iter.second;
470
471 // Merge this profile entry with one from a previous run (if present). Also
472 // remove the previous entry.
473 PreviousProfile::iterator pi = previous_.find(method_name);
474 if (pi != previous_.end()) {
475 count += pi->second.count_;
476 previous_.erase(pi);
477 }
478 os << StringPrintf("%s/%u/%u\n", method_name.c_str(), count, method_size);
479 ++num_methods;
480 }
Dave Allison0aded082013-11-07 13:15:11 -0800481 }
482 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800483
484 // Now we write out the remaining previous methods.
485 for (PreviousProfile::iterator pi = previous_.begin(); pi != previous_.end(); ++pi) {
486 os << StringPrintf("%s/%u/%u\n", pi->first.c_str(), pi->second.count_, pi->second.method_size_);
487 ++num_methods;
488 }
Dave Allison0aded082013-11-07 13:15:11 -0800489 return num_methods;
490}
491
492void ProfileSampleResults::Clear() {
493 num_samples_ = 0;
494 num_null_methods_ = 0;
495 num_boot_methods_ = 0;
496 for (int i = 0; i < kHashSize; i++) {
497 delete table[i];
498 table[i] = nullptr;
499 }
Dave Allison39c3bfb2014-01-28 18:33:52 -0800500 previous_.clear();
Dave Allison0aded082013-11-07 13:15:11 -0800501}
502
503uint32_t ProfileSampleResults::Hash(mirror::ArtMethod* method) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800504 return (PointerToLowMemUInt32(method) >> 3) % kHashSize;
Dave Allison0aded082013-11-07 13:15:11 -0800505}
506
Dave Allison39c3bfb2014-01-28 18:33:52 -0800507// Read a single line into the given string. Returns true if everything OK, false
508// on EOF or error.
509static bool ReadProfileLine(int fd, std::string& line) {
510 char buf[4];
511 line.clear();
512 while (true) {
513 int n = read(fd, buf, 1); // TODO: could speed this up but is it worth it?
514 if (n != 1) {
515 return false;
516 }
517 if (buf[0] == '\n') {
518 break;
519 }
520 line += buf[0];
521 }
522 return true;
523}
524
525void ProfileSampleResults::ReadPrevious(int fd) {
526 // Reset counters.
527 previous_num_samples_ = previous_num_null_methods_ = previous_num_boot_methods_ = 0;
528
529 std::string line;
530
531 // The first line contains summary information.
532 if (!ReadProfileLine(fd, line)) {
533 return;
534 }
535 std::vector<std::string> summary_info;
536 Split(line, '/', summary_info);
537 if (summary_info.size() != 3) {
538 // Bad summary info. It should be count/nullcount/bootcount
539 return;
540 }
541 previous_num_samples_ = atoi(summary_info[0].c_str());
542 previous_num_null_methods_ = atoi(summary_info[1].c_str());
543 previous_num_boot_methods_ = atoi(summary_info[2].c_str());
544
545 // Now read each line until the end of file. Each line consists of 3 fields separated by /
546 while (true) {
547 if (!ReadProfileLine(fd, line)) {
548 break;
549 }
550 std::vector<std::string> info;
551 Split(line, '/', info);
552 if (info.size() != 3) {
553 // Malformed.
554 break;
555 }
556 std::string methodname = info[0];
557 uint32_t count = atoi(info[1].c_str());
558 uint32_t size = atoi(info[2].c_str());
559 previous_[methodname] = PreviousValue(count, size);
560 }
561}
Dave Allison0aded082013-11-07 13:15:11 -0800562
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100563bool ProfileFile::LoadFile(const std::string& fileName) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300564 LOG(VERBOSE) << "reading profile file " << fileName;
565 struct stat st;
566 int err = stat(fileName.c_str(), &st);
567 if (err == -1) {
568 LOG(VERBOSE) << "not found";
569 return false;
570 }
571 if (st.st_size == 0) {
Dave Allison644789f2014-04-10 13:06:10 -0700572 return false; // Empty profiles are invalid.
Calin Juravle9dae5b42014-04-07 16:36:21 +0300573 }
574 std::ifstream in(fileName.c_str());
575 if (!in) {
576 LOG(VERBOSE) << "profile file " << fileName << " exists but can't be opened";
577 LOG(VERBOSE) << "file owner: " << st.st_uid << ":" << st.st_gid;
578 LOG(VERBOSE) << "me: " << getuid() << ":" << getgid();
579 LOG(VERBOSE) << "file permissions: " << std::oct << st.st_mode;
580 LOG(VERBOSE) << "errno: " << errno;
581 return false;
582 }
583 // The first line contains summary information.
584 std::string line;
585 std::getline(in, line);
586 if (in.eof()) {
587 return false;
588 }
589 std::vector<std::string> summary_info;
590 Split(line, '/', summary_info);
591 if (summary_info.size() != 3) {
Calin Juravle19477a82014-06-06 12:24:21 +0100592 // Bad summary info. It should be total/null/boot.
Calin Juravle9dae5b42014-04-07 16:36:21 +0300593 return false;
594 }
Calin Juravle19477a82014-06-06 12:24:21 +0100595 // This is the number of hits in all profiled methods (without nullptr or boot methods)
596 uint32_t total_count = atoi(summary_info[0].c_str());
Calin Juravle9dae5b42014-04-07 16:36:21 +0300597
598 // Now read each line until the end of file. Each line consists of 3 fields separated by '/'.
599 // Store the info in descending order given by the most used methods.
600 typedef std::set<std::pair<int, std::vector<std::string>>> ProfileSet;
601 ProfileSet countSet;
602 while (!in.eof()) {
603 std::getline(in, line);
604 if (in.eof()) {
605 break;
606 }
607 std::vector<std::string> info;
608 Split(line, '/', info);
609 if (info.size() != 3) {
610 // Malformed.
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100611 return false;
Calin Juravle9dae5b42014-04-07 16:36:21 +0300612 }
613 int count = atoi(info[1].c_str());
614 countSet.insert(std::make_pair(-count, info));
615 }
616
617 uint32_t curTotalCount = 0;
618 ProfileSet::iterator end = countSet.end();
619 const ProfileData* prevData = nullptr;
620 for (ProfileSet::iterator it = countSet.begin(); it != end ; it++) {
621 const std::string& methodname = it->second[0];
622 uint32_t count = -it->first;
623 uint32_t size = atoi(it->second[2].c_str());
624 double usedPercent = (count * 100.0) / total_count;
625
626 curTotalCount += count;
627 // Methods with the same count should be part of the same top K percentage bucket.
628 double topKPercentage = (prevData != nullptr) && (prevData->GetCount() == count)
629 ? prevData->GetTopKUsedPercentage()
630 : 100 * static_cast<double>(curTotalCount) / static_cast<double>(total_count);
631
632 // Add it to the profile map.
633 ProfileData curData = ProfileData(methodname, count, size, usedPercent, topKPercentage);
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100634 profile_map_[methodname] = curData;
Calin Juravle9dae5b42014-04-07 16:36:21 +0300635 prevData = &curData;
636 }
637 return true;
638}
639
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100640bool ProfileFile::GetProfileData(ProfileFile::ProfileData* data, const std::string& method_name) {
641 ProfileMap::iterator i = profile_map_.find(method_name);
642 if (i == profile_map_.end()) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300643 return false;
644 }
Calin Juravlebb0b53f2014-05-23 17:33:29 +0100645 *data = i->second;
646 return true;
647}
648
649bool ProfileFile::GetTopKSamples(std::set<std::string>& topKSamples, double topKPercentage) {
650 ProfileMap::iterator end = profile_map_.end();
651 for (ProfileMap::iterator it = profile_map_.begin(); it != end; it++) {
Calin Juravle9dae5b42014-04-07 16:36:21 +0300652 if (it->second.GetTopKUsedPercentage() < topKPercentage) {
653 topKSamples.insert(it->first);
654 }
655 }
656 return true;
657}
658
659} // namespace art