blob: c8d4728589fd67d00ae2b46fd21d98ca684854ee [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;
434 for (const auto& pair : hot_methods.GetMap()) {
435 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700436 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
437 if (locations.find(base_location) != locations.end()) {
Mathieu Chartierdb40eac2017-06-09 18:34:11 -0700438 const MethodReferenceCollection::IndexVector& indices = pair.second;
Mathieu Chartier06bed302017-07-13 13:23:18 -0700439 uint8_t flags = Hotness::kFlagHot;
440 flags |= startup ? Hotness::kFlagStartup : Hotness::kFlagPostStartup;
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700441 cached_info->AddMethodsForDex(
Mathieu Chartier06bed302017-07-13 13:23:18 -0700442 static_cast<Hotness::Flag>(flags),
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700443 dex_file,
444 indices.begin(),
445 indices.end());
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700446 }
447 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700448 for (const auto& pair : sampled_methods.GetMap()) {
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700449 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700450 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
451 if (locations.find(base_location) != locations.end()) {
Mathieu Chartierdb40eac2017-06-09 18:34:11 -0700452 const MethodReferenceCollection::IndexVector& indices = pair.second;
Mathieu Chartier06bed302017-07-13 13:23:18 -0700453 cached_info->AddMethodsForDex(startup ? Hotness::kFlagStartup : Hotness::kFlagPostStartup,
Mathieu Chartierdb40eac2017-06-09 18:34:11 -0700454 dex_file,
455 indices.begin(),
456 indices.end());
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700457 }
458 }
459 for (const auto& pair : resolved_classes.GetMap()) {
460 const DexFile* const dex_file = pair.first;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700461 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
462 if (locations.find(base_location) != locations.end()) {
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700463 const TypeReferenceCollection::IndexVector& classes = pair.second;
464 VLOG(profiler) << "Added " << classes.size() << " classes for location "
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700465 << base_location
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700466 << " (" << dex_file->GetLocation() << ")";
467 cached_info->AddClassesForDex(dex_file, classes.begin(), classes.end());
468 } else {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700469 VLOG(profiler) << "Location not found " << base_location
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700470 << " (" << dex_file->GetLocation() << ")";
471 }
472 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000473 total_number_of_profile_entries_cached += resolved_classes_for_location.size();
474 }
475 max_number_of_profile_entries_cached_ = std::max(
476 max_number_of_profile_entries_cached_,
477 total_number_of_profile_entries_cached);
Mathieu Chartierfaf83202017-06-08 10:35:20 -0700478 VLOG(profiler) << "Profile saver recorded " << hot_methods.NumReferences() << " hot methods and "
Mathieu Chartier06bed302017-07-13 13:23:18 -0700479 << sampled_methods.NumReferences() << " sampled methods with threshold "
480 << hot_method_sample_threshold << " in "
481 << PrettyDuration(NanoTime() - start_time);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000482}
483
Calin Juravlea345d312017-03-14 18:45:55 -0700484bool ProfileSaver::ProcessProfilingInfo(bool force_save, /*out*/uint16_t* number_of_new_methods) {
Calin Juravle85f7bf32016-03-18 16:23:40 +0000485 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700486
487 // Resolve any new registered locations.
488 ResolveTrackedLocations();
489
Calin Juravleb4eddd22016-01-13 15:52:33 -0800490 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000491 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800492 // Make a copy so that we don't hold the lock while doing I/O.
493 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
494 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000495 }
Calin Juravlec15e5662016-03-17 17:07:52 +0000496
Calin Juravle85f7bf32016-03-18 16:23:40 +0000497 bool profile_file_saved = false;
Calin Juravlea345d312017-03-14 18:45:55 -0700498 if (number_of_new_methods != nullptr) {
499 *number_of_new_methods = 0;
500 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100501
Mathieu Chartier06bed302017-07-13 13:23:18 -0700502 // We only need to do this once, not once per dex location.
503 // TODO: Figure out a way to only do it when stuff has changed? It takes 30-50ms.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700504 FetchAndCacheResolvedClassesAndMethods(/*startup=*/ false);
Mathieu Chartier06bed302017-07-13 13:23:18 -0700505
Calin Juravleb4eddd22016-01-13 15:52:33 -0800506 for (const auto& it : tracked_locations) {
Calin Juravlea345d312017-03-14 18:45:55 -0700507 if (!force_save && ShuttingDown(Thread::Current())) {
508 // The ProfileSaver is in shutdown mode, meaning a stop request was made and
509 // we need to exit cleanly (by waiting for the saver thread to finish). Unless
510 // we have a request for a forced save, do not do any processing so that we
511 // speed up the exit.
Calin Juravleb4eddd22016-01-13 15:52:33 -0800512 return true;
513 }
514 const std::string& filename = it.first;
515 const std::set<std::string>& locations = it.second;
Calin Juravle940eb0c2017-01-30 19:30:44 -0800516 std::vector<ProfileMethodInfo> profile_methods;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800517 {
518 ScopedObjectAccess soa(Thread::Current());
Calin Juravle940eb0c2017-01-30 19:30:44 -0800519 jit_code_cache_->GetProfiledMethods(locations, profile_methods);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000520 total_number_of_code_cache_queries_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800521 }
Calin Juravlecc3171a2017-05-19 16:47:53 -0700522 {
523 ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700524 if (!info.Load(filename, /*clear_if_invalid=*/ true)) {
Calin Juravlecc3171a2017-05-19 16:47:53 -0700525 LOG(WARNING) << "Could not forcefully load profile " << filename;
526 continue;
527 }
528 uint64_t last_save_number_of_methods = info.GetNumberOfMethods();
529 uint64_t last_save_number_of_classes = info.GetNumberOfResolvedClasses();
Calin Juravlec15e5662016-03-17 17:07:52 +0000530
Calin Juravled5aeade2018-05-08 18:23:24 -0700531 // Try to add the method data. Note this may fail is the profile loaded from disk contains
532 // outdated data (e.g. the previous profiled dex files might have been updated).
533 // If this happens we clear the profile data and for the save to ensure the file is cleared.
534 if (!info.AddMethods(profile_methods,
535 ProfileCompilationInfo::MethodHotness::kFlagPostStartup)) {
536 LOG(WARNING) << "Could not add methods to the existing profiler. "
537 << "Clearing the profile data.";
538 info.ClearData();
539 force_save = true;
540 }
541
Calin Juravlecc3171a2017-05-19 16:47:53 -0700542 auto profile_cache_it = profile_cache_.find(filename);
Calin Juravledcab1902017-05-12 19:18:47 -0700543 if (profile_cache_it != profile_cache_.end()) {
Calin Juravled5aeade2018-05-08 18:23:24 -0700544 if (!info.MergeWith(*(profile_cache_it->second))) {
545 LOG(WARNING) << "Could not merge the profile. Clearing the profile data.";
546 info.ClearData();
547 force_save = true;
548 }
Calin Juravledcab1902017-05-12 19:18:47 -0700549 }
Calin Juravlecc3171a2017-05-19 16:47:53 -0700550
551 int64_t delta_number_of_methods =
552 info.GetNumberOfMethods() - last_save_number_of_methods;
553 int64_t delta_number_of_classes =
554 info.GetNumberOfResolvedClasses() - last_save_number_of_classes;
555
556 if (!force_save &&
557 delta_number_of_methods < options_.GetMinMethodsToSave() &&
558 delta_number_of_classes < options_.GetMinClassesToSave()) {
559 VLOG(profiler) << "Not enough information to save to: " << filename
560 << " Number of methods: " << delta_number_of_methods
561 << " Number of classes: " << delta_number_of_classes;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000562 total_number_of_skipped_writes_++;
Calin Juravlecc3171a2017-05-19 16:47:53 -0700563 continue;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000564 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700565
Calin Juravlecc3171a2017-05-19 16:47:53 -0700566 if (number_of_new_methods != nullptr) {
567 *number_of_new_methods =
568 std::max(static_cast<uint16_t>(delta_number_of_methods),
569 *number_of_new_methods);
570 }
571 uint64_t bytes_written;
572 // Force the save. In case the profile data is corrupted or the the profile
573 // has the wrong version this will "fix" the file to the correct format.
574 if (info.Save(filename, &bytes_written)) {
575 // We managed to save the profile. Clear the cache stored during startup.
576 if (profile_cache_it != profile_cache_.end()) {
577 ProfileCompilationInfo *cached_info = profile_cache_it->second;
578 profile_cache_.erase(profile_cache_it);
579 delete cached_info;
580 }
581 if (bytes_written > 0) {
582 total_number_of_writes_++;
583 total_bytes_written_ += bytes_written;
584 profile_file_saved = true;
585 } else {
586 // At this point we could still have avoided the write.
587 // We load and merge the data from the file lazily at its first ever
588 // save attempt. So, whatever we are trying to save could already be
589 // in the file.
590 total_number_of_skipped_writes_++;
591 }
592 } else {
593 LOG(WARNING) << "Could not save profiling info to " << filename;
594 total_number_of_failed_writes_++;
595 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800596 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800597 }
Calin Juravledcab1902017-05-12 19:18:47 -0700598
Mathieu Chartier06bed302017-07-13 13:23:18 -0700599 // Trim the maps to madvise the pages used for profile info.
600 // It is unlikely we will need them again in the near feature.
601 Runtime::Current()->GetArenaPool()->TrimMaps();
602
Calin Juravle85f7bf32016-03-18 16:23:40 +0000603 return profile_file_saved;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000604}
605
606void* ProfileSaver::RunProfileSaverThread(void* arg) {
607 Runtime* runtime = Runtime::Current();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000608
Calin Juravlee55fda12016-04-28 12:59:33 +0100609 bool attached = runtime->AttachCurrentThread("Profile Saver",
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700610 /*as_daemon=*/true,
Calin Juravlee55fda12016-04-28 12:59:33 +0100611 runtime->GetSystemThreadGroup(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700612 /*create_peer=*/true);
Calin Juravlee55fda12016-04-28 12:59:33 +0100613 if (!attached) {
614 CHECK(runtime->IsShuttingDown(Thread::Current()));
615 return nullptr;
616 }
617
618 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000619 profile_saver->Run();
620
621 runtime->DetachCurrentThread();
622 VLOG(profiler) << "Profile saver shutdown";
623 return nullptr;
624}
625
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700626static bool ShouldProfileLocation(const std::string& location, bool profile_aot_code) {
627 if (profile_aot_code) {
628 // If we have to profile all the code, irrespective of its compilation state, return true
629 // right away.
630 return true;
631 }
632
Calin Juravle75064232016-04-18 16:38:27 +0100633 OatFileManager& oat_manager = Runtime::Current()->GetOatFileManager();
634 const OatFile* oat_file = oat_manager.FindOpenedOatFileFromDexLocation(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000635 if (oat_file == nullptr) {
636 // This can happen if we fallback to run code directly from the APK.
637 // Profile it with the hope that the background dexopt will get us back into
638 // a good state.
Calin Juravle75064232016-04-18 16:38:27 +0100639 VLOG(profiler) << "Asked to profile a location without an oat file:" << location;
Calin Juravle6044fa72016-03-25 17:17:09 +0000640 return true;
641 }
642 CompilerFilter::Filter filter = oat_file->GetCompilerFilter();
Calin Juravled19dc462016-04-19 18:17:41 +0100643 if ((filter == CompilerFilter::kSpeed) || (filter == CompilerFilter::kEverything)) {
Calin Juravle75064232016-04-18 16:38:27 +0100644 VLOG(profiler)
Calin Juravled19dc462016-04-19 18:17:41 +0100645 << "Skip profiling oat file because it's already speed|everything compiled: "
646 << location << " oat location: " << oat_file->GetLocation();
Calin Juravle6044fa72016-03-25 17:17:09 +0000647 return false;
648 }
649 return true;
650}
651
Calin Juravle138dbff2016-06-28 19:36:58 +0100652void ProfileSaver::Start(const ProfileSaverOptions& options,
653 const std::string& output_filename,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000654 jit::JitCodeCache* jit_code_cache,
Calin Juravle77651c42017-03-03 18:04:02 -0800655 const std::vector<std::string>& code_paths) {
Mathieu Chartier885a7132017-06-10 14:35:11 -0700656 Runtime* const runtime = Runtime::Current();
Calin Juravle138dbff2016-06-28 19:36:58 +0100657 DCHECK(options.IsEnabled());
Mathieu Chartier885a7132017-06-10 14:35:11 -0700658 DCHECK(runtime->GetJit() != nullptr);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000659 DCHECK(!output_filename.empty());
660 DCHECK(jit_code_cache != nullptr);
661
Calin Juravle6044fa72016-03-25 17:17:09 +0000662 std::vector<std::string> code_paths_to_profile;
Calin Juravle6044fa72016-03-25 17:17:09 +0000663 for (const std::string& location : code_paths) {
Calin Juravleb3d1eee2018-05-03 22:28:03 -0700664 if (ShouldProfileLocation(location, options.GetProfileAOTCode())) {
Calin Juravle6044fa72016-03-25 17:17:09 +0000665 code_paths_to_profile.push_back(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000666 }
667 }
Mathieu Chartier885a7132017-06-10 14:35:11 -0700668
669 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
670 // Support getting profile samples for the boot class path. This will be used to generate the boot
671 // image profile. The intention is to use this code to generate to boot image but not use it in
672 // production. b/37966211
673 if (options.GetProfileBootClassPath()) {
674 std::set<std::string> code_paths_keys;
675 for (const std::string& location : code_paths) {
676 code_paths_keys.insert(ProfileCompilationInfo::GetProfileDexFileKey(location));
677 }
678 for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
679 // Don't check ShouldProfileLocation since the boot class path may be speed compiled.
680 const std::string& location = dex_file->GetLocation();
681 const std::string key = ProfileCompilationInfo::GetProfileDexFileKey(location);
682 VLOG(profiler) << "Registering boot dex file " << location;
683 if (code_paths_keys.find(key) != code_paths_keys.end()) {
684 LOG(WARNING) << "Boot class path location key conflicts with code path " << location;
685 } else if (instance_ == nullptr) {
686 // Only add the boot class path once since Start may be called multiple times for secondary
687 // dexes.
688 // We still do the collision check above. This handles any secondary dexes that conflict
689 // with the boot class path dex files.
690 code_paths_to_profile.push_back(location);
691 }
692 }
693 }
Calin Juravle6044fa72016-03-25 17:17:09 +0000694 if (code_paths_to_profile.empty()) {
Calin Juravle75064232016-04-18 16:38:27 +0100695 VLOG(profiler) << "No code paths should be profiled.";
Calin Juravle6044fa72016-03-25 17:17:09 +0000696 return;
697 }
698
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000699 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800700 // If we already have an instance, make sure it uses the same jit_code_cache.
701 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
702 // apps which share the same runtime).
703 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
704 // Add the code_paths to the tracked locations.
Calin Juravle77651c42017-03-03 18:04:02 -0800705 instance_->AddTrackedLocations(output_filename, code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000706 return;
707 }
708
709 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
Andreas Gampe9186ced2016-12-12 14:28:21 -0800710 << ". Tracking: " << android::base::Join(code_paths_to_profile, ':');
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000711
Calin Juravle138dbff2016-06-28 19:36:58 +0100712 instance_ = new ProfileSaver(options,
713 output_filename,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000714 jit_code_cache,
Calin Juravle77651c42017-03-03 18:04:02 -0800715 code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000716
717 // Create a new thread which does the saving.
718 CHECK_PTHREAD_CALL(
719 pthread_create,
720 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
721 "Profile saver thread");
Nicolas Geoffray23caed82017-04-21 14:30:18 +0100722
Mathieu Chartier5494e5b2017-06-26 14:13:27 -0700723 SetProfileSaverThreadPriority(profiler_pthread_, kProfileSaverPthreadPriority);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000724}
725
Calin Juravlec19c1c22016-03-09 15:37:48 +0000726void ProfileSaver::Stop(bool dump_info) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000727 ProfileSaver* profile_saver = nullptr;
728 pthread_t profiler_pthread = 0U;
729
730 {
731 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800732 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000733 profile_saver = instance_;
734 profiler_pthread = profiler_pthread_;
735 if (instance_ == nullptr) {
736 DCHECK(false) << "Tried to stop a profile saver which was not started";
737 return;
738 }
739 if (instance_->shutting_down_) {
740 DCHECK(false) << "Tried to stop the profile saver twice";
741 return;
742 }
743 instance_->shutting_down_ = true;
744 }
745
746 {
747 // Wake up the saver thread if it is sleeping to allow for a clean exit.
748 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
749 profile_saver->period_condition_.Signal(Thread::Current());
750 }
751
Mathieu Chartier06bed302017-07-13 13:23:18 -0700752 // Force save everything before destroying the thread since we want profiler_pthread_ to remain
753 // valid.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700754 instance_->ProcessProfilingInfo(/*force_save=*/true, /*number_of_new_methods=*/nullptr);
Mathieu Chartier06bed302017-07-13 13:23:18 -0700755
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000756 // Wait for the saver thread to stop.
757 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
758
759 {
760 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle9db22e82017-03-30 16:31:23 -0700761 if (dump_info) {
762 instance_->DumpInfo(LOG_STREAM(INFO));
763 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000764 instance_ = nullptr;
765 profiler_pthread_ = 0U;
766 }
767 delete profile_saver;
768}
769
770bool ProfileSaver::ShuttingDown(Thread* self) {
771 MutexLock mu(self, *Locks::profiler_lock_);
772 return shutting_down_;
773}
774
775bool ProfileSaver::IsStarted() {
776 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
777 return instance_ != nullptr;
778}
779
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700780static void AddTrackedLocationsToMap(const std::string& output_filename,
781 const std::vector<std::string>& code_paths,
782 SafeMap<std::string, std::set<std::string>>* map) {
783 auto it = map->find(output_filename);
784 if (it == map->end()) {
785 map->Put(output_filename, std::set<std::string>(code_paths.begin(), code_paths.end()));
Calin Juravleb4eddd22016-01-13 15:52:33 -0800786 } else {
787 it->second.insert(code_paths.begin(), code_paths.end());
788 }
789}
790
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700791void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
792 const std::vector<std::string>& code_paths) {
793 // Add the code paths to the list of tracked location.
794 AddTrackedLocationsToMap(output_filename, code_paths, &tracked_dex_base_locations_);
795 // The code paths may contain symlinks which could fool the profiler.
796 // If the dex file is compiled with an absolute location but loaded with symlink
797 // the profiler could skip the dex due to location mismatch.
798 // To avoid this, we add the code paths to the temporary cache of 'to_be_resolved'
799 // locations. When the profiler thread executes we will resolve the paths to their
800 // real paths.
801 // Note that we delay taking the realpath to avoid spending more time than needed
802 // when registering location (as it is done during app launch).
803 AddTrackedLocationsToMap(output_filename,
804 code_paths,
805 &tracked_dex_base_locations_to_be_resolved_);
806}
807
Calin Juravlec19c1c22016-03-09 15:37:48 +0000808void ProfileSaver::DumpInstanceInfo(std::ostream& os) {
809 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
810 if (instance_ != nullptr) {
811 instance_->DumpInfo(os);
812 }
813}
814
815void ProfileSaver::DumpInfo(std::ostream& os) {
816 os << "ProfileSaver total_bytes_written=" << total_bytes_written_ << '\n'
817 << "ProfileSaver total_number_of_writes=" << total_number_of_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000818 << "ProfileSaver total_number_of_code_cache_queries="
819 << total_number_of_code_cache_queries_ << '\n'
Calin Juravlec19c1c22016-03-09 15:37:48 +0000820 << "ProfileSaver total_number_of_skipped_writes=" << total_number_of_skipped_writes_ << '\n'
821 << "ProfileSaver total_number_of_failed_writes=" << total_number_of_failed_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000822 << "ProfileSaver total_ms_of_sleep=" << total_ms_of_sleep_ << '\n'
Calin Juravle6044fa72016-03-25 17:17:09 +0000823 << "ProfileSaver total_ms_of_work=" << NsToMs(total_ns_of_work_) << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000824 << "ProfileSaver max_number_profile_entries_cached="
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100825 << max_number_of_profile_entries_cached_ << '\n'
826 << "ProfileSaver total_number_of_hot_spikes=" << total_number_of_hot_spikes_ << '\n'
827 << "ProfileSaver total_number_of_wake_ups=" << total_number_of_wake_ups_ << '\n';
Calin Juravlec19c1c22016-03-09 15:37:48 +0000828}
829
Calin Juravlee5de54c2016-04-20 14:22:09 +0100830
831void ProfileSaver::ForceProcessProfiles() {
832 ProfileSaver* saver = nullptr;
833 {
834 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
835 saver = instance_;
836 }
837 // TODO(calin): this is not actually thread safe as the instance_ may have been deleted,
838 // but we only use this in testing when we now this won't happen.
839 // Refactor the way we handle the instance so that we don't end up in this situation.
840 if (saver != nullptr) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700841 saver->ProcessProfilingInfo(/*force_save=*/true, /*number_of_new_methods=*/nullptr);
Calin Juravlee5de54c2016-04-20 14:22:09 +0100842 }
843}
844
Mathieu Chartier06bed302017-07-13 13:23:18 -0700845bool ProfileSaver::HasSeenMethod(const std::string& profile, bool hot, MethodReference ref) {
Calin Juravlee5de54c2016-04-20 14:22:09 +0100846 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
847 if (instance_ != nullptr) {
Calin Juravlecc3171a2017-05-19 16:47:53 -0700848 ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700849 if (!info.Load(profile, /*clear_if_invalid=*/false)) {
Calin Juravledcab1902017-05-12 19:18:47 -0700850 return false;
851 }
Mathieu Chartier06bed302017-07-13 13:23:18 -0700852 ProfileCompilationInfo::MethodHotness hotness = info.GetMethodHotness(ref);
Mathieu Chartier48a951b2017-07-13 17:04:02 -0700853 // Ignore hot parameter for now since it was causing test 595 to be flaky. TODO: Investigate.
854 // b/63635729
855 UNUSED(hot);
856 return hotness.IsInProfile();
Calin Juravlee5de54c2016-04-20 14:22:09 +0100857 }
858 return false;
859}
860
Calin Juravle8b5d9b62017-05-05 17:27:23 -0700861void ProfileSaver::ResolveTrackedLocations() {
862 SafeMap<std::string, std::set<std::string>> locations_to_be_resolved;
863 {
864 // Make a copy so that we don't hold the lock while doing I/O.
865 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
866 locations_to_be_resolved = tracked_dex_base_locations_to_be_resolved_;
867 tracked_dex_base_locations_to_be_resolved_.clear();
868 }
869
870 // Resolve the locations.
871 SafeMap<std::string, std::vector<std::string>> resolved_locations_map;
872 for (const auto& it : locations_to_be_resolved) {
873 const std::string& filename = it.first;
874 const std::set<std::string>& locations = it.second;
875 auto resolved_locations_it = resolved_locations_map.Put(
876 filename,
877 std::vector<std::string>(locations.size()));
878
879 for (const auto& location : locations) {
880 UniqueCPtr<const char[]> location_real(realpath(location.c_str(), nullptr));
881 // Note that it's ok if we cannot get the real path.
882 if (location_real != nullptr) {
883 resolved_locations_it->second.emplace_back(location_real.get());
884 }
885 }
886 }
887
888 // Add the resolved locations to the tracked collection.
889 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
890 for (const auto& it : resolved_locations_map) {
891 AddTrackedLocationsToMap(it.first, it.second, &tracked_dex_base_locations_);
892 }
893}
894
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000895} // namespace art