blob: b35c958b0b7d3255aa636cd1d9cc4f76887f0e06 [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 Juravlec90bc922016-02-24 10:13:09 +000019#include <sys/types.h>
20#include <sys/stat.h>
21#include <fcntl.h>
22
Calin Juravle4d77b6a2015-12-01 18:38:09 +000023#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070024#include "base/enums.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle050fb1b2016-03-25 17:17:09 +000026#include "base/time_utils.h"
27#include "compiler_filter.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000028#include "oat_file_manager.h"
Calin Juravle050fb1b2016-03-25 17:17:09 +000029#include "scoped_thread_state_change.h"
30
Calin Juravle4d77b6a2015-12-01 18:38:09 +000031
32namespace art {
33
Calin Juravle4d77b6a2015-12-01 18:38:09 +000034ProfileSaver* ProfileSaver::instance_ = nullptr;
35pthread_t ProfileSaver::profiler_pthread_ = 0U;
36
Calin Juravle138dbff2016-06-28 19:36:58 +010037ProfileSaver::ProfileSaver(const ProfileSaverOptions& options,
38 const std::string& output_filename,
Calin Juravle4d77b6a2015-12-01 18:38:09 +000039 jit::JitCodeCache* jit_code_cache,
Calin Juravlec90bc922016-02-24 10:13:09 +000040 const std::vector<std::string>& code_paths,
41 const std::string& foreign_dex_profile_path,
42 const std::string& app_data_dir)
Calin Juravleb4eddd22016-01-13 15:52:33 -080043 : jit_code_cache_(jit_code_cache),
Calin Juravlec90bc922016-02-24 10:13:09 +000044 foreign_dex_profile_path_(foreign_dex_profile_path),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000045 shutting_down_(false),
Calin Juravle67265462016-03-18 16:23:40 +000046 last_save_number_of_methods_(0),
Calin Juravle698f4d12016-03-30 18:18:58 +010047 last_save_number_of_classes_(0),
Calin Juravlea2638922016-04-29 16:44:11 +010048 last_time_ns_saver_woke_up_(0),
49 jit_activity_notifications_(0),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000050 wait_lock_("ProfileSaver wait lock"),
Calin Juravleb8e69992016-03-09 15:37:48 +000051 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),
Calin Juravle67265462016-03-18 16:23:40 +000057 total_ms_of_sleep_(0),
Calin Juravleb8e69992016-03-09 15:37:48 +000058 total_ns_of_work_(0),
Calin Juravle67265462016-03-18 16:23:40 +000059 total_number_of_foreign_dex_marks_(0),
Calin Juravlea2638922016-04-29 16:44:11 +010060 max_number_of_profile_entries_cached_(0),
61 total_number_of_hot_spikes_(0),
Calin Juravle138dbff2016-06-28 19:36:58 +010062 total_number_of_wake_ups_(0),
63 options_(options) {
64 DCHECK(options_.IsEnabled());
Calin Juravle20b7e3b2016-04-18 18:59:22 +010065 AddTrackedLocations(output_filename, app_data_dir, code_paths);
Calin Juravlec90bc922016-02-24 10:13:09 +000066 if (!app_data_dir.empty()) {
67 // The application directory is used to determine which dex files are owned by app.
68 // Since it could be a symlink (e.g. /data/data instead of /data/user/0), and we
69 // don't have control over how the dex files are actually loaded (symlink or canonical path),
70 // store it's canonical form to be sure we use the same base when comparing.
71 UniqueCPtr<const char[]> app_data_dir_real_path(realpath(app_data_dir.c_str(), nullptr));
72 if (app_data_dir_real_path != nullptr) {
Calin Juravle20b7e3b2016-04-18 18:59:22 +010073 app_data_dirs_.emplace(app_data_dir_real_path.get());
Calin Juravlec90bc922016-02-24 10:13:09 +000074 } else {
Calin Juravle20b7e3b2016-04-18 18:59:22 +010075 LOG(WARNING) << "Failed to get the real path for app dir: " << app_data_dir
Calin Juravlec90bc922016-02-24 10:13:09 +000076 << ". The app dir will not be used to determine which dex files belong to the app";
77 }
78 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000079}
80
81void ProfileSaver::Run() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +000082 Thread* self = Thread::Current();
83
Calin Juravlea2638922016-04-29 16:44:11 +010084 // Fetch the resolved classes for the app images after sleeping for
Calin Juravle138dbff2016-06-28 19:36:58 +010085 // options_.GetSaveResolvedClassesDelayMs().
Calin Juravlea2638922016-04-29 16:44:11 +010086 // TODO(calin) This only considers the case of the primary profile file.
87 // Anything that gets loaded in the same VM will not have their resolved
88 // classes save (unless they started before the initial saving was done).
89 {
90 MutexLock mu(self, wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +010091 const uint64_t end_time = NanoTime() + MsToNs(options_.GetSaveResolvedClassesDelayMs());
Mathieu Chartiera57305e2016-05-18 19:51:23 -070092 while (true) {
93 const uint64_t current_time = NanoTime();
94 if (current_time >= end_time) {
95 break;
96 }
97 period_condition_.TimedWait(self, NsToMs(end_time - current_time), 0);
98 }
Calin Juravle138dbff2016-06-28 19:36:58 +010099 total_ms_of_sleep_ += options_.GetSaveResolvedClassesDelayMs();
Calin Juravlea2638922016-04-29 16:44:11 +0100100 }
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700101 FetchAndCacheResolvedClassesAndMethods();
Calin Juravlea2638922016-04-29 16:44:11 +0100102
103 // Loop for the profiled methods.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800104 while (!ShuttingDown(self)) {
Calin Juravlea2638922016-04-29 16:44:11 +0100105 uint64_t sleep_start = NanoTime();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000106 {
Calin Juravle8fbea8e2016-05-18 15:49:36 -0700107 uint64_t sleep_time = 0;
108 {
109 MutexLock mu(self, wait_lock_);
110 period_condition_.Wait(self);
Calin Juravle5d04eb62016-05-25 18:09:53 +0100111 sleep_time = NanoTime() - sleep_start;
Calin Juravle8fbea8e2016-05-18 15:49:36 -0700112 }
113 // Check if the thread was woken up for shutdown.
114 if (ShuttingDown(self)) {
115 break;
116 }
Calin Juravlea2638922016-04-29 16:44:11 +0100117 total_number_of_wake_ups_++;
118 // We might have been woken up by a huge number of notifications to guarantee saving.
119 // If we didn't meet the minimum saving period go back to sleep (only if missed by
120 // a reasonable margin).
Calin Juravle138dbff2016-06-28 19:36:58 +0100121 uint64_t min_save_period_ns = MsToNs(options_.GetMinSavePeriodMs());
122 while (min_save_period_ns * 0.9 > sleep_time) {
Calin Juravle8fbea8e2016-05-18 15:49:36 -0700123 {
124 MutexLock mu(self, wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +0100125 period_condition_.TimedWait(self, NsToMs(min_save_period_ns - sleep_time), 0);
Calin Juravle5d04eb62016-05-25 18:09:53 +0100126 sleep_time = NanoTime() - sleep_start;
Calin Juravle8fbea8e2016-05-18 15:49:36 -0700127 }
128 // Check if the thread was woken up for shutdown.
129 if (ShuttingDown(self)) {
130 break;
131 }
Calin Juravlea2638922016-04-29 16:44:11 +0100132 total_number_of_wake_ups_++;
Calin Juravlea2638922016-04-29 16:44:11 +0100133 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000134 }
Calin Juravlea2638922016-04-29 16:44:11 +0100135 total_ms_of_sleep_ += NsToMs(NanoTime() - sleep_start);
136
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000137 if (ShuttingDown(self)) {
138 break;
139 }
140
Calin Juravlea2638922016-04-29 16:44:11 +0100141 uint16_t new_methods = 0;
142 uint64_t start_work = NanoTime();
143 bool profile_saved_to_disk = ProcessProfilingInfo(&new_methods);
144 // Update the notification counter based on result. Note that there might be contention on this
145 // but we don't care about to be 100% precise.
146 if (!profile_saved_to_disk) {
147 // If we didn't save to disk it may be because we didn't have enough new methods.
148 // Set the jit activity notifications to new_methods so we can wake up earlier if needed.
149 jit_activity_notifications_ = new_methods;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000150 }
Calin Juravlea2638922016-04-29 16:44:11 +0100151 total_ns_of_work_ += NanoTime() - start_work;
152 }
153}
Calin Juravleb8e69992016-03-09 15:37:48 +0000154
Calin Juravlea2638922016-04-29 16:44:11 +0100155void ProfileSaver::NotifyJitActivity() {
156 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
157 if (instance_ == nullptr || instance_->shutting_down_) {
158 return;
159 }
160 instance_->NotifyJitActivityInternal();
161}
162
163void ProfileSaver::WakeUpSaver() {
164 jit_activity_notifications_ = 0;
165 last_time_ns_saver_woke_up_ = NanoTime();
166 period_condition_.Signal(Thread::Current());
167}
168
169void ProfileSaver::NotifyJitActivityInternal() {
170 // Unlikely to overflow but if it happens,
171 // we would have waken up the saver long before that.
172 jit_activity_notifications_++;
173 // Note that we are not as precise as we could be here but we don't want to wake the saver
174 // every time we see a hot method.
Calin Juravle138dbff2016-06-28 19:36:58 +0100175 if (jit_activity_notifications_ > options_.GetMinNotificationBeforeWake()) {
Calin Juravlea2638922016-04-29 16:44:11 +0100176 MutexLock wait_mutex(Thread::Current(), wait_lock_);
Calin Juravle138dbff2016-06-28 19:36:58 +0100177 if ((NanoTime() - last_time_ns_saver_woke_up_) > MsToNs(options_.GetMinSavePeriodMs())) {
Calin Juravlea2638922016-04-29 16:44:11 +0100178 WakeUpSaver();
Serguei Katkov87de9cf2016-08-01 17:47:04 +0700179 } else if (jit_activity_notifications_ > options_.GetMaxNotificationBeforeWake()) {
180 // Make sure to wake up the saver if we see a spike in the number of notifications.
181 // This is a precaution to avoid losing a big number of methods in case
182 // this is a spike with no jit after.
183 total_number_of_hot_spikes_++;
184 WakeUpSaver();
Calin Juravlea2638922016-04-29 16:44:11 +0100185 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000186 }
187}
188
Calin Juravle67265462016-03-18 16:23:40 +0000189ProfileCompilationInfo* ProfileSaver::GetCachedProfiledInfo(const std::string& filename) {
190 auto info_it = profile_cache_.find(filename);
191 if (info_it == profile_cache_.end()) {
192 info_it = profile_cache_.Put(filename, ProfileCompilationInfo());
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000193 }
Calin Juravle67265462016-03-18 16:23:40 +0000194 return &info_it->second;
195}
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000196
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700197// Get resolved methods that have a profile info or more than kStartupMethodSamples samples.
198// Excludes native methods and classes in the boot image.
199class GetMethodsVisitor : public ClassVisitor {
200 public:
Calin Juravle138dbff2016-06-28 19:36:58 +0100201 GetMethodsVisitor(std::vector<MethodReference>* methods, uint32_t startup_method_samples)
202 : methods_(methods),
203 startup_method_samples_(startup_method_samples) {}
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700204
205 virtual bool operator()(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
206 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
207 return true;
208 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700209 for (ArtMethod& method : klass->GetMethods(kRuntimePointerSize)) {
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700210 if (!method.IsNative()) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100211 if (method.GetCounter() >= startup_method_samples_ ||
Andreas Gampe542451c2016-07-26 09:02:02 -0700212 method.GetProfilingInfo(kRuntimePointerSize) != nullptr) {
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700213 // Have samples, add to profile.
Andreas Gampe542451c2016-07-26 09:02:02 -0700214 const DexFile* dex_file =
215 method.GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetDexFile();
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700216 methods_->push_back(MethodReference(dex_file, method.GetDexMethodIndex()));
217 }
218 }
219 }
220 return true;
221 }
222
223 private:
224 std::vector<MethodReference>* const methods_;
Calin Juravle138dbff2016-06-28 19:36:58 +0100225 uint32_t startup_method_samples_;
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700226};
227
228void ProfileSaver::FetchAndCacheResolvedClassesAndMethods() {
Calin Juravle67265462016-03-18 16:23:40 +0000229 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle67265462016-03-18 16:23:40 +0000230 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
231 std::set<DexCacheResolvedClasses> resolved_classes =
232 class_linker->GetResolvedClasses(/*ignore boot classes*/ true);
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700233
234 std::vector<MethodReference> methods;
235 {
236 ScopedTrace trace2("Get hot methods");
Calin Juravle138dbff2016-06-28 19:36:58 +0100237 GetMethodsVisitor visitor(&methods, options_.GetStartupMethodSamples());
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700238 ScopedObjectAccess soa(Thread::Current());
239 class_linker->VisitClasses(&visitor);
240 VLOG(profiler) << "Methods with samples greater than "
Calin Juravle138dbff2016-06-28 19:36:58 +0100241 << options_.GetStartupMethodSamples() << " = " << methods.size();
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700242 }
Calin Juravle67265462016-03-18 16:23:40 +0000243 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
244 uint64_t total_number_of_profile_entries_cached = 0;
Mathieu Chartierb384e5e2016-04-29 12:03:56 -0700245
Calin Juravle67265462016-03-18 16:23:40 +0000246 for (const auto& it : tracked_dex_base_locations_) {
Mathieu Chartierb384e5e2016-04-29 12:03:56 -0700247 std::set<DexCacheResolvedClasses> resolved_classes_for_location;
Calin Juravle67265462016-03-18 16:23:40 +0000248 const std::string& filename = it.first;
249 const std::set<std::string>& locations = it.second;
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700250 std::vector<MethodReference> methods_for_location;
251 for (const MethodReference& ref : methods) {
252 if (locations.find(ref.dex_file->GetBaseLocation()) != locations.end()) {
253 methods_for_location.push_back(ref);
254 }
255 }
Calin Juravle67265462016-03-18 16:23:40 +0000256 for (const DexCacheResolvedClasses& classes : resolved_classes) {
Mathieu Chartierb384e5e2016-04-29 12:03:56 -0700257 if (locations.find(classes.GetBaseLocation()) != locations.end()) {
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700258 VLOG(profiler) << "Added " << classes.GetClasses().size() << " classes for location "
259 << classes.GetBaseLocation() << " (" << classes.GetDexLocation() << ")";
Calin Juravle67265462016-03-18 16:23:40 +0000260 resolved_classes_for_location.insert(classes);
Mathieu Chartierb384e5e2016-04-29 12:03:56 -0700261 } else {
262 VLOG(profiler) << "Location not found " << classes.GetBaseLocation()
263 << " (" << classes.GetDexLocation() << ")";
Calin Juravle67265462016-03-18 16:23:40 +0000264 }
265 }
266 ProfileCompilationInfo* info = GetCachedProfiledInfo(filename);
Mathieu Chartier27ed3a42016-05-18 08:51:52 -0700267 info->AddMethodsAndClasses(methods_for_location, resolved_classes_for_location);
Calin Juravle67265462016-03-18 16:23:40 +0000268 total_number_of_profile_entries_cached += resolved_classes_for_location.size();
269 }
270 max_number_of_profile_entries_cached_ = std::max(
271 max_number_of_profile_entries_cached_,
272 total_number_of_profile_entries_cached);
273}
274
Calin Juravlea2638922016-04-29 16:44:11 +0100275bool ProfileSaver::ProcessProfilingInfo(uint16_t* new_methods) {
Calin Juravle67265462016-03-18 16:23:40 +0000276 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800277 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000278 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800279 // Make a copy so that we don't hold the lock while doing I/O.
280 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
281 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000282 }
Calin Juravleb9c1b9b2016-03-17 17:07:52 +0000283
Calin Juravle67265462016-03-18 16:23:40 +0000284 bool profile_file_saved = false;
285 uint64_t total_number_of_profile_entries_cached = 0;
Calin Juravlea2638922016-04-29 16:44:11 +0100286 *new_methods = 0;
287
Calin Juravleb4eddd22016-01-13 15:52:33 -0800288 for (const auto& it : tracked_locations) {
289 if (ShuttingDown(Thread::Current())) {
290 return true;
291 }
292 const std::string& filename = it.first;
293 const std::set<std::string>& locations = it.second;
Calin Juravle99629622016-04-19 16:33:46 +0100294 std::vector<MethodReference> methods;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800295 {
296 ScopedObjectAccess soa(Thread::Current());
Calin Juravle99629622016-04-19 16:33:46 +0100297 jit_code_cache_->GetProfiledMethods(locations, methods);
Calin Juravleb8e69992016-03-09 15:37:48 +0000298 total_number_of_code_cache_queries_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800299 }
Calin Juravleb9c1b9b2016-03-17 17:07:52 +0000300
Calin Juravle67265462016-03-18 16:23:40 +0000301 ProfileCompilationInfo* cached_info = GetCachedProfiledInfo(filename);
302 cached_info->AddMethodsAndClasses(methods, std::set<DexCacheResolvedClasses>());
Calin Juravle698f4d12016-03-30 18:18:58 +0100303 int64_t delta_number_of_methods =
304 cached_info->GetNumberOfMethods() -
305 static_cast<int64_t>(last_save_number_of_methods_);
306 int64_t delta_number_of_classes =
307 cached_info->GetNumberOfResolvedClasses() -
308 static_cast<int64_t>(last_save_number_of_classes_);
Calin Juravle67265462016-03-18 16:23:40 +0000309
Calin Juravle138dbff2016-06-28 19:36:58 +0100310 if (delta_number_of_methods < options_.GetMinMethodsToSave() &&
311 delta_number_of_classes < options_.GetMinClassesToSave()) {
Calin Juravle698f4d12016-03-30 18:18:58 +0100312 VLOG(profiler) << "Not enough information to save to: " << filename
Calin Juravle138dbff2016-06-28 19:36:58 +0100313 << " Number of methods: " << delta_number_of_methods
314 << " Number of classes: " << delta_number_of_classes;
Calin Juravleb8e69992016-03-09 15:37:48 +0000315 total_number_of_skipped_writes_++;
Calin Juravle67265462016-03-18 16:23:40 +0000316 continue;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800317 }
Calin Juravlea2638922016-04-29 16:44:11 +0100318 *new_methods = std::max(static_cast<uint16_t>(delta_number_of_methods), *new_methods);
Calin Juravleb8e69992016-03-09 15:37:48 +0000319 uint64_t bytes_written;
Calin Juravle5d1bd0a2016-03-24 20:33:22 +0000320 // Force the save. In case the profile data is corrupted or the the profile
321 // has the wrong version this will "fix" the file to the correct format.
322 if (cached_info->MergeAndSave(filename, &bytes_written, /*force*/ true)) {
Calin Juravle67265462016-03-18 16:23:40 +0000323 last_save_number_of_methods_ = cached_info->GetNumberOfMethods();
Calin Juravle698f4d12016-03-30 18:18:58 +0100324 last_save_number_of_classes_ = cached_info->GetNumberOfResolvedClasses();
Calin Juravle67265462016-03-18 16:23:40 +0000325 // Clear resolved classes. No need to store them around as
326 // they don't change after the first write.
327 cached_info->ClearResolvedClasses();
Calin Juravleb8e69992016-03-09 15:37:48 +0000328 if (bytes_written > 0) {
329 total_number_of_writes_++;
330 total_bytes_written_ += bytes_written;
Calin Juravle698f4d12016-03-30 18:18:58 +0100331 profile_file_saved = true;
Calin Juravle67265462016-03-18 16:23:40 +0000332 } else {
333 // At this point we could still have avoided the write.
334 // We load and merge the data from the file lazily at its first ever
335 // save attempt. So, whatever we are trying to save could already be
336 // in the file.
337 total_number_of_skipped_writes_++;
Calin Juravleb8e69992016-03-09 15:37:48 +0000338 }
Calin Juravle67265462016-03-18 16:23:40 +0000339 } else {
340 LOG(WARNING) << "Could not save profiling info to " << filename;
341 total_number_of_failed_writes_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800342 }
Calin Juravle67265462016-03-18 16:23:40 +0000343 total_number_of_profile_entries_cached +=
344 cached_info->GetNumberOfMethods() +
345 cached_info->GetNumberOfResolvedClasses();
Calin Juravleb4eddd22016-01-13 15:52:33 -0800346 }
Calin Juravle67265462016-03-18 16:23:40 +0000347 max_number_of_profile_entries_cached_ = std::max(
348 max_number_of_profile_entries_cached_,
349 total_number_of_profile_entries_cached);
350 return profile_file_saved;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000351}
352
353void* ProfileSaver::RunProfileSaverThread(void* arg) {
354 Runtime* runtime = Runtime::Current();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000355
Calin Juravlef39f0092016-04-28 12:59:33 +0100356 bool attached = runtime->AttachCurrentThread("Profile Saver",
357 /*as_daemon*/true,
358 runtime->GetSystemThreadGroup(),
359 /*create_peer*/true);
360 if (!attached) {
361 CHECK(runtime->IsShuttingDown(Thread::Current()));
362 return nullptr;
363 }
364
365 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000366 profile_saver->Run();
367
368 runtime->DetachCurrentThread();
369 VLOG(profiler) << "Profile saver shutdown";
370 return nullptr;
371}
372
Calin Juravle050fb1b2016-03-25 17:17:09 +0000373static bool ShouldProfileLocation(const std::string& location) {
Calin Juravle0b791272016-04-18 16:38:27 +0100374 OatFileManager& oat_manager = Runtime::Current()->GetOatFileManager();
375 const OatFile* oat_file = oat_manager.FindOpenedOatFileFromDexLocation(location);
Calin Juravle050fb1b2016-03-25 17:17:09 +0000376 if (oat_file == nullptr) {
377 // This can happen if we fallback to run code directly from the APK.
378 // Profile it with the hope that the background dexopt will get us back into
379 // a good state.
Calin Juravle0b791272016-04-18 16:38:27 +0100380 VLOG(profiler) << "Asked to profile a location without an oat file:" << location;
Calin Juravle050fb1b2016-03-25 17:17:09 +0000381 return true;
382 }
383 CompilerFilter::Filter filter = oat_file->GetCompilerFilter();
Calin Juravle65439332016-04-19 18:17:41 +0100384 if ((filter == CompilerFilter::kSpeed) || (filter == CompilerFilter::kEverything)) {
Calin Juravle0b791272016-04-18 16:38:27 +0100385 VLOG(profiler)
Calin Juravle65439332016-04-19 18:17:41 +0100386 << "Skip profiling oat file because it's already speed|everything compiled: "
387 << location << " oat location: " << oat_file->GetLocation();
Calin Juravle050fb1b2016-03-25 17:17:09 +0000388 return false;
389 }
390 return true;
391}
392
Calin Juravle138dbff2016-06-28 19:36:58 +0100393void ProfileSaver::Start(const ProfileSaverOptions& options,
394 const std::string& output_filename,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000395 jit::JitCodeCache* jit_code_cache,
Calin Juravlec90bc922016-02-24 10:13:09 +0000396 const std::vector<std::string>& code_paths,
397 const std::string& foreign_dex_profile_path,
398 const std::string& app_data_dir) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100399 DCHECK(options.IsEnabled());
400 DCHECK(Runtime::Current()->GetJit() != nullptr);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000401 DCHECK(!output_filename.empty());
402 DCHECK(jit_code_cache != nullptr);
403
Calin Juravle050fb1b2016-03-25 17:17:09 +0000404 std::vector<std::string> code_paths_to_profile;
405
406 for (const std::string& location : code_paths) {
407 if (ShouldProfileLocation(location)) {
408 code_paths_to_profile.push_back(location);
Calin Juravle050fb1b2016-03-25 17:17:09 +0000409 }
410 }
411 if (code_paths_to_profile.empty()) {
Calin Juravle0b791272016-04-18 16:38:27 +0100412 VLOG(profiler) << "No code paths should be profiled.";
Calin Juravle050fb1b2016-03-25 17:17:09 +0000413 return;
414 }
415
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000416 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000417 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800418 // If we already have an instance, make sure it uses the same jit_code_cache.
419 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
420 // apps which share the same runtime).
421 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
422 // Add the code_paths to the tracked locations.
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100423 instance_->AddTrackedLocations(output_filename, app_data_dir, code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000424 return;
425 }
426
427 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
Calin Juravle0b791272016-04-18 16:38:27 +0100428 << ". Tracking: " << Join(code_paths_to_profile, ':');
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000429
Calin Juravle138dbff2016-06-28 19:36:58 +0100430 instance_ = new ProfileSaver(options,
431 output_filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000432 jit_code_cache,
Calin Juravle0b791272016-04-18 16:38:27 +0100433 code_paths_to_profile,
Calin Juravlec90bc922016-02-24 10:13:09 +0000434 foreign_dex_profile_path,
435 app_data_dir);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000436
437 // Create a new thread which does the saving.
438 CHECK_PTHREAD_CALL(
439 pthread_create,
440 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
441 "Profile saver thread");
442}
443
Calin Juravleb8e69992016-03-09 15:37:48 +0000444void ProfileSaver::Stop(bool dump_info) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000445 ProfileSaver* profile_saver = nullptr;
446 pthread_t profiler_pthread = 0U;
447
448 {
449 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800450 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000451 profile_saver = instance_;
452 profiler_pthread = profiler_pthread_;
453 if (instance_ == nullptr) {
454 DCHECK(false) << "Tried to stop a profile saver which was not started";
455 return;
456 }
457 if (instance_->shutting_down_) {
458 DCHECK(false) << "Tried to stop the profile saver twice";
459 return;
460 }
461 instance_->shutting_down_ = true;
Calin Juravleb8e69992016-03-09 15:37:48 +0000462 if (dump_info) {
463 instance_->DumpInfo(LOG(INFO));
464 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000465 }
466
467 {
468 // Wake up the saver thread if it is sleeping to allow for a clean exit.
469 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
470 profile_saver->period_condition_.Signal(Thread::Current());
471 }
472
473 // Wait for the saver thread to stop.
474 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
475
476 {
477 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
478 instance_ = nullptr;
479 profiler_pthread_ = 0U;
480 }
481 delete profile_saver;
482}
483
484bool ProfileSaver::ShuttingDown(Thread* self) {
485 MutexLock mu(self, *Locks::profiler_lock_);
486 return shutting_down_;
487}
488
489bool ProfileSaver::IsStarted() {
490 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
491 return instance_ != nullptr;
492}
493
Calin Juravleb4eddd22016-01-13 15:52:33 -0800494void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100495 const std::string& app_data_dir,
Calin Juravleb4eddd22016-01-13 15:52:33 -0800496 const std::vector<std::string>& code_paths) {
497 auto it = tracked_dex_base_locations_.find(output_filename);
498 if (it == tracked_dex_base_locations_.end()) {
499 tracked_dex_base_locations_.Put(output_filename,
500 std::set<std::string>(code_paths.begin(), code_paths.end()));
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100501 app_data_dirs_.insert(app_data_dir);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800502 } else {
503 it->second.insert(code_paths.begin(), code_paths.end());
504 }
505}
506
Calin Juravlec90bc922016-02-24 10:13:09 +0000507void ProfileSaver::NotifyDexUse(const std::string& dex_location) {
Calin Juravle050fb1b2016-03-25 17:17:09 +0000508 if (!ShouldProfileLocation(dex_location)) {
509 return;
510 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000511 std::set<std::string> app_code_paths;
512 std::string foreign_dex_profile_path;
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100513 std::set<std::string> app_data_dirs;
Calin Juravlec90bc922016-02-24 10:13:09 +0000514 {
515 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb8e69992016-03-09 15:37:48 +0000516 if (instance_ == nullptr) {
517 return;
518 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000519 // Make a copy so that we don't hold the lock while doing I/O.
520 for (const auto& it : instance_->tracked_dex_base_locations_) {
521 app_code_paths.insert(it.second.begin(), it.second.end());
522 }
523 foreign_dex_profile_path = instance_->foreign_dex_profile_path_;
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100524 app_data_dirs.insert(instance_->app_data_dirs_.begin(), instance_->app_data_dirs_.end());
Calin Juravlec90bc922016-02-24 10:13:09 +0000525 }
526
Calin Juravleb8e69992016-03-09 15:37:48 +0000527 bool mark_created = MaybeRecordDexUseInternal(dex_location,
528 app_code_paths,
529 foreign_dex_profile_path,
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100530 app_data_dirs);
Calin Juravleb8e69992016-03-09 15:37:48 +0000531 if (mark_created) {
532 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
533 if (instance_ != nullptr) {
534 instance_->total_number_of_foreign_dex_marks_++;
535 }
536 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000537}
538
Calin Juravleb8e69992016-03-09 15:37:48 +0000539bool ProfileSaver::MaybeRecordDexUseInternal(
Calin Juravlec90bc922016-02-24 10:13:09 +0000540 const std::string& dex_location,
541 const std::set<std::string>& app_code_paths,
542 const std::string& foreign_dex_profile_path,
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100543 const std::set<std::string>& app_data_dirs) {
Calin Juravlef529e9b2016-03-08 12:52:52 +0000544 if (dex_location.empty()) {
545 LOG(WARNING) << "Asked to record foreign dex use with an empty dex location.";
Calin Juravleb8e69992016-03-09 15:37:48 +0000546 return false;
Calin Juravlef529e9b2016-03-08 12:52:52 +0000547 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000548 if (foreign_dex_profile_path.empty()) {
549 LOG(WARNING) << "Asked to record foreign dex use without a valid profile path ";
Calin Juravleb8e69992016-03-09 15:37:48 +0000550 return false;
Calin Juravlec90bc922016-02-24 10:13:09 +0000551 }
552
553 UniqueCPtr<const char[]> dex_location_real_path(realpath(dex_location.c_str(), nullptr));
Calin Juravlef529e9b2016-03-08 12:52:52 +0000554 if (dex_location_real_path == nullptr) {
555 PLOG(WARNING) << "Could not get realpath for " << dex_location;
556 }
557 std::string dex_location_real_path_str((dex_location_real_path == nullptr)
558 ? dex_location.c_str()
559 : dex_location_real_path.get());
Calin Juravlec90bc922016-02-24 10:13:09 +0000560
Calin Juravle20b7e3b2016-04-18 18:59:22 +0100561 if (app_data_dirs.find(dex_location_real_path_str) != app_data_dirs.end()) {
Calin Juravlec90bc922016-02-24 10:13:09 +0000562 // The dex location is under the application folder. Nothing to record.
Calin Juravleb8e69992016-03-09 15:37:48 +0000563 return false;
Calin Juravlec90bc922016-02-24 10:13:09 +0000564 }
565
566 if (app_code_paths.find(dex_location) != app_code_paths.end()) {
567 // The dex location belongs to the application code paths. Nothing to record.
Calin Juravleb8e69992016-03-09 15:37:48 +0000568 return false;
Calin Juravlec90bc922016-02-24 10:13:09 +0000569 }
570 // Do another round of checks with the real paths.
571 // Note that we could cache all the real locations in the saver (since it's an expensive
572 // operation). However we expect that app_code_paths is small (usually 1 element), and
573 // NotifyDexUse is called just a few times in the app lifetime. So we make the compromise
574 // to save some bytes of memory usage.
575 for (const auto& app_code_location : app_code_paths) {
576 UniqueCPtr<const char[]> real_app_code_location(realpath(app_code_location.c_str(), nullptr));
Calin Juravlef529e9b2016-03-08 12:52:52 +0000577 if (real_app_code_location == nullptr) {
578 PLOG(WARNING) << "Could not get realpath for " << app_code_location;
579 }
580 std::string real_app_code_location_str((real_app_code_location == nullptr)
581 ? app_code_location.c_str()
582 : real_app_code_location.get());
Calin Juravlec90bc922016-02-24 10:13:09 +0000583 if (real_app_code_location_str == dex_location_real_path_str) {
584 // The dex location belongs to the application code paths. Nothing to record.
Calin Juravleb8e69992016-03-09 15:37:48 +0000585 return false;
Calin Juravlec90bc922016-02-24 10:13:09 +0000586 }
587 }
588
589 // For foreign dex files we record a flag on disk. PackageManager will (potentially) take this
590 // into account when deciding how to optimize the loaded dex file.
591 // The expected flag name is the canonical path of the apk where '/' is substituted to '@'.
592 // (it needs to be kept in sync with
593 // frameworks/base/services/core/java/com/android/server/pm/PackageDexOptimizer.java)
594 std::replace(dex_location_real_path_str.begin(), dex_location_real_path_str.end(), '/', '@');
595 std::string flag_path = foreign_dex_profile_path + "/" + dex_location_real_path_str;
Richard Uhlere18d6192016-05-10 14:01:18 -0700596 // We use O_RDONLY as the access mode because we must supply some access
597 // mode, and there is no access mode that means 'create but do not read' the
598 // file. We will not not actually read from the file.
599 int fd = TEMP_FAILURE_RETRY(open(flag_path.c_str(),
600 O_CREAT | O_RDONLY | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0));
Calin Juravlec90bc922016-02-24 10:13:09 +0000601 if (fd != -1) {
602 if (close(fd) != 0) {
603 PLOG(WARNING) << "Could not close file after flagging foreign dex use " << flag_path;
604 }
Calin Juravleb8e69992016-03-09 15:37:48 +0000605 return true;
Calin Juravlec90bc922016-02-24 10:13:09 +0000606 } else {
Richard Uhlere18d6192016-05-10 14:01:18 -0700607 if (errno != EEXIST && errno != EACCES) {
608 // Another app could have already created the file, and selinux may not
609 // allow the read access to the file implied by the call to open.
Calin Juravlec90bc922016-02-24 10:13:09 +0000610 PLOG(WARNING) << "Could not create foreign dex use mark " << flag_path;
Calin Juravleb8e69992016-03-09 15:37:48 +0000611 return false;
Calin Juravlec90bc922016-02-24 10:13:09 +0000612 }
Calin Juravleb8e69992016-03-09 15:37:48 +0000613 return true;
Calin Juravlec90bc922016-02-24 10:13:09 +0000614 }
615}
616
Calin Juravleb8e69992016-03-09 15:37:48 +0000617void ProfileSaver::DumpInstanceInfo(std::ostream& os) {
618 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
619 if (instance_ != nullptr) {
620 instance_->DumpInfo(os);
621 }
622}
623
624void ProfileSaver::DumpInfo(std::ostream& os) {
625 os << "ProfileSaver total_bytes_written=" << total_bytes_written_ << '\n'
626 << "ProfileSaver total_number_of_writes=" << total_number_of_writes_ << '\n'
Calin Juravle67265462016-03-18 16:23:40 +0000627 << "ProfileSaver total_number_of_code_cache_queries="
628 << total_number_of_code_cache_queries_ << '\n'
Calin Juravleb8e69992016-03-09 15:37:48 +0000629 << "ProfileSaver total_number_of_skipped_writes=" << total_number_of_skipped_writes_ << '\n'
630 << "ProfileSaver total_number_of_failed_writes=" << total_number_of_failed_writes_ << '\n'
Calin Juravle67265462016-03-18 16:23:40 +0000631 << "ProfileSaver total_ms_of_sleep=" << total_ms_of_sleep_ << '\n'
Calin Juravle050fb1b2016-03-25 17:17:09 +0000632 << "ProfileSaver total_ms_of_work=" << NsToMs(total_ns_of_work_) << '\n'
Calin Juravle67265462016-03-18 16:23:40 +0000633 << "ProfileSaver total_number_of_foreign_dex_marks="
634 << total_number_of_foreign_dex_marks_ << '\n'
635 << "ProfileSaver max_number_profile_entries_cached="
Calin Juravlea2638922016-04-29 16:44:11 +0100636 << max_number_of_profile_entries_cached_ << '\n'
637 << "ProfileSaver total_number_of_hot_spikes=" << total_number_of_hot_spikes_ << '\n'
638 << "ProfileSaver total_number_of_wake_ups=" << total_number_of_wake_ups_ << '\n';
Calin Juravleb8e69992016-03-09 15:37:48 +0000639}
640
Calin Juravleffc87072016-04-20 14:22:09 +0100641
642void ProfileSaver::ForceProcessProfiles() {
643 ProfileSaver* saver = nullptr;
644 {
645 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
646 saver = instance_;
647 }
648 // TODO(calin): this is not actually thread safe as the instance_ may have been deleted,
649 // but we only use this in testing when we now this won't happen.
650 // Refactor the way we handle the instance so that we don't end up in this situation.
651 if (saver != nullptr) {
Calin Juravlea2638922016-04-29 16:44:11 +0100652 uint16_t new_methods;
653 saver->ProcessProfilingInfo(&new_methods);
Calin Juravleffc87072016-04-20 14:22:09 +0100654 }
655}
656
657bool ProfileSaver::HasSeenMethod(const std::string& profile,
658 const DexFile* dex_file,
659 uint16_t method_idx) {
660 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
661 if (instance_ != nullptr) {
662 ProfileCompilationInfo* info = instance_->GetCachedProfiledInfo(profile);
663 if (info != nullptr) {
664 return info->ContainsMethod(MethodReference(dex_file, method_idx));
665 }
666 }
667 return false;
668}
669
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000670} // namespace art