1 /*
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 
19 #include <sys/resource.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 
24 #include "android-base/strings.h"
25 
26 #include "art_method-inl.h"
27 #include "base/enums.h"
28 #include "base/systrace.h"
29 #include "base/time_utils.h"
30 #include "compiler_filter.h"
31 #include "gc/collector_type.h"
32 #include "gc/gc_cause.h"
33 #include "gc/scoped_gc_critical_section.h"
34 #include "oat_file_manager.h"
35 #include "scoped_thread_state_change-inl.h"
36 
37 namespace art {
38 
39 ProfileSaver* ProfileSaver::instance_ = nullptr;
40 pthread_t ProfileSaver::profiler_pthread_ = 0U;
41 
ProfileSaver(const ProfileSaverOptions & options,const std::string & output_filename,jit::JitCodeCache * jit_code_cache,const std::vector<std::string> & code_paths)42 ProfileSaver::ProfileSaver(const ProfileSaverOptions& options,
43                            const std::string& output_filename,
44                            jit::JitCodeCache* jit_code_cache,
45                            const std::vector<std::string>& code_paths)
46     : jit_code_cache_(jit_code_cache),
47       shutting_down_(false),
48       last_time_ns_saver_woke_up_(0),
49       jit_activity_notifications_(0),
50       wait_lock_("ProfileSaver wait lock"),
51       period_condition_("ProfileSaver period condition", wait_lock_),
52       total_bytes_written_(0),
53       total_number_of_writes_(0),
54       total_number_of_code_cache_queries_(0),
55       total_number_of_skipped_writes_(0),
56       total_number_of_failed_writes_(0),
57       total_ms_of_sleep_(0),
58       total_ns_of_work_(0),
59       max_number_of_profile_entries_cached_(0),
60       total_number_of_hot_spikes_(0),
61       total_number_of_wake_ups_(0),
62       options_(options) {
63   DCHECK(options_.IsEnabled());
64   AddTrackedLocations(output_filename, code_paths);
65 }
66 
~ProfileSaver()67 ProfileSaver::~ProfileSaver() {
68   for (auto& it : profile_cache_) {
69     delete it.second;
70   }
71 }
72 
Run()73 void ProfileSaver::Run() {
74   Thread* self = Thread::Current();
75 
76   // Fetch the resolved classes for the app images after sleeping for
77   // options_.GetSaveResolvedClassesDelayMs().
78   // TODO(calin) This only considers the case of the primary profile file.
79   // Anything that gets loaded in the same VM will not have their resolved
80   // classes save (unless they started before the initial saving was done).
81   {
82     MutexLock mu(self, wait_lock_);
83     const uint64_t end_time = NanoTime() + MsToNs(options_.GetSaveResolvedClassesDelayMs());
84     while (true) {
85       const uint64_t current_time = NanoTime();
86       if (current_time >= end_time) {
87         break;
88       }
89       period_condition_.TimedWait(self, NsToMs(end_time - current_time), 0);
90     }
91     total_ms_of_sleep_ += options_.GetSaveResolvedClassesDelayMs();
92   }
93   FetchAndCacheResolvedClassesAndMethods();
94 
95   // Loop for the profiled methods.
96   while (!ShuttingDown(self)) {
97     uint64_t sleep_start = NanoTime();
98     {
99       uint64_t sleep_time = 0;
100       {
101         MutexLock mu(self, wait_lock_);
102         period_condition_.Wait(self);
103         sleep_time = NanoTime() - sleep_start;
104       }
105       // Check if the thread was woken up for shutdown.
106       if (ShuttingDown(self)) {
107         break;
108       }
109       total_number_of_wake_ups_++;
110       // We might have been woken up by a huge number of notifications to guarantee saving.
111       // If we didn't meet the minimum saving period go back to sleep (only if missed by
112       // a reasonable margin).
113       uint64_t min_save_period_ns = MsToNs(options_.GetMinSavePeriodMs());
114       while (min_save_period_ns * 0.9 > sleep_time) {
115         {
116           MutexLock mu(self, wait_lock_);
117           period_condition_.TimedWait(self, NsToMs(min_save_period_ns - sleep_time), 0);
118           sleep_time = NanoTime() - sleep_start;
119         }
120         // Check if the thread was woken up for shutdown.
121         if (ShuttingDown(self)) {
122           break;
123         }
124         total_number_of_wake_ups_++;
125       }
126     }
127     total_ms_of_sleep_ += NsToMs(NanoTime() - sleep_start);
128 
129     if (ShuttingDown(self)) {
130       break;
131     }
132 
133     uint16_t number_of_new_methods = 0;
134     uint64_t start_work = NanoTime();
135     bool profile_saved_to_disk = ProcessProfilingInfo(/*force_save*/false, &number_of_new_methods);
136     // Update the notification counter based on result. Note that there might be contention on this
137     // but we don't care about to be 100% precise.
138     if (!profile_saved_to_disk) {
139       // If we didn't save to disk it may be because we didn't have enough new methods.
140       // Set the jit activity notifications to number_of_new_methods so we can wake up earlier
141       // if needed.
142       jit_activity_notifications_ = number_of_new_methods;
143     }
144     total_ns_of_work_ += NanoTime() - start_work;
145   }
146 }
147 
NotifyJitActivity()148 void ProfileSaver::NotifyJitActivity() {
149   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
150   if (instance_ == nullptr || instance_->shutting_down_) {
151     return;
152   }
153   instance_->NotifyJitActivityInternal();
154 }
155 
WakeUpSaver()156 void ProfileSaver::WakeUpSaver() {
157   jit_activity_notifications_ = 0;
158   last_time_ns_saver_woke_up_ = NanoTime();
159   period_condition_.Signal(Thread::Current());
160 }
161 
NotifyJitActivityInternal()162 void ProfileSaver::NotifyJitActivityInternal() {
163   // Unlikely to overflow but if it happens,
164   // we would have waken up the saver long before that.
165   jit_activity_notifications_++;
166   // Note that we are not as precise as we could be here but we don't want to wake the saver
167   // every time we see a hot method.
168   if (jit_activity_notifications_ > options_.GetMinNotificationBeforeWake()) {
169     MutexLock wait_mutex(Thread::Current(), wait_lock_);
170     if ((NanoTime() - last_time_ns_saver_woke_up_) > MsToNs(options_.GetMinSavePeriodMs())) {
171       WakeUpSaver();
172     } else if (jit_activity_notifications_ > options_.GetMaxNotificationBeforeWake()) {
173       // Make sure to wake up the saver if we see a spike in the number of notifications.
174       // This is a precaution to avoid losing a big number of methods in case
175       // this is a spike with no jit after.
176       total_number_of_hot_spikes_++;
177       WakeUpSaver();
178     }
179   }
180 }
181 
182 // Get resolved methods that have a profile info or more than kStartupMethodSamples samples.
183 // Excludes native methods and classes in the boot image.
184 class GetMethodsVisitor : public ClassVisitor {
185  public:
GetMethodsVisitor(std::vector<MethodReference> * methods,uint32_t startup_method_samples)186   GetMethodsVisitor(std::vector<MethodReference>* methods, uint32_t startup_method_samples)
187     : methods_(methods),
188       startup_method_samples_(startup_method_samples) {}
189 
operator ()(ObjPtr<mirror::Class> klass)190   virtual bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
191     if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass) ||
192         !klass->IsResolved() ||
193         klass->IsErroneousResolved()) {
194       return true;
195     }
196     for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
197       if (!method.IsNative()) {
198         if (method.GetCounter() >= startup_method_samples_ ||
199             method.GetProfilingInfo(kRuntimePointerSize) != nullptr) {
200           // Have samples, add to profile.
201           const DexFile* dex_file =
202               method.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetDexFile();
203           methods_->push_back(MethodReference(dex_file, method.GetDexMethodIndex()));
204         }
205       }
206     }
207     return true;
208   }
209 
210  private:
211   std::vector<MethodReference>* const methods_;
212   uint32_t startup_method_samples_;
213 };
214 
FetchAndCacheResolvedClassesAndMethods()215 void ProfileSaver::FetchAndCacheResolvedClassesAndMethods() {
216   ScopedTrace trace(__PRETTY_FUNCTION__);
217 
218   // Resolve any new registered locations.
219   ResolveTrackedLocations();
220 
221   Thread* const self = Thread::Current();
222   std::vector<MethodReference> methods;
223   std::set<DexCacheResolvedClasses> resolved_classes;
224   {
225     ScopedObjectAccess soa(self);
226     gc::ScopedGCCriticalSection sgcs(self,
227                                      gc::kGcCauseProfileSaver,
228                                      gc::kCollectorTypeCriticalSection);
229 
230     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
231     resolved_classes = class_linker->GetResolvedClasses(/*ignore boot classes*/ true);
232 
233     {
234       ScopedTrace trace2("Get hot methods");
235       GetMethodsVisitor visitor(&methods, options_.GetStartupMethodSamples());
236       class_linker->VisitClasses(&visitor);
237       VLOG(profiler) << "Methods with samples greater than "
238                      << options_.GetStartupMethodSamples() << " = " << methods.size();
239     }
240   }
241   MutexLock mu(self, *Locks::profiler_lock_);
242   uint64_t total_number_of_profile_entries_cached = 0;
243 
244   for (const auto& it : tracked_dex_base_locations_) {
245     std::set<DexCacheResolvedClasses> resolved_classes_for_location;
246     const std::string& filename = it.first;
247     const std::set<std::string>& locations = it.second;
248     std::vector<ProfileMethodInfo> profile_methods_for_location;
249     for (const MethodReference& ref : methods) {
250       if (locations.find(ref.dex_file->GetBaseLocation()) != locations.end()) {
251         profile_methods_for_location.emplace_back(ref.dex_file, ref.dex_method_index);
252       }
253     }
254     for (const DexCacheResolvedClasses& classes : resolved_classes) {
255       if (locations.find(classes.GetBaseLocation()) != locations.end()) {
256         VLOG(profiler) << "Added " << classes.GetClasses().size() << " classes for location "
257                        << classes.GetBaseLocation() << " (" << classes.GetDexLocation() << ")";
258         resolved_classes_for_location.insert(classes);
259       } else {
260         VLOG(profiler) << "Location not found " << classes.GetBaseLocation()
261                        << " (" << classes.GetDexLocation() << ")";
262       }
263     }
264     auto info_it = profile_cache_.Put(
265         filename,
266         new ProfileCompilationInfo(Runtime::Current()->GetArenaPool()));
267 
268     ProfileCompilationInfo* cached_info = info_it->second;
269     cached_info->AddMethodsAndClasses(profile_methods_for_location,
270                                       resolved_classes_for_location);
271     total_number_of_profile_entries_cached += resolved_classes_for_location.size();
272   }
273   max_number_of_profile_entries_cached_ = std::max(
274       max_number_of_profile_entries_cached_,
275       total_number_of_profile_entries_cached);
276 }
277 
ProcessProfilingInfo(bool force_save,uint16_t * number_of_new_methods)278 bool ProfileSaver::ProcessProfilingInfo(bool force_save, /*out*/uint16_t* number_of_new_methods) {
279   ScopedTrace trace(__PRETTY_FUNCTION__);
280 
281   // Resolve any new registered locations.
282   ResolveTrackedLocations();
283 
284   SafeMap<std::string, std::set<std::string>> tracked_locations;
285   {
286     // Make a copy so that we don't hold the lock while doing I/O.
287     MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
288     tracked_locations = tracked_dex_base_locations_;
289   }
290 
291   bool profile_file_saved = false;
292   if (number_of_new_methods != nullptr) {
293     *number_of_new_methods = 0;
294   }
295 
296   for (const auto& it : tracked_locations) {
297     if (!force_save && ShuttingDown(Thread::Current())) {
298       // The ProfileSaver is in shutdown mode, meaning a stop request was made and
299       // we need to exit cleanly (by waiting for the saver thread to finish). Unless
300       // we have a request for a forced save, do not do any processing so that we
301       // speed up the exit.
302       return true;
303     }
304     const std::string& filename = it.first;
305     const std::set<std::string>& locations = it.second;
306     std::vector<ProfileMethodInfo> profile_methods;
307     {
308       ScopedObjectAccess soa(Thread::Current());
309       jit_code_cache_->GetProfiledMethods(locations, profile_methods);
310       total_number_of_code_cache_queries_++;
311     }
312     {
313       ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
314       if (!info.Load(filename, /*clear_if_invalid*/ true)) {
315         LOG(WARNING) << "Could not forcefully load profile " << filename;
316         continue;
317       }
318       uint64_t last_save_number_of_methods = info.GetNumberOfMethods();
319       uint64_t last_save_number_of_classes = info.GetNumberOfResolvedClasses();
320 
321       info.AddMethodsAndClasses(profile_methods,
322                                 std::set<DexCacheResolvedClasses>());
323       auto profile_cache_it = profile_cache_.find(filename);
324       if (profile_cache_it != profile_cache_.end()) {
325         info.MergeWith(*(profile_cache_it->second));
326       }
327 
328       int64_t delta_number_of_methods =
329           info.GetNumberOfMethods() - last_save_number_of_methods;
330       int64_t delta_number_of_classes =
331           info.GetNumberOfResolvedClasses() - last_save_number_of_classes;
332 
333       if (!force_save &&
334           delta_number_of_methods < options_.GetMinMethodsToSave() &&
335           delta_number_of_classes < options_.GetMinClassesToSave()) {
336         VLOG(profiler) << "Not enough information to save to: " << filename
337                        << " Number of methods: " << delta_number_of_methods
338                        << " Number of classes: " << delta_number_of_classes;
339         total_number_of_skipped_writes_++;
340         continue;
341       }
342       if (number_of_new_methods != nullptr) {
343         *number_of_new_methods =
344             std::max(static_cast<uint16_t>(delta_number_of_methods),
345                      *number_of_new_methods);
346       }
347       uint64_t bytes_written;
348       // Force the save. In case the profile data is corrupted or the the profile
349       // has the wrong version this will "fix" the file to the correct format.
350       if (info.Save(filename, &bytes_written)) {
351         // We managed to save the profile. Clear the cache stored during startup.
352         if (profile_cache_it != profile_cache_.end()) {
353           ProfileCompilationInfo *cached_info = profile_cache_it->second;
354           profile_cache_.erase(profile_cache_it);
355           delete cached_info;
356         }
357         if (bytes_written > 0) {
358           total_number_of_writes_++;
359           total_bytes_written_ += bytes_written;
360           profile_file_saved = true;
361         } else {
362           // At this point we could still have avoided the write.
363           // We load and merge the data from the file lazily at its first ever
364           // save attempt. So, whatever we are trying to save could already be
365           // in the file.
366           total_number_of_skipped_writes_++;
367         }
368       } else {
369         LOG(WARNING) << "Could not save profiling info to " << filename;
370         total_number_of_failed_writes_++;
371       }
372     }
373     // Trim the maps to madvise the pages used for profile info.
374     // It is unlikely we will need them again in the near feature.
375     Runtime::Current()->GetArenaPool()->TrimMaps();
376   }
377 
378   return profile_file_saved;
379 }
380 
RunProfileSaverThread(void * arg)381 void* ProfileSaver::RunProfileSaverThread(void* arg) {
382   Runtime* runtime = Runtime::Current();
383 
384   bool attached = runtime->AttachCurrentThread("Profile Saver",
385                                                /*as_daemon*/true,
386                                                runtime->GetSystemThreadGroup(),
387                                                /*create_peer*/true);
388   if (!attached) {
389     CHECK(runtime->IsShuttingDown(Thread::Current()));
390     return nullptr;
391   }
392 
393   ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
394   profile_saver->Run();
395 
396   runtime->DetachCurrentThread();
397   VLOG(profiler) << "Profile saver shutdown";
398   return nullptr;
399 }
400 
ShouldProfileLocation(const std::string & location)401 static bool ShouldProfileLocation(const std::string& location) {
402   OatFileManager& oat_manager = Runtime::Current()->GetOatFileManager();
403   const OatFile* oat_file = oat_manager.FindOpenedOatFileFromDexLocation(location);
404   if (oat_file == nullptr) {
405     // This can happen if we fallback to run code directly from the APK.
406     // Profile it with the hope that the background dexopt will get us back into
407     // a good state.
408     VLOG(profiler) << "Asked to profile a location without an oat file:" << location;
409     return true;
410   }
411   CompilerFilter::Filter filter = oat_file->GetCompilerFilter();
412   if ((filter == CompilerFilter::kSpeed) || (filter == CompilerFilter::kEverything)) {
413     VLOG(profiler)
414         << "Skip profiling oat file because it's already speed|everything compiled: "
415         << location << " oat location: " << oat_file->GetLocation();
416     return false;
417   }
418   return true;
419 }
420 
Start(const ProfileSaverOptions & options,const std::string & output_filename,jit::JitCodeCache * jit_code_cache,const std::vector<std::string> & code_paths)421 void ProfileSaver::Start(const ProfileSaverOptions& options,
422                          const std::string& output_filename,
423                          jit::JitCodeCache* jit_code_cache,
424                          const std::vector<std::string>& code_paths) {
425   DCHECK(options.IsEnabled());
426   DCHECK(Runtime::Current()->GetJit() != nullptr);
427   DCHECK(!output_filename.empty());
428   DCHECK(jit_code_cache != nullptr);
429 
430   std::vector<std::string> code_paths_to_profile;
431 
432   for (const std::string& location : code_paths) {
433     if (ShouldProfileLocation(location))  {
434       code_paths_to_profile.push_back(location);
435     }
436   }
437   if (code_paths_to_profile.empty()) {
438     VLOG(profiler) << "No code paths should be profiled.";
439     return;
440   }
441 
442   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
443   if (instance_ != nullptr) {
444     // If we already have an instance, make sure it uses the same jit_code_cache.
445     // This may be called multiple times via Runtime::registerAppInfo (e.g. for
446     // apps which share the same runtime).
447     DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
448     // Add the code_paths to the tracked locations.
449     instance_->AddTrackedLocations(output_filename, code_paths_to_profile);
450     return;
451   }
452 
453   VLOG(profiler) << "Starting profile saver using output file: " << output_filename
454       << ". Tracking: " << android::base::Join(code_paths_to_profile, ':');
455 
456   instance_ = new ProfileSaver(options,
457                                output_filename,
458                                jit_code_cache,
459                                code_paths_to_profile);
460 
461   // Create a new thread which does the saving.
462   CHECK_PTHREAD_CALL(
463       pthread_create,
464       (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
465       "Profile saver thread");
466 
467 #if defined(ART_TARGET_ANDROID)
468   // At what priority to schedule the saver threads. 9 is the lowest foreground priority on device.
469   static constexpr int kProfileSaverPthreadPriority = 9;
470   int result = setpriority(
471       PRIO_PROCESS, pthread_gettid_np(profiler_pthread_), kProfileSaverPthreadPriority);
472   if (result != 0) {
473     PLOG(ERROR) << "Failed to setpriority to :" << kProfileSaverPthreadPriority;
474   }
475 #endif
476 }
477 
Stop(bool dump_info)478 void ProfileSaver::Stop(bool dump_info) {
479   ProfileSaver* profile_saver = nullptr;
480   pthread_t profiler_pthread = 0U;
481 
482   {
483     MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
484     VLOG(profiler) << "Stopping profile saver thread";
485     profile_saver = instance_;
486     profiler_pthread = profiler_pthread_;
487     if (instance_ == nullptr) {
488       DCHECK(false) << "Tried to stop a profile saver which was not started";
489       return;
490     }
491     if (instance_->shutting_down_) {
492       DCHECK(false) << "Tried to stop the profile saver twice";
493       return;
494     }
495     instance_->shutting_down_ = true;
496   }
497 
498   {
499     // Wake up the saver thread if it is sleeping to allow for a clean exit.
500     MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
501     profile_saver->period_condition_.Signal(Thread::Current());
502   }
503 
504   // Wait for the saver thread to stop.
505   CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
506 
507   // Force save everything before destroying the instance.
508   instance_->ProcessProfilingInfo(/*force_save*/true, /*number_of_new_methods*/nullptr);
509 
510   {
511     MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
512     if (dump_info) {
513       instance_->DumpInfo(LOG_STREAM(INFO));
514     }
515     instance_ = nullptr;
516     profiler_pthread_ = 0U;
517   }
518   delete profile_saver;
519 }
520 
ShuttingDown(Thread * self)521 bool ProfileSaver::ShuttingDown(Thread* self) {
522   MutexLock mu(self, *Locks::profiler_lock_);
523   return shutting_down_;
524 }
525 
IsStarted()526 bool ProfileSaver::IsStarted() {
527   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
528   return instance_ != nullptr;
529 }
530 
AddTrackedLocationsToMap(const std::string & output_filename,const std::vector<std::string> & code_paths,SafeMap<std::string,std::set<std::string>> * map)531 static void AddTrackedLocationsToMap(const std::string& output_filename,
532                                      const std::vector<std::string>& code_paths,
533                                      SafeMap<std::string, std::set<std::string>>* map) {
534   auto it = map->find(output_filename);
535   if (it == map->end()) {
536     map->Put(output_filename, std::set<std::string>(code_paths.begin(), code_paths.end()));
537   } else {
538     it->second.insert(code_paths.begin(), code_paths.end());
539   }
540 }
541 
AddTrackedLocations(const std::string & output_filename,const std::vector<std::string> & code_paths)542 void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
543                                        const std::vector<std::string>& code_paths) {
544   // Add the code paths to the list of tracked location.
545   AddTrackedLocationsToMap(output_filename, code_paths, &tracked_dex_base_locations_);
546   // The code paths may contain symlinks which could fool the profiler.
547   // If the dex file is compiled with an absolute location but loaded with symlink
548   // the profiler could skip the dex due to location mismatch.
549   // To avoid this, we add the code paths to the temporary cache of 'to_be_resolved'
550   // locations. When the profiler thread executes we will resolve the paths to their
551   // real paths.
552   // Note that we delay taking the realpath to avoid spending more time than needed
553   // when registering location (as it is done during app launch).
554   AddTrackedLocationsToMap(output_filename,
555                            code_paths,
556                            &tracked_dex_base_locations_to_be_resolved_);
557 }
558 
DumpInstanceInfo(std::ostream & os)559 void ProfileSaver::DumpInstanceInfo(std::ostream& os) {
560   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
561   if (instance_ != nullptr) {
562     instance_->DumpInfo(os);
563   }
564 }
565 
DumpInfo(std::ostream & os)566 void ProfileSaver::DumpInfo(std::ostream& os) {
567   os << "ProfileSaver total_bytes_written=" << total_bytes_written_ << '\n'
568      << "ProfileSaver total_number_of_writes=" << total_number_of_writes_ << '\n'
569      << "ProfileSaver total_number_of_code_cache_queries="
570      << total_number_of_code_cache_queries_ << '\n'
571      << "ProfileSaver total_number_of_skipped_writes=" << total_number_of_skipped_writes_ << '\n'
572      << "ProfileSaver total_number_of_failed_writes=" << total_number_of_failed_writes_ << '\n'
573      << "ProfileSaver total_ms_of_sleep=" << total_ms_of_sleep_ << '\n'
574      << "ProfileSaver total_ms_of_work=" << NsToMs(total_ns_of_work_) << '\n'
575      << "ProfileSaver max_number_profile_entries_cached="
576      << max_number_of_profile_entries_cached_ << '\n'
577      << "ProfileSaver total_number_of_hot_spikes=" << total_number_of_hot_spikes_ << '\n'
578      << "ProfileSaver total_number_of_wake_ups=" << total_number_of_wake_ups_ << '\n';
579 }
580 
581 
ForceProcessProfiles()582 void ProfileSaver::ForceProcessProfiles() {
583   ProfileSaver* saver = nullptr;
584   {
585     MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
586     saver = instance_;
587   }
588   // TODO(calin): this is not actually thread safe as the instance_ may have been deleted,
589   // but we only use this in testing when we now this won't happen.
590   // Refactor the way we handle the instance so that we don't end up in this situation.
591   if (saver != nullptr) {
592     saver->ProcessProfilingInfo(/*force_save*/true, /*number_of_new_methods*/nullptr);
593   }
594 }
595 
HasSeenMethod(const std::string & profile,const DexFile * dex_file,uint16_t method_idx)596 bool ProfileSaver::HasSeenMethod(const std::string& profile,
597                                  const DexFile* dex_file,
598                                  uint16_t method_idx) {
599   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
600   if (instance_ != nullptr) {
601     ProfileCompilationInfo info(Runtime::Current()->GetArenaPool());
602     if (!info.Load(profile, /*clear_if_invalid*/false)) {
603       return false;
604     }
605     return info.ContainsMethod(MethodReference(dex_file, method_idx));
606   }
607   return false;
608 }
609 
ResolveTrackedLocations()610 void ProfileSaver::ResolveTrackedLocations() {
611   SafeMap<std::string, std::set<std::string>> locations_to_be_resolved;
612   {
613     // Make a copy so that we don't hold the lock while doing I/O.
614     MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
615     locations_to_be_resolved = tracked_dex_base_locations_to_be_resolved_;
616     tracked_dex_base_locations_to_be_resolved_.clear();
617   }
618 
619   // Resolve the locations.
620   SafeMap<std::string, std::vector<std::string>> resolved_locations_map;
621   for (const auto& it : locations_to_be_resolved) {
622     const std::string& filename = it.first;
623     const std::set<std::string>& locations = it.second;
624     auto resolved_locations_it = resolved_locations_map.Put(
625         filename,
626         std::vector<std::string>(locations.size()));
627 
628     for (const auto& location : locations) {
629       UniqueCPtr<const char[]> location_real(realpath(location.c_str(), nullptr));
630       // Note that it's ok if we cannot get the real path.
631       if (location_real != nullptr) {
632         resolved_locations_it->second.emplace_back(location_real.get());
633       }
634     }
635   }
636 
637   // Add the resolved locations to the tracked collection.
638   MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
639   for (const auto& it : resolved_locations_map) {
640     AddTrackedLocationsToMap(it.first, it.second, &tracked_dex_base_locations_);
641   }
642 }
643 
644 }   // namespace art
645