blob: 841ace5cb0fa966e2c9d2282f31d4e3b4f4fb0fd [file] [log] [blame]
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001/*
2 * Copyright (C) 2015 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 "profile_saver.h"
18
Calin Juravle86a9ebe2016-02-24 10:13:09 +000019#include <fcntl.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070020#include <sys/resource.h>
21#include <sys/stat.h>
22#include <sys/types.h>
Calin Juravle86a9ebe2016-02-24 10:13:09 +000023
Andreas Gampe9186ced2016-12-12 14:28:21 -080024#include "android-base/strings.h"
25
Calin Juravle4d77b6a2015-12-01 18:38:09 +000026#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070027#include "base/enums.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080028#include "base/logging.h" // For VLOG.
Mathieu Chartierfaf83202017-06-08 10:35:20 -070029#include "base/scoped_arena_containers.h"
Andreas Gampe5678db52017-06-08 14:11:18 -070030#include "base/stl_util.h"
Mathieu Chartierdabdc0f2016-03-04 14:58:03 -080031#include "base/systrace.h"
Calin Juravle6044fa72016-03-25 17:17:09 +000032#include "base/time_utils.h"
Mathieu Chartier06bed302017-07-13 13:23:18 -070033#include "class_table-inl.h"
Calin Juravle6044fa72016-03-25 17:17:09 +000034#include "compiler_filter.h"
David Sehr9e734c72018-01-04 17:56:19 -080035#include "dex/dex_file_loader.h"
Mathieu Chartierfaf83202017-06-08 10:35:20 -070036#include "dex_reference_collection.h"
Mathieu Chartier39100372017-05-17 13:14:10 -070037#include "gc/collector_type.h"
38#include "gc/gc_cause.h"
39#include "gc/scoped_gc_critical_section.h"
David Sehr82d046e2018-04-23 08:14:19 -070040#include "jit/profiling_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000041#include "oat_file_manager.h"
David Sehr82d046e2018-04-23 08:14:19 -070042#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Calin Juravle6044fa72016-03-25 17:17:09 +000044
Calin Juravle4d77b6a2015-12-01 18:38:09 +000045namespace art {
46
Calin Juravle4d77b6a2015-12-01 18:38:09 +000047ProfileSaver* ProfileSaver::instance_ = nullptr;
48pthread_t ProfileSaver::profiler_pthread_ = 0U;
49
David Sehr82d046e2018-04-23 08:14:19 -070050static_assert(ProfileCompilationInfo::kIndividualInlineCacheSize ==
51 InlineCache::kIndividualCacheSize,
52 "InlineCache and ProfileCompilationInfo do not agree on kIndividualCacheSize");
53
Mathieu Chartier5494e5b2017-06-26 14:13:27 -070054// At what priority to schedule the saver threads. 9 is the lowest foreground priority on device.
55static constexpr int kProfileSaverPthreadPriority = 9;
56
57static void SetProfileSaverThreadPriority(pthread_t thread, int priority) {
58#if defined(ART_TARGET_ANDROID)
59 int result = setpriority(PRIO_PROCESS, pthread_gettid_np(thread), priority);
60 if (result != 0) {
61 LOG(ERROR) << "Failed to setpriority to :" << priority;
62 }
63#else
64 UNUSED(thread);
65 UNUSED(priority);
66#endif
67}
68
69static int GetDefaultThreadPriority() {
70#if defined(ART_TARGET_ANDROID)
71 pthread_attr_t attr;
72 sched_param param;
73 pthread_attr_init(&attr);
74 pthread_attr_getschedparam(&attr, &param);
75 return param.sched_priority;
76#else
77 return 0;
78#endif
79}
80
Calin Juravle138dbff2016-06-28 19:36:58 +010081ProfileSaver::ProfileSaver(const ProfileSaverOptions& options,
82 const std::string& output_filename,
Calin Juravle4d77b6a2015-12-01 18:38:09 +000083 jit::JitCodeCache* jit_code_cache,
Calin Juravle77651c42017-03-03 18:04:02 -080084 const std::vector<std::string>& code_paths)
Calin Juravleb4eddd22016-01-13 15:52:33 -080085 : jit_code_cache_(jit_code_cache),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000086 shutting_down_(false),
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010087 last_time_ns_saver_woke_up_(0),
88 jit_activity_notifications_(0),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000089 wait_lock_("ProfileSaver wait lock"),
Calin Juravlec19c1c22016-03-09 15:37:48 +000090 period_condition_("ProfileSaver period condition", wait_lock_),
91 total_bytes_written_(0),
92 total_number_of_writes_(0),
93 total_number_of_code_cache_queries_(0),
94 total_number_of_skipped_writes_(0),
95 total_number_of_failed_writes_(0),
Calin Juravle85f7bf32016-03-18 16:23:40 +000096 total_ms_of_sleep_(0),
Calin Juravlec19c1c22016-03-09 15:37:48 +000097 total_ns_of_work_(0),
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010098 max_number_of_profile_entries_cached_(0),
99 total_number_of_hot_spikes_(0),
Calin Juravle138dbff2016-06-28 19:36:58 +0100100 total_number_of_wake_ups_(0),
101 options_(options) {
102 DCHECK(options_.IsEnabled());
Calin Juravle77651c42017-03-03 18:04:02 -0800103 AddTrackedLocations(output_filename, code_paths);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000104}
105
Calin Juravlecc3171a2017-05-19 16:47:53 -0700106ProfileSaver::~ProfileSaver() {
107 for (auto& it : profile_cache_) {
108 delete it.second;
109 }
110}
111
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000112void ProfileSaver::Run() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000113 Thread* self = Thread::Current();
114
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100115 // Fetch the resolved classes for the app images after sleeping for
Calin Juravle138dbff2016-06-28 19:36:58 +0100116 // options_.GetSaveResolvedClassesDelayMs().
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100117 // TODO(calin) This only considers the case of the primary profile file.
118 // Anything that gets loaded in the same VM will not have their resolved
119 // classes save (unless they started before the initial saving was done).
120 {
121 MutexLock mu(self, wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +0100122 const uint64_t end_time = NanoTime() + MsToNs(options_.GetSaveResolvedClassesDelayMs());
Mathieu Chartier0ec065d2016-05-18 19:51:23 -0700123 while (true) {
124 const uint64_t current_time = NanoTime();
125 if (current_time >= end_time) {
126 break;
127 }
128 period_condition_.TimedWait(self, NsToMs(end_time - current_time), 0);
129 }
Calin Juravle138dbff2016-06-28 19:36:58 +0100130 total_ms_of_sleep_ += options_.GetSaveResolvedClassesDelayMs();
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100131 }
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700132 FetchAndCacheResolvedClassesAndMethods(/*startup=*/ true);
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100133
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700134
135 // When we save without waiting for JIT notifications we use a simple
136 // exponential back off policy bounded by max_wait_without_jit.
137 uint32_t max_wait_without_jit = options_.GetMinSavePeriodMs() * 16;
138 uint64_t cur_wait_without_jit = options_.GetMinSavePeriodMs();
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100139 // Loop for the profiled methods.
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800140 while (!ShuttingDown(self)) {
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100141 uint64_t sleep_start = NanoTime();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000142 {
Calin Juravle0233a412016-05-18 15:49:36 -0700143 uint64_t sleep_time = 0;
144 {
145 MutexLock mu(self, wait_lock_);
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700146 if (options_.GetWaitForJitNotificationsToSave()) {
147 period_condition_.Wait(self);
148 } else {
149 period_condition_.TimedWait(self, cur_wait_without_jit, 0);
150 if (cur_wait_without_jit < max_wait_without_jit) {
151 cur_wait_without_jit *= 2;
152 }
153 }
Calin Juravledc85bd72016-05-25 18:09:53 +0100154 sleep_time = NanoTime() - sleep_start;
Calin Juravle0233a412016-05-18 15:49:36 -0700155 }
156 // Check if the thread was woken up for shutdown.
157 if (ShuttingDown(self)) {
158 break;
159 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100160 total_number_of_wake_ups_++;
161 // We might have been woken up by a huge number of notifications to guarantee saving.
162 // If we didn't meet the minimum saving period go back to sleep (only if missed by
163 // a reasonable margin).
Calin Juravle138dbff2016-06-28 19:36:58 +0100164 uint64_t min_save_period_ns = MsToNs(options_.GetMinSavePeriodMs());
165 while (min_save_period_ns * 0.9 > sleep_time) {
Calin Juravle0233a412016-05-18 15:49:36 -0700166 {
167 MutexLock mu(self, wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +0100168 period_condition_.TimedWait(self, NsToMs(min_save_period_ns - sleep_time), 0);
Calin Juravledc85bd72016-05-25 18:09:53 +0100169 sleep_time = NanoTime() - sleep_start;
Calin Juravle0233a412016-05-18 15:49:36 -0700170 }
171 // Check if the thread was woken up for shutdown.
172 if (ShuttingDown(self)) {
173 break;
174 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100175 total_number_of_wake_ups_++;
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100176 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000177 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100178 total_ms_of_sleep_ += NsToMs(NanoTime() - sleep_start);
179
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000180 if (ShuttingDown(self)) {
181 break;
182 }
183
Calin Juravlea345d312017-03-14 18:45:55 -0700184 uint16_t number_of_new_methods = 0;
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100185 uint64_t start_work = NanoTime();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700186 bool profile_saved_to_disk = ProcessProfilingInfo(/*force_save=*/false, &number_of_new_methods);
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100187 // Update the notification counter based on result. Note that there might be contention on this
188 // but we don't care about to be 100% precise.
189 if (!profile_saved_to_disk) {
190 // If we didn't save to disk it may be because we didn't have enough new methods.
Calin Juravlea345d312017-03-14 18:45:55 -0700191 // Set the jit activity notifications to number_of_new_methods so we can wake up earlier
192 // if needed.
193 jit_activity_notifications_ = number_of_new_methods;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000194 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100195 total_ns_of_work_ += NanoTime() - start_work;
196 }
197}
Calin Juravlec19c1c22016-03-09 15:37:48 +0000198
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100199void ProfileSaver::NotifyJitActivity() {
200 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
201 if (instance_ == nullptr || instance_->shutting_down_) {
202 return;
203 }
204 instance_->NotifyJitActivityInternal();
205}
206
207void ProfileSaver::WakeUpSaver() {
208 jit_activity_notifications_ = 0;
209 last_time_ns_saver_woke_up_ = NanoTime();
210 period_condition_.Signal(Thread::Current());
211}
212
213void ProfileSaver::NotifyJitActivityInternal() {
214 // Unlikely to overflow but if it happens,
215 // we would have waken up the saver long before that.
216 jit_activity_notifications_++;
217 // Note that we are not as precise as we could be here but we don't want to wake the saver
218 // every time we see a hot method.
Calin Juravle138dbff2016-06-28 19:36:58 +0100219 if (jit_activity_notifications_ > options_.GetMinNotificationBeforeWake()) {
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100220 MutexLock wait_mutex(Thread::Current(), wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +0100221 if ((NanoTime() - last_time_ns_saver_woke_up_) > MsToNs(options_.GetMinSavePeriodMs())) {
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100222 WakeUpSaver();
Serguei Katkov87de9cf2016-08-01 17:47:04 +0700223 } else if (jit_activity_notifications_ > options_.GetMaxNotificationBeforeWake()) {
224 // Make sure to wake up the saver if we see a spike in the number of notifications.
225 // This is a precaution to avoid losing a big number of methods in case
226 // this is a spike with no jit after.
227 total_number_of_hot_spikes_++;
228 WakeUpSaver();
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100229 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000230 }
231}
232
Mathieu Chartier5494e5b2017-06-26 14:13:27 -0700233class ScopedDefaultPriority {
234 public:
235 explicit ScopedDefaultPriority(pthread_t thread) : thread_(thread) {
236 SetProfileSaverThreadPriority(thread_, GetDefaultThreadPriority());
237 }
238
239 ~ScopedDefaultPriority() {
240 SetProfileSaverThreadPriority(thread_, kProfileSaverPthreadPriority);
241 }
242
243 private:
244 const pthread_t thread_;
245};
246
Mathieu Chartier06bed302017-07-13 13:23:18 -0700247// GetClassLoadersVisitor takes a snapshot of the class loaders and stores them in the out
248// class_loaders argument. Not affected by class unloading since there are no suspend points in
249// the caller.
250class GetClassLoadersVisitor : public ClassLoaderVisitor {
251 public:
252 explicit GetClassLoadersVisitor(VariableSizedHandleScope* hs,
253 std::vector<Handle<mirror::ClassLoader>>* class_loaders)
254 : hs_(hs),
255 class_loaders_(class_loaders) {}
256
257 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100258 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier06bed302017-07-13 13:23:18 -0700259 class_loaders_->push_back(hs_->NewHandle(class_loader));
260 }
261
262 private:
263 VariableSizedHandleScope* const hs_;
264 std::vector<Handle<mirror::ClassLoader>>* const class_loaders_;
265};
266
267// GetClassesVisitor takes a snapshot of the loaded classes that we may want to visit and stores
268// them in the out argument. Not affected by class unloading since there are no suspend points in
269// the caller.
270class GetClassesVisitor : public ClassVisitor {
271 public:
272 explicit GetClassesVisitor(bool profile_boot_class_path,
273 ScopedArenaVector<ObjPtr<mirror::Class>>* out)
274 : profile_boot_class_path_(profile_boot_class_path),
275 out_(out) {}
276
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700277 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier06bed302017-07-13 13:23:18 -0700278 if (klass->IsProxyClass() ||
279 klass->IsArrayClass() ||
280 klass->IsPrimitive() ||
281 !klass->IsResolved() ||
282 klass->IsErroneousResolved() ||
283 (!profile_boot_class_path_ && klass->GetClassLoader() == nullptr)) {
284 return true;
285 }
286 out_->push_back(klass);
287 return true;
288 }
289
290 private:
291 const bool profile_boot_class_path_;
292 ScopedArenaVector<ObjPtr<mirror::Class>>* const out_;
293};
294
295using MethodReferenceCollection = DexReferenceCollection<uint16_t, ScopedArenaAllocatorAdapter>;
296using TypeReferenceCollection = DexReferenceCollection<dex::TypeIndex,
297 ScopedArenaAllocatorAdapter>;
298
299// Iterate over all of the loaded classes and visit each one. For each class, add it to the
300// resolved_classes out argument if startup is true.
301// Add methods to the hot_methods out argument if the number of samples is greater or equal to
302// hot_method_sample_threshold, add it to sampled_methods if it has at least one sample.
303static void SampleClassesAndExecutedMethods(pthread_t profiler_pthread,
304 bool profile_boot_class_path,
305 ScopedArenaAllocator* allocator,
306 uint32_t hot_method_sample_threshold,
307 bool startup,
308 TypeReferenceCollection* resolved_classes,
309 MethodReferenceCollection* hot_methods,
310 MethodReferenceCollection* sampled_methods) {
311 Thread* const self = Thread::Current();
312 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
313 // Restore profile saver thread priority during the GC critical section. This helps prevent
314 // priority inversions blocking the GC for long periods of time.
315 std::unique_ptr<ScopedDefaultPriority> sdp;
316 // Only restore default priority if we are the profile saver thread. Other threads that call this
317 // are threads calling Stop and the signal catcher (for SIGUSR1).
318 if (pthread_self() == profiler_pthread) {
319 sdp.reset(new ScopedDefaultPriority(profiler_pthread));
320 }
321
322 // Do ScopedGCCriticalSection before acquiring mutator lock to prevent the GC running and
323 // blocking threads during thread root flipping. Since the GC is a background thread, blocking it
324 // is not a problem.
325 ScopedObjectAccess soa(self);
326 gc::ScopedGCCriticalSection sgcs(self,
327 gc::kGcCauseProfileSaver,
328 gc::kCollectorTypeCriticalSection);
329 VariableSizedHandleScope hs(soa.Self());
330 std::vector<Handle<mirror::ClassLoader>> class_loaders;
331 if (profile_boot_class_path) {
332 // First add the boot class loader since visit classloaders doesn't visit it.
333 class_loaders.push_back(hs.NewHandle<mirror::ClassLoader>(nullptr));
334 }
335 GetClassLoadersVisitor class_loader_visitor(&hs, &class_loaders);
336 {
337 // Read the class loaders into a temporary array to prevent contention problems on the
338 // class_linker_classes_lock.
339 ScopedTrace trace2("Get class loaders");
340 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
341 class_linker->VisitClassLoaders(&class_loader_visitor);
342 }
343 ScopedArenaVector<ObjPtr<mirror::Class>> classes(allocator->Adapter());
344 for (Handle<mirror::ClassLoader> class_loader : class_loaders) {
345 ClassTable* table = class_linker->ClassTableForClassLoader(class_loader.Get());
346 if (table == nullptr) {
347 // If the class loader has not loaded any classes, it may have a null table.
348 continue;
349 }
350 GetClassesVisitor get_classes_visitor(profile_boot_class_path, &classes);
351 {
352 // Collect the classes into a temporary array to prevent lock contention on the class
353 // table lock. We want to avoid blocking class loading in other threads as much as
354 // possible.
355 ScopedTrace trace3("Visiting class table");
356 table->Visit(get_classes_visitor);
357 }
358 for (ObjPtr<mirror::Class> klass : classes) {
359 if (startup) {
360 // We only record classes for the startup case. This may change in the future.
361 resolved_classes->AddReference(&klass->GetDexFile(), klass->GetDexTypeIndex());
362 }
363 // Visit all of the methods in the class to see which ones were executed.
364 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
David Srbeckye36e7f22018-11-14 14:21:23 +0000365 if (!method.IsNative() && !method.IsAbstract()) {
Mathieu Chartier06bed302017-07-13 13:23:18 -0700366 DCHECK(!method.IsProxyMethod());
367 const uint16_t counter = method.GetCounter();
368 // Mark startup methods as hot if they have more than hot_method_sample_threshold
369 // samples. This means they will get compiled by the compiler driver.
370 if (method.GetProfilingInfo(kRuntimePointerSize) != nullptr ||
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100371 method.PreviouslyWarm() ||
Mathieu Chartier06bed302017-07-13 13:23:18 -0700372 counter >= hot_method_sample_threshold) {
373 hot_methods->AddReference(method.GetDexFile(), method.GetDexMethodIndex());
374 } else if (counter != 0) {
375 sampled_methods->AddReference(method.GetDexFile(), method.GetDexMethodIndex());
376 }
377 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000378 // We do not record native methods. Once we AOT-compile the app, all native
379 // methods shall have their thunks compiled.
Mathieu Chartier06bed302017-07-13 13:23:18 -0700380 }
381 }
382 }
383 classes.clear();
384 }
385}
386
387void ProfileSaver::FetchAndCacheResolvedClassesAndMethods(bool startup) {
Calin Juravle85f7bf32016-03-18 16:23:40 +0000388 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700389 const uint64_t start_time = NanoTime();
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700390
391 // Resolve any new registered locations.
392 ResolveTrackedLocations();
393
Mathieu Chartier39100372017-05-17 13:14:10 -0700394 Thread* const self = Thread::Current();
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700395 Runtime* const runtime = Runtime::Current();
396 ArenaStack stack(runtime->GetArenaPool());
397 ScopedArenaAllocator allocator(&stack);
398 MethodReferenceCollection hot_methods(allocator.Adapter(), allocator.Adapter());
Mathieu Chartier06bed302017-07-13 13:23:18 -0700399 MethodReferenceCollection sampled_methods(allocator.Adapter(), allocator.Adapter());
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700400 TypeReferenceCollection resolved_classes(allocator.Adapter(), allocator.Adapter());
Mathieu Chartier273d1102017-06-06 17:07:13 -0700401 const bool is_low_ram = Runtime::Current()->GetHeap()->IsLowMemoryMode();
Mathieu Chartier5494e5b2017-06-26 14:13:27 -0700402 pthread_t profiler_pthread;
Mathieu Chartierc600eaa2016-05-18 08:51:52 -0700403 {
Mathieu Chartier5494e5b2017-06-26 14:13:27 -0700404 MutexLock mu(self, *Locks::profiler_lock_);
405 profiler_pthread = profiler_pthread_;
406 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700407 const uint32_t hot_method_sample_threshold = startup ?
408 options_.GetHotStartupMethodSamples(is_low_ram) :
409 std::numeric_limits<uint32_t>::max();
410 SampleClassesAndExecutedMethods(profiler_pthread,
411 options_.GetProfileBootClassPath(),
412 &allocator,
413 hot_method_sample_threshold,
414 startup,
415 &resolved_classes,
416 &hot_methods,
417 &sampled_methods);
Mathieu Chartier39100372017-05-17 13:14:10 -0700418 MutexLock mu(self, *Locks::profiler_lock_);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000419 uint64_t total_number_of_profile_entries_cached = 0;
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700420 using Hotness = ProfileCompilationInfo::MethodHotness;
Mathieu Chartier9275af62016-04-29 12:03:56 -0700421
Calin Juravle85f7bf32016-03-18 16:23:40 +0000422 for (const auto& it : tracked_dex_base_locations_) {
Mathieu Chartier9275af62016-04-29 12:03:56 -0700423 std::set<DexCacheResolvedClasses> resolved_classes_for_location;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000424 const std::string& filename = it.first;
Mathieu Chartier06bed302017-07-13 13:23:18 -0700425 auto info_it = profile_cache_.find(filename);
426 if (info_it == profile_cache_.end()) {
427 info_it = profile_cache_.Put(
428 filename,
429 new ProfileCompilationInfo(Runtime::Current()->GetArenaPool()));
430 }
Calin Juravlecc3171a2017-05-19 16:47:53 -0700431 ProfileCompilationInfo* cached_info = info_it->second;
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700432
433 const std::set<std::string>& locations = it.second;
Mathieu Chartier1a074352019-01-04 15:08:29 -0800434 VLOG(profiler) << "Locations for " << it.first << " " << android::base::Join(locations, ':');
435
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700436 for (const auto& pair : hot_methods.GetMap()) {
437 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700438 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
Mathieu Chartier1a074352019-01-04 15:08:29 -0800439 const MethodReferenceCollection::IndexVector& indices = pair.second;
440 VLOG(profiler) << "Location " << dex_file->GetLocation()
441 << " found=" << (locations.find(base_location) != locations.end())
442 << " indices size=" << indices.size();
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700443 if (locations.find(base_location) != locations.end()) {
Mathieu Chartier06bed302017-07-13 13:23:18 -0700444 uint8_t flags = Hotness::kFlagHot;
445 flags |= startup ? Hotness::kFlagStartup : Hotness::kFlagPostStartup;
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700446 cached_info->AddMethodsForDex(
Mathieu Chartier06bed302017-07-13 13:23:18 -0700447 static_cast<Hotness::Flag>(flags),
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700448 dex_file,
449 indices.begin(),
450 indices.end());
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700451 }
452 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700453 for (const auto& pair : sampled_methods.GetMap()) {
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700454 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700455 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
Mathieu Chartier1a074352019-01-04 15:08:29 -0800456 const MethodReferenceCollection::IndexVector& indices = pair.second;
457 VLOG(profiler) << "Location " << base_location
458 << " found=" << (locations.find(base_location) != locations.end())
459 << " indices size=" << indices.size();
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700460 if (locations.find(base_location) != locations.end()) {
Mathieu Chartier06bed302017-07-13 13:23:18 -0700461 cached_info->AddMethodsForDex(startup ? Hotness::kFlagStartup : Hotness::kFlagPostStartup,
Mathieu Chartierdb40eac2017-06-09 18:34:11 -0700462 dex_file,
463 indices.begin(),
464 indices.end());
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700465 }
466 }
467 for (const auto& pair : resolved_classes.GetMap()) {
468 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700469 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
470 if (locations.find(base_location) != locations.end()) {
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700471 const TypeReferenceCollection::IndexVector& classes = pair.second;
472 VLOG(profiler) << "Added " << classes.size() << " classes for location "
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700473 << base_location
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700474 << " (" << dex_file->GetLocation() << ")";
475 cached_info->AddClassesForDex(dex_file, classes.begin(), classes.end());
476 } else {
Mathieu Chartier1a074352019-01-04 15:08:29 -0800477 VLOG(profiler) << "Location not found " << base_location;
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700478 }
479 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000480 total_number_of_profile_entries_cached += resolved_classes_for_location.size();
481 }
482 max_number_of_profile_entries_cached_ = std::max(
483 max_number_of_profile_entries_cached_,
484 total_number_of_profile_entries_cached);
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700485 VLOG(profiler) << "Profile saver recorded " << hot_methods.NumReferences() << " hot methods and "
Mathieu Chartier06bed302017-07-13 13:23:18 -0700486 << sampled_methods.NumReferences() << " sampled methods with threshold "
487 << hot_method_sample_threshold << " in "
488 << PrettyDuration(NanoTime() - start_time);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000489}
490
Calin Juravlea345d312017-03-14 18:45:55 -0700491bool ProfileSaver::ProcessProfilingInfo(bool force_save, /*out*/uint16_t* number_of_new_methods) {
Calin Juravle85f7bf32016-03-18 16:23:40 +0000492 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700493
494 // Resolve any new registered locations.
495 ResolveTrackedLocations();
496
Calin Juravleb4eddd22016-01-13 15:52:33 -0800497 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000498 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800499 // Make a copy so that we don't hold the lock while doing I/O.
500 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
501 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000502 }
Calin Juravlec15e5662016-03-17 17:07:52 +0000503
Calin Juravle85f7bf32016-03-18 16:23:40 +0000504 bool profile_file_saved = false;
Calin Juravlea345d312017-03-14 18:45:55 -0700505 if (number_of_new_methods != nullptr) {
506 *number_of_new_methods = 0;
507 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100508
Mathieu Chartier06bed302017-07-13 13:23:18 -0700509 // We only need to do this once, not once per dex location.
510 // TODO: Figure out a way to only do it when stuff has changed? It takes 30-50ms.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700511 FetchAndCacheResolvedClassesAndMethods(/*startup=*/ false);
Mathieu Chartier06bed302017-07-13 13:23:18 -0700512
Calin Juravleb4eddd22016-01-13 15:52:33 -0800513 for (const auto& it : tracked_locations) {
Calin Juravlea345d312017-03-14 18:45:55 -0700514 if (!force_save && ShuttingDown(Thread::Current())) {
515 // The ProfileSaver is in shutdown mode, meaning a stop request was made and
516 // we need to exit cleanly (by waiting for the saver thread to finish). Unless
517 // we have a request for a forced save, do not do any processing so that we
518 // speed up the exit.
Calin Juravleb4eddd22016-01-13 15:52:33 -0800519 return true;
520 }
521 const std::string& filename = it.first;
522 const std::set<std::string>& locations = it.second;
Mathieu Chartier1a074352019-01-04 15:08:29 -0800523 VLOG(profiler) << "Tracked filename " << filename << " locations "
524 << android::base::Join(locations, ":");
525
Calin Juravle940eb0c2017-01-30 19:30:44 -0800526 std::vector<ProfileMethodInfo> profile_methods;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800527 {
528 ScopedObjectAccess soa(Thread::Current());
Calin Juravle940eb0c2017-01-30 19:30:44 -0800529 jit_code_cache_->GetProfiledMethods(locations, profile_methods);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000530 total_number_of_code_cache_queries_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800531 }
Calin Juravlecc3171a2017-05-19 16:47:53 -0700532 {
533 ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700534 if (!info.Load(filename, /*clear_if_invalid=*/ true)) {
Calin Juravlecc3171a2017-05-19 16:47:53 -0700535 LOG(WARNING) << "Could not forcefully load profile " << filename;
536 continue;
537 }
538 uint64_t last_save_number_of_methods = info.GetNumberOfMethods();
539 uint64_t last_save_number_of_classes = info.GetNumberOfResolvedClasses();
Mathieu Chartier1a074352019-01-04 15:08:29 -0800540 VLOG(profiler) << "last_save_number_of_methods=" << last_save_number_of_methods
541 << " last_save_number_of_classes=" << last_save_number_of_classes
542 << " number of profiled methods=" << profile_methods.size();
Calin Juravlec15e5662016-03-17 17:07:52 +0000543
Calin Juravled5aeade2018-05-08 18:23:24 -0700544 // Try to add the method data. Note this may fail is the profile loaded from disk contains
545 // outdated data (e.g. the previous profiled dex files might have been updated).
546 // If this happens we clear the profile data and for the save to ensure the file is cleared.
547 if (!info.AddMethods(profile_methods,
548 ProfileCompilationInfo::MethodHotness::kFlagPostStartup)) {
549 LOG(WARNING) << "Could not add methods to the existing profiler. "
550 << "Clearing the profile data.";
551 info.ClearData();
552 force_save = true;
553 }
554
Calin Juravlecc3171a2017-05-19 16:47:53 -0700555 auto profile_cache_it = profile_cache_.find(filename);
Calin Juravledcab1902017-05-12 19:18:47 -0700556 if (profile_cache_it != profile_cache_.end()) {
Calin Juravled5aeade2018-05-08 18:23:24 -0700557 if (!info.MergeWith(*(profile_cache_it->second))) {
558 LOG(WARNING) << "Could not merge the profile. Clearing the profile data.";
559 info.ClearData();
560 force_save = true;
561 }
Mathieu Chartier1a074352019-01-04 15:08:29 -0800562 } else if (VLOG_IS_ON(profiler)) {
563 LOG(INFO) << "Failed to find cached profile for " << filename;
564 for (auto&& pair : profile_cache_) {
565 LOG(INFO) << "Cached profile " << pair.first;
566 }
Calin Juravledcab1902017-05-12 19:18:47 -0700567 }
Calin Juravlecc3171a2017-05-19 16:47:53 -0700568
569 int64_t delta_number_of_methods =
570 info.GetNumberOfMethods() - last_save_number_of_methods;
571 int64_t delta_number_of_classes =
572 info.GetNumberOfResolvedClasses() - last_save_number_of_classes;
573
574 if (!force_save &&
575 delta_number_of_methods < options_.GetMinMethodsToSave() &&
576 delta_number_of_classes < options_.GetMinClassesToSave()) {
577 VLOG(profiler) << "Not enough information to save to: " << filename
578 << " Number of methods: " << delta_number_of_methods
579 << " Number of classes: " << delta_number_of_classes;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000580 total_number_of_skipped_writes_++;
Calin Juravlecc3171a2017-05-19 16:47:53 -0700581 continue;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000582 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700583
Calin Juravlecc3171a2017-05-19 16:47:53 -0700584 if (number_of_new_methods != nullptr) {
585 *number_of_new_methods =
586 std::max(static_cast<uint16_t>(delta_number_of_methods),
587 *number_of_new_methods);
588 }
589 uint64_t bytes_written;
590 // Force the save. In case the profile data is corrupted or the the profile
591 // has the wrong version this will "fix" the file to the correct format.
592 if (info.Save(filename, &bytes_written)) {
593 // We managed to save the profile. Clear the cache stored during startup.
594 if (profile_cache_it != profile_cache_.end()) {
595 ProfileCompilationInfo *cached_info = profile_cache_it->second;
596 profile_cache_.erase(profile_cache_it);
597 delete cached_info;
598 }
599 if (bytes_written > 0) {
600 total_number_of_writes_++;
601 total_bytes_written_ += bytes_written;
602 profile_file_saved = true;
603 } else {
604 // At this point we could still have avoided the write.
605 // We load and merge the data from the file lazily at its first ever
606 // save attempt. So, whatever we are trying to save could already be
607 // in the file.
608 total_number_of_skipped_writes_++;
609 }
610 } else {
611 LOG(WARNING) << "Could not save profiling info to " << filename;
612 total_number_of_failed_writes_++;
613 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800614 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800615 }
Calin Juravledcab1902017-05-12 19:18:47 -0700616
Mathieu Chartier06bed302017-07-13 13:23:18 -0700617 // Trim the maps to madvise the pages used for profile info.
618 // It is unlikely we will need them again in the near feature.
619 Runtime::Current()->GetArenaPool()->TrimMaps();
620
Calin Juravle85f7bf32016-03-18 16:23:40 +0000621 return profile_file_saved;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000622}
623
624void* ProfileSaver::RunProfileSaverThread(void* arg) {
625 Runtime* runtime = Runtime::Current();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000626
Calin Juravlee55fda12016-04-28 12:59:33 +0100627 bool attached = runtime->AttachCurrentThread("Profile Saver",
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700628 /*as_daemon=*/true,
Calin Juravlee55fda12016-04-28 12:59:33 +0100629 runtime->GetSystemThreadGroup(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700630 /*create_peer=*/true);
Calin Juravlee55fda12016-04-28 12:59:33 +0100631 if (!attached) {
632 CHECK(runtime->IsShuttingDown(Thread::Current()));
633 return nullptr;
634 }
635
636 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000637 profile_saver->Run();
638
639 runtime->DetachCurrentThread();
640 VLOG(profiler) << "Profile saver shutdown";
641 return nullptr;
642}
643
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700644static bool ShouldProfileLocation(const std::string& location, bool profile_aot_code) {
645 if (profile_aot_code) {
646 // If we have to profile all the code, irrespective of its compilation state, return true
647 // right away.
648 return true;
649 }
650
Calin Juravle75064232016-04-18 16:38:27 +0100651 OatFileManager& oat_manager = Runtime::Current()->GetOatFileManager();
652 const OatFile* oat_file = oat_manager.FindOpenedOatFileFromDexLocation(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000653 if (oat_file == nullptr) {
654 // This can happen if we fallback to run code directly from the APK.
655 // Profile it with the hope that the background dexopt will get us back into
656 // a good state.
Calin Juravle75064232016-04-18 16:38:27 +0100657 VLOG(profiler) << "Asked to profile a location without an oat file:" << location;
Calin Juravle6044fa72016-03-25 17:17:09 +0000658 return true;
659 }
660 CompilerFilter::Filter filter = oat_file->GetCompilerFilter();
Calin Juravled19dc462016-04-19 18:17:41 +0100661 if ((filter == CompilerFilter::kSpeed) || (filter == CompilerFilter::kEverything)) {
Calin Juravle75064232016-04-18 16:38:27 +0100662 VLOG(profiler)
Calin Juravled19dc462016-04-19 18:17:41 +0100663 << "Skip profiling oat file because it's already speed|everything compiled: "
664 << location << " oat location: " << oat_file->GetLocation();
Calin Juravle6044fa72016-03-25 17:17:09 +0000665 return false;
666 }
667 return true;
668}
669
Calin Juravle138dbff2016-06-28 19:36:58 +0100670void ProfileSaver::Start(const ProfileSaverOptions& options,
671 const std::string& output_filename,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000672 jit::JitCodeCache* jit_code_cache,
Calin Juravle77651c42017-03-03 18:04:02 -0800673 const std::vector<std::string>& code_paths) {
Mathieu Chartier885a7132017-06-10 14:35:11 -0700674 Runtime* const runtime = Runtime::Current();
Calin Juravle138dbff2016-06-28 19:36:58 +0100675 DCHECK(options.IsEnabled());
Mathieu Chartier885a7132017-06-10 14:35:11 -0700676 DCHECK(runtime->GetJit() != nullptr);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000677 DCHECK(!output_filename.empty());
678 DCHECK(jit_code_cache != nullptr);
679
Calin Juravle6044fa72016-03-25 17:17:09 +0000680 std::vector<std::string> code_paths_to_profile;
Calin Juravle6044fa72016-03-25 17:17:09 +0000681 for (const std::string& location : code_paths) {
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700682 if (ShouldProfileLocation(location, options.GetProfileAOTCode())) {
Mathieu Chartier1a074352019-01-04 15:08:29 -0800683 VLOG(profiler) << "Code path to profile " << location;
Calin Juravle6044fa72016-03-25 17:17:09 +0000684 code_paths_to_profile.push_back(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000685 }
686 }
Mathieu Chartier885a7132017-06-10 14:35:11 -0700687
688 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
689 // Support getting profile samples for the boot class path. This will be used to generate the boot
690 // image profile. The intention is to use this code to generate to boot image but not use it in
691 // production. b/37966211
692 if (options.GetProfileBootClassPath()) {
693 std::set<std::string> code_paths_keys;
694 for (const std::string& location : code_paths) {
695 code_paths_keys.insert(ProfileCompilationInfo::GetProfileDexFileKey(location));
696 }
697 for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
698 // Don't check ShouldProfileLocation since the boot class path may be speed compiled.
699 const std::string& location = dex_file->GetLocation();
700 const std::string key = ProfileCompilationInfo::GetProfileDexFileKey(location);
701 VLOG(profiler) << "Registering boot dex file " << location;
702 if (code_paths_keys.find(key) != code_paths_keys.end()) {
703 LOG(WARNING) << "Boot class path location key conflicts with code path " << location;
704 } else if (instance_ == nullptr) {
705 // Only add the boot class path once since Start may be called multiple times for secondary
706 // dexes.
707 // We still do the collision check above. This handles any secondary dexes that conflict
708 // with the boot class path dex files.
709 code_paths_to_profile.push_back(location);
710 }
711 }
712 }
Calin Juravle6044fa72016-03-25 17:17:09 +0000713 if (code_paths_to_profile.empty()) {
Calin Juravle75064232016-04-18 16:38:27 +0100714 VLOG(profiler) << "No code paths should be profiled.";
Calin Juravle6044fa72016-03-25 17:17:09 +0000715 return;
716 }
717
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000718 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800719 // If we already have an instance, make sure it uses the same jit_code_cache.
720 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
721 // apps which share the same runtime).
722 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
723 // Add the code_paths to the tracked locations.
Calin Juravle77651c42017-03-03 18:04:02 -0800724 instance_->AddTrackedLocations(output_filename, code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000725 return;
726 }
727
728 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
Andreas Gampe9186ced2016-12-12 14:28:21 -0800729 << ". Tracking: " << android::base::Join(code_paths_to_profile, ':');
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000730
Calin Juravle138dbff2016-06-28 19:36:58 +0100731 instance_ = new ProfileSaver(options,
732 output_filename,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000733 jit_code_cache,
Calin Juravle77651c42017-03-03 18:04:02 -0800734 code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000735
736 // Create a new thread which does the saving.
737 CHECK_PTHREAD_CALL(
738 pthread_create,
739 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
740 "Profile saver thread");
Nicolas Geoffray23caed82017-04-21 14:30:18 +0100741
Mathieu Chartier5494e5b2017-06-26 14:13:27 -0700742 SetProfileSaverThreadPriority(profiler_pthread_, kProfileSaverPthreadPriority);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000743}
744
Calin Juravlec19c1c22016-03-09 15:37:48 +0000745void ProfileSaver::Stop(bool dump_info) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000746 ProfileSaver* profile_saver = nullptr;
747 pthread_t profiler_pthread = 0U;
748
749 {
750 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800751 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000752 profile_saver = instance_;
753 profiler_pthread = profiler_pthread_;
754 if (instance_ == nullptr) {
755 DCHECK(false) << "Tried to stop a profile saver which was not started";
756 return;
757 }
758 if (instance_->shutting_down_) {
759 DCHECK(false) << "Tried to stop the profile saver twice";
760 return;
761 }
762 instance_->shutting_down_ = true;
763 }
764
765 {
766 // Wake up the saver thread if it is sleeping to allow for a clean exit.
767 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
768 profile_saver->period_condition_.Signal(Thread::Current());
769 }
770
Mathieu Chartier06bed302017-07-13 13:23:18 -0700771 // Force save everything before destroying the thread since we want profiler_pthread_ to remain
772 // valid.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700773 instance_->ProcessProfilingInfo(/*force_save=*/true, /*number_of_new_methods=*/nullptr);
Mathieu Chartier06bed302017-07-13 13:23:18 -0700774
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000775 // Wait for the saver thread to stop.
776 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
777
778 {
779 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle9db22e82017-03-30 16:31:23 -0700780 if (dump_info) {
781 instance_->DumpInfo(LOG_STREAM(INFO));
782 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000783 instance_ = nullptr;
784 profiler_pthread_ = 0U;
785 }
786 delete profile_saver;
787}
788
789bool ProfileSaver::ShuttingDown(Thread* self) {
790 MutexLock mu(self, *Locks::profiler_lock_);
791 return shutting_down_;
792}
793
794bool ProfileSaver::IsStarted() {
795 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
796 return instance_ != nullptr;
797}
798
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700799static void AddTrackedLocationsToMap(const std::string& output_filename,
800 const std::vector<std::string>& code_paths,
801 SafeMap<std::string, std::set<std::string>>* map) {
802 auto it = map->find(output_filename);
803 if (it == map->end()) {
804 map->Put(output_filename, std::set<std::string>(code_paths.begin(), code_paths.end()));
Calin Juravleb4eddd22016-01-13 15:52:33 -0800805 } else {
806 it->second.insert(code_paths.begin(), code_paths.end());
807 }
808}
809
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700810void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
811 const std::vector<std::string>& code_paths) {
812 // Add the code paths to the list of tracked location.
813 AddTrackedLocationsToMap(output_filename, code_paths, &tracked_dex_base_locations_);
814 // The code paths may contain symlinks which could fool the profiler.
815 // If the dex file is compiled with an absolute location but loaded with symlink
816 // the profiler could skip the dex due to location mismatch.
817 // To avoid this, we add the code paths to the temporary cache of 'to_be_resolved'
818 // locations. When the profiler thread executes we will resolve the paths to their
819 // real paths.
820 // Note that we delay taking the realpath to avoid spending more time than needed
821 // when registering location (as it is done during app launch).
822 AddTrackedLocationsToMap(output_filename,
823 code_paths,
824 &tracked_dex_base_locations_to_be_resolved_);
825}
826
Calin Juravlec19c1c22016-03-09 15:37:48 +0000827void ProfileSaver::DumpInstanceInfo(std::ostream& os) {
828 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
829 if (instance_ != nullptr) {
830 instance_->DumpInfo(os);
831 }
832}
833
834void ProfileSaver::DumpInfo(std::ostream& os) {
835 os << "ProfileSaver total_bytes_written=" << total_bytes_written_ << '\n'
836 << "ProfileSaver total_number_of_writes=" << total_number_of_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000837 << "ProfileSaver total_number_of_code_cache_queries="
838 << total_number_of_code_cache_queries_ << '\n'
Calin Juravlec19c1c22016-03-09 15:37:48 +0000839 << "ProfileSaver total_number_of_skipped_writes=" << total_number_of_skipped_writes_ << '\n'
840 << "ProfileSaver total_number_of_failed_writes=" << total_number_of_failed_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000841 << "ProfileSaver total_ms_of_sleep=" << total_ms_of_sleep_ << '\n'
Calin Juravle6044fa72016-03-25 17:17:09 +0000842 << "ProfileSaver total_ms_of_work=" << NsToMs(total_ns_of_work_) << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000843 << "ProfileSaver max_number_profile_entries_cached="
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100844 << max_number_of_profile_entries_cached_ << '\n'
845 << "ProfileSaver total_number_of_hot_spikes=" << total_number_of_hot_spikes_ << '\n'
846 << "ProfileSaver total_number_of_wake_ups=" << total_number_of_wake_ups_ << '\n';
Calin Juravlec19c1c22016-03-09 15:37:48 +0000847}
848
Calin Juravlee5de54c2016-04-20 14:22:09 +0100849
850void ProfileSaver::ForceProcessProfiles() {
851 ProfileSaver* saver = nullptr;
852 {
853 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
854 saver = instance_;
855 }
856 // TODO(calin): this is not actually thread safe as the instance_ may have been deleted,
857 // but we only use this in testing when we now this won't happen.
858 // Refactor the way we handle the instance so that we don't end up in this situation.
859 if (saver != nullptr) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700860 saver->ProcessProfilingInfo(/*force_save=*/true, /*number_of_new_methods=*/nullptr);
Calin Juravlee5de54c2016-04-20 14:22:09 +0100861 }
862}
863
Mathieu Chartier06bed302017-07-13 13:23:18 -0700864bool ProfileSaver::HasSeenMethod(const std::string& profile, bool hot, MethodReference ref) {
Calin Juravlee5de54c2016-04-20 14:22:09 +0100865 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
866 if (instance_ != nullptr) {
Calin Juravlecc3171a2017-05-19 16:47:53 -0700867 ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700868 if (!info.Load(profile, /*clear_if_invalid=*/false)) {
Calin Juravledcab1902017-05-12 19:18:47 -0700869 return false;
870 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700871 ProfileCompilationInfo::MethodHotness hotness = info.GetMethodHotness(ref);
Mathieu Chartier48a951b2017-07-13 17:04:02 -0700872 // Ignore hot parameter for now since it was causing test 595 to be flaky. TODO: Investigate.
873 // b/63635729
874 UNUSED(hot);
875 return hotness.IsInProfile();
Calin Juravlee5de54c2016-04-20 14:22:09 +0100876 }
877 return false;
878}
879
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700880void ProfileSaver::ResolveTrackedLocations() {
881 SafeMap<std::string, std::set<std::string>> locations_to_be_resolved;
882 {
883 // Make a copy so that we don't hold the lock while doing I/O.
884 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
885 locations_to_be_resolved = tracked_dex_base_locations_to_be_resolved_;
886 tracked_dex_base_locations_to_be_resolved_.clear();
887 }
888
889 // Resolve the locations.
890 SafeMap<std::string, std::vector<std::string>> resolved_locations_map;
891 for (const auto& it : locations_to_be_resolved) {
892 const std::string& filename = it.first;
893 const std::set<std::string>& locations = it.second;
894 auto resolved_locations_it = resolved_locations_map.Put(
895 filename,
896 std::vector<std::string>(locations.size()));
897
898 for (const auto& location : locations) {
899 UniqueCPtr<const char[]> location_real(realpath(location.c_str(), nullptr));
900 // Note that it's ok if we cannot get the real path.
901 if (location_real != nullptr) {
902 resolved_locations_it->second.emplace_back(location_real.get());
903 }
904 }
905 }
906
907 // Add the resolved locations to the tracked collection.
908 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
909 for (const auto& it : resolved_locations_map) {
910 AddTrackedLocationsToMap(it.first, it.second, &tracked_dex_base_locations_);
911 }
912}
913
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000914} // namespace art