1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "profiler.h"
#include <sys/uio.h>
#include <sys/file.h>
#include "base/stl_util.h"
#include "base/unix_file/fd_file.h"
#include "class_linker.h"
#include "common_throws.h"
#include "debugger.h"
#include "dex_file-inl.h"
#include "instrumentation.h"
#include "mirror/art_method-inl.h"
#include "mirror/class-inl.h"
#include "mirror/dex_cache.h"
#include "mirror/object_array-inl.h"
#include "mirror/object-inl.h"
#include "object_utils.h"
#include "os.h"
#include "scoped_thread_state_change.h"
#include "ScopedLocalRef.h"
#include "thread.h"
#include "thread_list.h"
#ifdef HAVE_ANDROID_OS
#include "cutils/properties.h"
#endif
#if !defined(ART_USE_PORTABLE_COMPILER)
#include "entrypoints/quick/quick_entrypoints.h"
#endif
namespace art {
BackgroundMethodSamplingProfiler* BackgroundMethodSamplingProfiler::profiler_ = nullptr;
pthread_t BackgroundMethodSamplingProfiler::profiler_pthread_ = 0U;
volatile bool BackgroundMethodSamplingProfiler::shutting_down_ = false;
// TODO: this profiler runs regardless of the state of the machine. Maybe we should use the
// wakelock or something to modify the run characteristics. This can be done when we
// have some performance data after it's been used for a while.
// This is called from either a thread list traversal or from a checkpoint. Regardless
// of which caller, the mutator lock must be held.
static void GetSample(Thread* thread, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
BackgroundMethodSamplingProfiler* profiler =
reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
mirror::ArtMethod* method = thread->GetCurrentMethod(nullptr);
if (false && method == nullptr) {
LOG(INFO) << "No current method available";
std::ostringstream os;
thread->Dump(os);
std::string data(os.str());
LOG(INFO) << data;
}
profiler->RecordMethod(method);
}
// A closure that is called by the thread checkpoint code.
class SampleCheckpoint : public Closure {
public:
explicit SampleCheckpoint(BackgroundMethodSamplingProfiler* const profiler) :
profiler_(profiler) {}
virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Thread* self = Thread::Current();
if (thread == nullptr) {
LOG(ERROR) << "Checkpoint with nullptr thread";
return;
}
// Grab the mutator lock (shared access).
ScopedObjectAccess soa(self);
// Grab a sample.
GetSample(thread, this->profiler_);
// And finally tell the barrier that we're done.
this->profiler_->GetBarrier().Pass(self);
}
private:
BackgroundMethodSamplingProfiler* const profiler_;
};
bool BackgroundMethodSamplingProfiler::ShuttingDown(Thread* self) {
MutexLock mu(self, *Locks::profiler_lock_);
return shutting_down_;
}
void* BackgroundMethodSamplingProfiler::RunProfilerThread(void* arg) {
Runtime* runtime = Runtime::Current();
BackgroundMethodSamplingProfiler* profiler =
reinterpret_cast<BackgroundMethodSamplingProfiler*>(arg);
// Add a random delay for the first time run so that we don't hammer the CPU
// with all profiles running at the same time.
const int kRandomDelayMaxSecs = 30;
const double kMaxBackoffSecs = 24*60*60; // Max backoff time.
srand(MicroTime() * getpid());
int startup_delay = rand() % kRandomDelayMaxSecs; // random delay for startup.
CHECK(runtime->AttachCurrentThread("Profiler", true, runtime->GetSystemThreadGroup(),
!runtime->IsCompiler()));
Thread* self = Thread::Current();
while (true) {
if (ShuttingDown(self)) {
break;
}
{
// wait until we need to run another profile
uint64_t delay_secs = profiler->period_s_ * profiler->backoff_factor_;
// Add a startup delay to prevent all the profiles running at once.
delay_secs += startup_delay;
// Immediate startup for benchmarking?
if (profiler->start_immediately_ && startup_delay > 0) {
delay_secs = 0;
}
startup_delay = 0;
LOG(DEBUG) << "Delaying profile start for " << delay_secs << " secs";
MutexLock mu(self, profiler->wait_lock_);
profiler->period_condition_.TimedWait(self, delay_secs * 1000, 0);
// Expand the backoff by its coefficient, but don't go beyond the max.
double new_backoff = profiler->backoff_factor_ * profiler->backoff_coefficient_;
if (new_backoff < kMaxBackoffSecs) {
profiler->backoff_factor_ = new_backoff;
}
}
if (ShuttingDown(self)) {
break;
}
uint64_t start_us = MicroTime();
uint64_t end_us = start_us + profiler->duration_s_ * UINT64_C(1000000);
uint64_t now_us = start_us;
LOG(DEBUG) << "Starting profiling run now for " << PrettyDuration((end_us - start_us) * 1000);
SampleCheckpoint check_point(profiler);
size_t valid_samples = 0;
while (now_us < end_us) {
if (ShuttingDown(self)) {
break;
}
usleep(profiler->interval_us_); // Non-interruptible sleep.
ThreadList* thread_list = runtime->GetThreadList();
profiler->profiler_barrier_->Init(self, 0);
size_t barrier_count = thread_list->RunCheckpointOnRunnableThreads(&check_point);
// All threads are suspended, nothing to do.
if (barrier_count == 0) {
now_us = MicroTime();
continue;
}
valid_samples += barrier_count;
ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
// Wait for the barrier to be crossed by all runnable threads. This wait
// is done with a timeout so that we can detect problems with the checkpoint
// running code. We should never see this.
const uint32_t kWaitTimeoutMs = 10000;
const uint32_t kWaitTimeoutUs = kWaitTimeoutMs * 1000;
uint64_t waitstart_us = MicroTime();
// Wait for all threads to pass the barrier.
profiler->profiler_barrier_->Increment(self, barrier_count, kWaitTimeoutMs);
uint64_t waitend_us = MicroTime();
uint64_t waitdiff_us = waitend_us - waitstart_us;
// We should never get a timeout. If we do, it suggests a problem with the checkpoint
// code. Crash the process in this case.
CHECK_LT(waitdiff_us, kWaitTimeoutUs);
self->SetState(old_state);
// Update the current time.
now_us = MicroTime();
}
if (valid_samples > 0 && !ShuttingDown(self)) {
// After the profile has been taken, write it out.
ScopedObjectAccess soa(self); // Acquire the mutator lock.
uint32_t size = profiler->WriteProfile();
LOG(DEBUG) << "Profile size: " << size;
}
}
LOG(INFO) << "Profiler shutdown";
runtime->DetachCurrentThread();
return nullptr;
}
// Write out the profile file if we are generating a profile.
uint32_t BackgroundMethodSamplingProfiler::WriteProfile() {
std::string full_name = profile_file_name_;
LOG(DEBUG) << "Saving profile to " << full_name;
int fd = open(full_name.c_str(), O_RDWR);
if (fd < 0) {
// Open failed.
LOG(ERROR) << "Failed to open profile file " << full_name;
return 0;
}
// Lock the file for exclusive access. This will block if another process is using
// the file.
int err = flock(fd, LOCK_EX);
if (err < 0) {
LOG(ERROR) << "Failed to lock profile file " << full_name;
return 0;
}
// Read the previous profile.
profile_table_.ReadPrevious(fd);
// Move back to the start of the file.
lseek(fd, 0, SEEK_SET);
// Format the profile output and write to the file.
std::ostringstream os;
uint32_t num_methods = DumpProfile(os);
std::string data(os.str());
const char *p = data.c_str();
size_t length = data.length();
size_t full_length = length;
do {
int n = ::write(fd, p, length);
p += n;
length -= n;
} while (length > 0);
// Truncate the file to the new length.
ftruncate(fd, full_length);
// Now unlock the file, allowing another process in.
err = flock(fd, LOCK_UN);
if (err < 0) {
LOG(ERROR) << "Failed to unlock profile file " << full_name;
}
// Done, close the file.
::close(fd);
// Clean the profile for the next time.
CleanProfile();
return num_methods;
}
// Start a profile thread with the user-supplied arguments.
void BackgroundMethodSamplingProfiler::Start(int period, int duration,
const std::string& profile_file_name, const std::string& procName,
int interval_us,
double backoff_coefficient, bool startImmediately) {
Thread* self = Thread::Current();
{
MutexLock mu(self, *Locks::profiler_lock_);
// Don't start two profiler threads.
if (profiler_ != nullptr) {
return;
}
}
// Only on target...
#ifdef HAVE_ANDROID_OS
if (!startImmediately) {
// Switch off profiler if the dalvik.vm.profiler property has value 0.
char buf[PROP_VALUE_MAX];
property_get("dalvik.vm.profiler", buf, "0");
if (strcmp(buf, "0") == 0) {
LOG(INFO) << "Profiler disabled. To enable setprop dalvik.vm.profiler 1";
return;
}
}
#endif
LOG(INFO) << "Starting profile with period " << period << "s, duration " << duration <<
"s, interval " << interval_us << "us. Profile file " << profile_file_name;
{
MutexLock mu(self, *Locks::profiler_lock_);
profiler_ = new BackgroundMethodSamplingProfiler(period, duration, profile_file_name,
procName,
backoff_coefficient,
interval_us, startImmediately);
CHECK_PTHREAD_CALL(pthread_create, (&profiler_pthread_, nullptr, &RunProfilerThread,
reinterpret_cast<void*>(profiler_)),
"Profiler thread");
}
}
void BackgroundMethodSamplingProfiler::Stop() {
BackgroundMethodSamplingProfiler* profiler = nullptr;
pthread_t profiler_pthread = 0U;
{
MutexLock trace_mu(Thread::Current(), *Locks::profiler_lock_);
profiler = profiler_;
shutting_down_ = true;
profiler_pthread = profiler_pthread_;
}
// Now wake up the sampler thread if it sleeping.
{
MutexLock profile_mu(Thread::Current(), profiler->wait_lock_);
profiler->period_condition_.Signal(Thread::Current());
}
// Wait for the sample thread to stop.
CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profiler thread shutdown");
{
MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
profiler_ = nullptr;
}
delete profiler;
}
void BackgroundMethodSamplingProfiler::Shutdown() {
Stop();
}
BackgroundMethodSamplingProfiler::BackgroundMethodSamplingProfiler(int period, int duration,
const std::string& profile_file_name,
const std::string& process_name,
double backoff_coefficient, int interval_us, bool startImmediately)
: profile_file_name_(profile_file_name), process_name_(process_name),
period_s_(period), start_immediately_(startImmediately),
interval_us_(interval_us), backoff_factor_(1.0),
backoff_coefficient_(backoff_coefficient), duration_s_(duration),
wait_lock_("Profile wait lock"),
period_condition_("Profile condition", wait_lock_),
profile_table_(wait_lock_),
profiler_barrier_(new Barrier(0)) {
// Populate the filtered_methods set.
// This is empty right now, but to add a method, do this:
//
// filtered_methods_.insert("void java.lang.Object.wait(long, int)");
}
// A method has been hit, record its invocation in the method map.
// The mutator_lock must be held (shared) when this is called.
void BackgroundMethodSamplingProfiler::RecordMethod(mirror::ArtMethod* method) {
if (method == nullptr) {
profile_table_.NullMethod();
// Don't record a nullptr method.
return;
}
mirror::Class* cls = method->GetDeclaringClass();
if (cls != nullptr) {
if (cls->GetClassLoader() == nullptr) {
// Don't include things in the boot
profile_table_.BootMethod();
return;
}
}
bool is_filtered = false;
MethodHelper mh(method);
if (strcmp(mh.GetName(), "<clinit>") == 0) {
// always filter out class init
is_filtered = true;
}
// Filter out methods by name if there are any.
if (!is_filtered && filtered_methods_.size() > 0) {
std::string method_full_name = PrettyMethod(method);
// Don't include specific filtered methods.
is_filtered = filtered_methods_.count(method_full_name) != 0;
}
// Add to the profile table unless it is filtered out.
if (!is_filtered) {
profile_table_.Put(method);
}
}
// Clean out any recordings for the method traces.
void BackgroundMethodSamplingProfiler::CleanProfile() {
profile_table_.Clear();
}
uint32_t BackgroundMethodSamplingProfiler::DumpProfile(std::ostream& os) {
return profile_table_.Write(os);
}
// Profile Table.
// This holds a mapping of mirror::ArtMethod* to a count of how many times a sample
// hit it at the top of the stack.
ProfileSampleResults::ProfileSampleResults(Mutex& lock) : lock_(lock), num_samples_(0),
num_null_methods_(0),
num_boot_methods_(0) {
for (int i = 0; i < kHashSize; i++) {
table[i] = nullptr;
}
}
ProfileSampleResults::~ProfileSampleResults() {
for (int i = 0; i < kHashSize; i++) {
delete table[i];
}
}
// Add a method to the profile table. If it the first time the method
// has been seen, add it with count=1, otherwise increment the count.
void ProfileSampleResults::Put(mirror::ArtMethod* method) {
lock_.Lock(Thread::Current());
uint32_t index = Hash(method);
if (table[index] == nullptr) {
table[index] = new Map();
}
Map::iterator i = table[index]->find(method);
if (i == table[index]->end()) {
(*table[index])[method] = 1;
} else {
i->second++;
}
num_samples_++;
lock_.Unlock(Thread::Current());
}
// Write the profile table to the output stream. Also merge with the previous profile.
uint32_t ProfileSampleResults::Write(std::ostream &os) {
ScopedObjectAccess soa(Thread::Current());
num_samples_ += previous_num_samples_;
num_null_methods_ += previous_num_null_methods_;
num_boot_methods_ += previous_num_boot_methods_;
LOG(DEBUG) << "Profile: " << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_;
os << num_samples_ << "/" << num_null_methods_ << "/" << num_boot_methods_ << "\n";
uint32_t num_methods = 0;
for (int i = 0 ; i < kHashSize; i++) {
Map *map = table[i];
if (map != nullptr) {
for (const auto &meth_iter : *map) {
mirror::ArtMethod *method = meth_iter.first;
std::string method_name = PrettyMethod(method);
MethodHelper mh(method);
const DexFile::CodeItem* codeitem = mh.GetCodeItem();
uint32_t method_size = 0;
if (codeitem != nullptr) {
method_size = codeitem->insns_size_in_code_units_;
}
uint32_t count = meth_iter.second;
// Merge this profile entry with one from a previous run (if present). Also
// remove the previous entry.
PreviousProfile::iterator pi = previous_.find(method_name);
if (pi != previous_.end()) {
count += pi->second.count_;
previous_.erase(pi);
}
os << StringPrintf("%s/%u/%u\n", method_name.c_str(), count, method_size);
++num_methods;
}
}
}
// Now we write out the remaining previous methods.
for (PreviousProfile::iterator pi = previous_.begin(); pi != previous_.end(); ++pi) {
os << StringPrintf("%s/%u/%u\n", pi->first.c_str(), pi->second.count_, pi->second.method_size_);
++num_methods;
}
return num_methods;
}
void ProfileSampleResults::Clear() {
num_samples_ = 0;
num_null_methods_ = 0;
num_boot_methods_ = 0;
for (int i = 0; i < kHashSize; i++) {
delete table[i];
table[i] = nullptr;
}
previous_.clear();
}
uint32_t ProfileSampleResults::Hash(mirror::ArtMethod* method) {
return (PointerToLowMemUInt32(method) >> 3) % kHashSize;
}
// Read a single line into the given string. Returns true if everything OK, false
// on EOF or error.
static bool ReadProfileLine(int fd, std::string& line) {
char buf[4];
line.clear();
while (true) {
int n = read(fd, buf, 1); // TODO: could speed this up but is it worth it?
if (n != 1) {
return false;
}
if (buf[0] == '\n') {
break;
}
line += buf[0];
}
return true;
}
void ProfileSampleResults::ReadPrevious(int fd) {
// Reset counters.
previous_num_samples_ = previous_num_null_methods_ = previous_num_boot_methods_ = 0;
std::string line;
// The first line contains summary information.
if (!ReadProfileLine(fd, line)) {
return;
}
std::vector<std::string> summary_info;
Split(line, '/', summary_info);
if (summary_info.size() != 3) {
// Bad summary info. It should be count/nullcount/bootcount
return;
}
previous_num_samples_ = atoi(summary_info[0].c_str());
previous_num_null_methods_ = atoi(summary_info[1].c_str());
previous_num_boot_methods_ = atoi(summary_info[2].c_str());
// Now read each line until the end of file. Each line consists of 3 fields separated by /
while (true) {
if (!ReadProfileLine(fd, line)) {
break;
}
std::vector<std::string> info;
Split(line, '/', info);
if (info.size() != 3) {
// Malformed.
break;
}
std::string methodname = info[0];
uint32_t count = atoi(info[1].c_str());
uint32_t size = atoi(info[2].c_str());
previous_[methodname] = PreviousValue(count, size);
}
}
} // namespace art
|