blob: 8358ce3601a5405c3b2d3358a484ef3bda562b2d [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 <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"
Mathieu Chartierdabdc0f2016-03-04 14:58:03 -080024#include "base/systrace.h"
Calin Juravle6044fa72016-03-25 17:17:09 +000025#include "base/time_utils.h"
26#include "compiler_filter.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000027#include "oat_file_manager.h"
Calin Juravle6044fa72016-03-25 17:17:09 +000028#include "scoped_thread_state_change.h"
29
Calin Juravle4d77b6a2015-12-01 18:38:09 +000030
31namespace art {
32
Calin Juravle4d77b6a2015-12-01 18:38:09 +000033// TODO: read the constants from ProfileOptions,
34// Add a random delay each time we go to sleep so that we don't hammer the CPU
35// with all profile savers running at the same time.
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010036static constexpr const uint64_t kMinSavePeriodNs = MsToNs(20 * 1000); // 20 seconds
Calin Juravlec15e5662016-03-17 17:07:52 +000037static constexpr const uint64_t kSaveResolvedClassesDelayMs = 2 * 1000; // 2 seconds
Calin Juravle4d77b6a2015-12-01 18:38:09 +000038
Calin Juravle85f7bf32016-03-18 16:23:40 +000039static constexpr const uint32_t kMinimumNumberOfMethodsToSave = 10;
40static constexpr const uint32_t kMinimumNumberOfClassesToSave = 10;
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010041static constexpr const uint32_t kMinimumNumberOfNotificationBeforeWake =
42 kMinimumNumberOfMethodsToSave;
43static constexpr const uint32_t kMaximumNumberOfNotificationBeforeWake = 50;
44
Calin Juravle4d77b6a2015-12-01 18:38:09 +000045
46ProfileSaver* ProfileSaver::instance_ = nullptr;
47pthread_t ProfileSaver::profiler_pthread_ = 0U;
48
49ProfileSaver::ProfileSaver(const std::string& output_filename,
50 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +000051 const std::vector<std::string>& code_paths,
52 const std::string& foreign_dex_profile_path,
53 const std::string& app_data_dir)
Calin Juravleb4eddd22016-01-13 15:52:33 -080054 : jit_code_cache_(jit_code_cache),
Calin Juravle86a9ebe2016-02-24 10:13:09 +000055 foreign_dex_profile_path_(foreign_dex_profile_path),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000056 shutting_down_(false),
Calin Juravle85f7bf32016-03-18 16:23:40 +000057 last_save_number_of_methods_(0),
Calin Juravle0cdaa6c2016-03-30 18:18:58 +010058 last_save_number_of_classes_(0),
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010059 last_time_ns_saver_woke_up_(0),
60 jit_activity_notifications_(0),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000061 wait_lock_("ProfileSaver wait lock"),
Calin Juravlec19c1c22016-03-09 15:37:48 +000062 period_condition_("ProfileSaver period condition", wait_lock_),
63 total_bytes_written_(0),
64 total_number_of_writes_(0),
65 total_number_of_code_cache_queries_(0),
66 total_number_of_skipped_writes_(0),
67 total_number_of_failed_writes_(0),
Calin Juravle85f7bf32016-03-18 16:23:40 +000068 total_ms_of_sleep_(0),
Calin Juravlec19c1c22016-03-09 15:37:48 +000069 total_ns_of_work_(0),
Calin Juravle85f7bf32016-03-18 16:23:40 +000070 total_number_of_foreign_dex_marks_(0),
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010071 max_number_of_profile_entries_cached_(0),
72 total_number_of_hot_spikes_(0),
73 total_number_of_wake_ups_(0) {
Calin Juravle20ae7932016-04-18 18:59:22 +010074 AddTrackedLocations(output_filename, app_data_dir, code_paths);
Calin Juravle86a9ebe2016-02-24 10:13:09 +000075 if (!app_data_dir.empty()) {
76 // The application directory is used to determine which dex files are owned by app.
77 // Since it could be a symlink (e.g. /data/data instead of /data/user/0), and we
78 // don't have control over how the dex files are actually loaded (symlink or canonical path),
79 // store it's canonical form to be sure we use the same base when comparing.
80 UniqueCPtr<const char[]> app_data_dir_real_path(realpath(app_data_dir.c_str(), nullptr));
81 if (app_data_dir_real_path != nullptr) {
Calin Juravle20ae7932016-04-18 18:59:22 +010082 app_data_dirs_.emplace(app_data_dir_real_path.get());
Calin Juravle86a9ebe2016-02-24 10:13:09 +000083 } else {
Calin Juravle20ae7932016-04-18 18:59:22 +010084 LOG(WARNING) << "Failed to get the real path for app dir: " << app_data_dir
Calin Juravle86a9ebe2016-02-24 10:13:09 +000085 << ". The app dir will not be used to determine which dex files belong to the app";
86 }
87 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000088}
89
90void ProfileSaver::Run() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +000091 Thread* self = Thread::Current();
92
Calin Juravle5fbb0fe2016-04-29 16:44:11 +010093 // Fetch the resolved classes for the app images after sleeping for
94 // kSaveResolvedClassesDelayMs.
95 // TODO(calin) This only considers the case of the primary profile file.
96 // Anything that gets loaded in the same VM will not have their resolved
97 // classes save (unless they started before the initial saving was done).
98 {
99 MutexLock mu(self, wait_lock_);
100 period_condition_.TimedWait(self, kSaveResolvedClassesDelayMs, 0);
101 total_ms_of_sleep_ += kSaveResolvedClassesDelayMs;
102 }
103 FetchAndCacheResolvedClasses();
104
105 // Loop for the profiled methods.
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800106 while (!ShuttingDown(self)) {
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100107 uint64_t sleep_start = NanoTime();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000108 {
109 MutexLock mu(self, wait_lock_);
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100110 period_condition_.Wait(self);
111 total_number_of_wake_ups_++;
112 // We might have been woken up by a huge number of notifications to guarantee saving.
113 // If we didn't meet the minimum saving period go back to sleep (only if missed by
114 // a reasonable margin).
115 uint64_t sleep_time = NanoTime() - last_time_ns_saver_woke_up_;
116 while (kMinSavePeriodNs - sleep_time > (kMinSavePeriodNs / 10)) {
117 period_condition_.TimedWait(self, NsToMs(kMinSavePeriodNs - sleep_time), 0);
118 total_number_of_wake_ups_++;
119 sleep_time = NanoTime() - last_time_ns_saver_woke_up_;
120 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000121 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100122 total_ms_of_sleep_ += NsToMs(NanoTime() - sleep_start);
123
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000124 if (ShuttingDown(self)) {
125 break;
126 }
127
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100128 uint16_t new_methods = 0;
129 uint64_t start_work = NanoTime();
130 bool profile_saved_to_disk = ProcessProfilingInfo(&new_methods);
131 // Update the notification counter based on result. Note that there might be contention on this
132 // but we don't care about to be 100% precise.
133 if (!profile_saved_to_disk) {
134 // If we didn't save to disk it may be because we didn't have enough new methods.
135 // Set the jit activity notifications to new_methods so we can wake up earlier if needed.
136 jit_activity_notifications_ = new_methods;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000137 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100138 total_ns_of_work_ += NanoTime() - start_work;
139 }
140}
Calin Juravlec19c1c22016-03-09 15:37:48 +0000141
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100142void ProfileSaver::NotifyJitActivity() {
143 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
144 if (instance_ == nullptr || instance_->shutting_down_) {
145 return;
146 }
147 instance_->NotifyJitActivityInternal();
148}
149
150void ProfileSaver::WakeUpSaver() {
151 jit_activity_notifications_ = 0;
152 last_time_ns_saver_woke_up_ = NanoTime();
153 period_condition_.Signal(Thread::Current());
154}
155
156void ProfileSaver::NotifyJitActivityInternal() {
157 // Unlikely to overflow but if it happens,
158 // we would have waken up the saver long before that.
159 jit_activity_notifications_++;
160 // Note that we are not as precise as we could be here but we don't want to wake the saver
161 // every time we see a hot method.
162 if (jit_activity_notifications_ > kMinimumNumberOfNotificationBeforeWake) {
163 MutexLock wait_mutex(Thread::Current(), wait_lock_);
164 if ((NanoTime() - last_time_ns_saver_woke_up_) > kMinSavePeriodNs) {
165 WakeUpSaver();
166 }
167 } else if (jit_activity_notifications_ > kMaximumNumberOfNotificationBeforeWake) {
168 // Make sure to wake up the saver if we see a spike in the number of notifications.
169 // This is a precaution to avoid "loosing" a big number of methods in case
170 // this is a spike with no jit after.
171 total_number_of_hot_spikes_++;
172 MutexLock wait_mutex(Thread::Current(), wait_lock_);
173 WakeUpSaver();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000174 }
175}
176
Calin Juravle85f7bf32016-03-18 16:23:40 +0000177ProfileCompilationInfo* ProfileSaver::GetCachedProfiledInfo(const std::string& filename) {
178 auto info_it = profile_cache_.find(filename);
179 if (info_it == profile_cache_.end()) {
180 info_it = profile_cache_.Put(filename, ProfileCompilationInfo());
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000181 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000182 return &info_it->second;
183}
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000184
Calin Juravle85f7bf32016-03-18 16:23:40 +0000185void ProfileSaver::FetchAndCacheResolvedClasses() {
186 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000187 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
188 std::set<DexCacheResolvedClasses> resolved_classes =
189 class_linker->GetResolvedClasses(/*ignore boot classes*/ true);
190 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
191 uint64_t total_number_of_profile_entries_cached = 0;
Mathieu Chartier9275af62016-04-29 12:03:56 -0700192
Calin Juravle85f7bf32016-03-18 16:23:40 +0000193 for (const auto& it : tracked_dex_base_locations_) {
Mathieu Chartier9275af62016-04-29 12:03:56 -0700194 std::set<DexCacheResolvedClasses> resolved_classes_for_location;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000195 const std::string& filename = it.first;
196 const std::set<std::string>& locations = it.second;
197
198 for (const DexCacheResolvedClasses& classes : resolved_classes) {
Mathieu Chartier9275af62016-04-29 12:03:56 -0700199 if (locations.find(classes.GetBaseLocation()) != locations.end()) {
200 VLOG(profiler) << "Added classes for location " << classes.GetBaseLocation()
201 << " (" << classes.GetDexLocation() << ")";
Calin Juravle85f7bf32016-03-18 16:23:40 +0000202 resolved_classes_for_location.insert(classes);
Mathieu Chartier9275af62016-04-29 12:03:56 -0700203 } else {
204 VLOG(profiler) << "Location not found " << classes.GetBaseLocation()
205 << " (" << classes.GetDexLocation() << ")";
Calin Juravle85f7bf32016-03-18 16:23:40 +0000206 }
207 }
208 ProfileCompilationInfo* info = GetCachedProfiledInfo(filename);
Calin Juravlee2d066d2016-04-19 16:33:46 +0100209 info->AddMethodsAndClasses(std::vector<MethodReference>(), resolved_classes_for_location);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000210 total_number_of_profile_entries_cached += resolved_classes_for_location.size();
211 }
212 max_number_of_profile_entries_cached_ = std::max(
213 max_number_of_profile_entries_cached_,
214 total_number_of_profile_entries_cached);
215}
216
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100217bool ProfileSaver::ProcessProfilingInfo(uint16_t* new_methods) {
Calin Juravle85f7bf32016-03-18 16:23:40 +0000218 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800219 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000220 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800221 // Make a copy so that we don't hold the lock while doing I/O.
222 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
223 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000224 }
Calin Juravlec15e5662016-03-17 17:07:52 +0000225
Calin Juravle85f7bf32016-03-18 16:23:40 +0000226 bool profile_file_saved = false;
227 uint64_t total_number_of_profile_entries_cached = 0;
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100228 *new_methods = 0;
229
Calin Juravleb4eddd22016-01-13 15:52:33 -0800230 for (const auto& it : tracked_locations) {
231 if (ShuttingDown(Thread::Current())) {
232 return true;
233 }
234 const std::string& filename = it.first;
235 const std::set<std::string>& locations = it.second;
Calin Juravlee2d066d2016-04-19 16:33:46 +0100236 std::vector<MethodReference> methods;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800237 {
238 ScopedObjectAccess soa(Thread::Current());
Calin Juravlee2d066d2016-04-19 16:33:46 +0100239 jit_code_cache_->GetProfiledMethods(locations, methods);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000240 total_number_of_code_cache_queries_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800241 }
Calin Juravlec15e5662016-03-17 17:07:52 +0000242
Calin Juravle85f7bf32016-03-18 16:23:40 +0000243 ProfileCompilationInfo* cached_info = GetCachedProfiledInfo(filename);
244 cached_info->AddMethodsAndClasses(methods, std::set<DexCacheResolvedClasses>());
Calin Juravle0cdaa6c2016-03-30 18:18:58 +0100245 int64_t delta_number_of_methods =
246 cached_info->GetNumberOfMethods() -
247 static_cast<int64_t>(last_save_number_of_methods_);
248 int64_t delta_number_of_classes =
249 cached_info->GetNumberOfResolvedClasses() -
250 static_cast<int64_t>(last_save_number_of_classes_);
Calin Juravle85f7bf32016-03-18 16:23:40 +0000251
252 if (delta_number_of_methods < kMinimumNumberOfMethodsToSave &&
253 delta_number_of_classes < kMinimumNumberOfClassesToSave) {
Calin Juravle0cdaa6c2016-03-30 18:18:58 +0100254 VLOG(profiler) << "Not enough information to save to: " << filename
Calin Juravle85f7bf32016-03-18 16:23:40 +0000255 << " Nr of methods: " << delta_number_of_methods
256 << " Nr of classes: " << delta_number_of_classes;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000257 total_number_of_skipped_writes_++;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000258 continue;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800259 }
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100260 *new_methods = std::max(static_cast<uint16_t>(delta_number_of_methods), *new_methods);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000261 uint64_t bytes_written;
Calin Juravlefe297a92016-03-24 20:33:22 +0000262 // Force the save. In case the profile data is corrupted or the the profile
263 // has the wrong version this will "fix" the file to the correct format.
264 if (cached_info->MergeAndSave(filename, &bytes_written, /*force*/ true)) {
Calin Juravle85f7bf32016-03-18 16:23:40 +0000265 last_save_number_of_methods_ = cached_info->GetNumberOfMethods();
Calin Juravle0cdaa6c2016-03-30 18:18:58 +0100266 last_save_number_of_classes_ = cached_info->GetNumberOfResolvedClasses();
Calin Juravle85f7bf32016-03-18 16:23:40 +0000267 // Clear resolved classes. No need to store them around as
268 // they don't change after the first write.
269 cached_info->ClearResolvedClasses();
Calin Juravlec19c1c22016-03-09 15:37:48 +0000270 if (bytes_written > 0) {
271 total_number_of_writes_++;
272 total_bytes_written_ += bytes_written;
Calin Juravle0cdaa6c2016-03-30 18:18:58 +0100273 profile_file_saved = true;
Calin Juravle85f7bf32016-03-18 16:23:40 +0000274 } else {
275 // At this point we could still have avoided the write.
276 // We load and merge the data from the file lazily at its first ever
277 // save attempt. So, whatever we are trying to save could already be
278 // in the file.
279 total_number_of_skipped_writes_++;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000280 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000281 } else {
282 LOG(WARNING) << "Could not save profiling info to " << filename;
283 total_number_of_failed_writes_++;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800284 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000285 total_number_of_profile_entries_cached +=
286 cached_info->GetNumberOfMethods() +
287 cached_info->GetNumberOfResolvedClasses();
Calin Juravleb4eddd22016-01-13 15:52:33 -0800288 }
Calin Juravle85f7bf32016-03-18 16:23:40 +0000289 max_number_of_profile_entries_cached_ = std::max(
290 max_number_of_profile_entries_cached_,
291 total_number_of_profile_entries_cached);
292 return profile_file_saved;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000293}
294
295void* ProfileSaver::RunProfileSaverThread(void* arg) {
296 Runtime* runtime = Runtime::Current();
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000297
Calin Juravlee55fda12016-04-28 12:59:33 +0100298 bool attached = runtime->AttachCurrentThread("Profile Saver",
299 /*as_daemon*/true,
300 runtime->GetSystemThreadGroup(),
301 /*create_peer*/true);
302 if (!attached) {
303 CHECK(runtime->IsShuttingDown(Thread::Current()));
304 return nullptr;
305 }
306
307 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000308 profile_saver->Run();
309
310 runtime->DetachCurrentThread();
311 VLOG(profiler) << "Profile saver shutdown";
312 return nullptr;
313}
314
Calin Juravle6044fa72016-03-25 17:17:09 +0000315static bool ShouldProfileLocation(const std::string& location) {
Calin Juravle75064232016-04-18 16:38:27 +0100316 OatFileManager& oat_manager = Runtime::Current()->GetOatFileManager();
317 const OatFile* oat_file = oat_manager.FindOpenedOatFileFromDexLocation(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000318 if (oat_file == nullptr) {
319 // This can happen if we fallback to run code directly from the APK.
320 // Profile it with the hope that the background dexopt will get us back into
321 // a good state.
Calin Juravle75064232016-04-18 16:38:27 +0100322 VLOG(profiler) << "Asked to profile a location without an oat file:" << location;
Calin Juravle6044fa72016-03-25 17:17:09 +0000323 return true;
324 }
325 CompilerFilter::Filter filter = oat_file->GetCompilerFilter();
Calin Juravled19dc462016-04-19 18:17:41 +0100326 if ((filter == CompilerFilter::kSpeed) || (filter == CompilerFilter::kEverything)) {
Calin Juravle75064232016-04-18 16:38:27 +0100327 VLOG(profiler)
Calin Juravled19dc462016-04-19 18:17:41 +0100328 << "Skip profiling oat file because it's already speed|everything compiled: "
329 << location << " oat location: " << oat_file->GetLocation();
Calin Juravle6044fa72016-03-25 17:17:09 +0000330 return false;
331 }
332 return true;
333}
334
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000335void ProfileSaver::Start(const std::string& output_filename,
336 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000337 const std::vector<std::string>& code_paths,
338 const std::string& foreign_dex_profile_path,
339 const std::string& app_data_dir) {
Calin Juravlee5de54c2016-04-20 14:22:09 +0100340 DCHECK(Runtime::Current()->SaveProfileInfo());
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000341 DCHECK(!output_filename.empty());
342 DCHECK(jit_code_cache != nullptr);
343
Calin Juravle6044fa72016-03-25 17:17:09 +0000344 std::vector<std::string> code_paths_to_profile;
345
346 for (const std::string& location : code_paths) {
347 if (ShouldProfileLocation(location)) {
348 code_paths_to_profile.push_back(location);
Calin Juravle6044fa72016-03-25 17:17:09 +0000349 }
350 }
351 if (code_paths_to_profile.empty()) {
Calin Juravle75064232016-04-18 16:38:27 +0100352 VLOG(profiler) << "No code paths should be profiled.";
Calin Juravle6044fa72016-03-25 17:17:09 +0000353 return;
354 }
355
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000356 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000357 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800358 // If we already have an instance, make sure it uses the same jit_code_cache.
359 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
360 // apps which share the same runtime).
361 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
362 // Add the code_paths to the tracked locations.
Calin Juravle20ae7932016-04-18 18:59:22 +0100363 instance_->AddTrackedLocations(output_filename, app_data_dir, code_paths_to_profile);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000364 return;
365 }
366
367 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
Calin Juravle75064232016-04-18 16:38:27 +0100368 << ". Tracking: " << Join(code_paths_to_profile, ':');
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000369
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000370 instance_ = new ProfileSaver(output_filename,
371 jit_code_cache,
Calin Juravle75064232016-04-18 16:38:27 +0100372 code_paths_to_profile,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000373 foreign_dex_profile_path,
374 app_data_dir);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000375
376 // Create a new thread which does the saving.
377 CHECK_PTHREAD_CALL(
378 pthread_create,
379 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
380 "Profile saver thread");
381}
382
Calin Juravlec19c1c22016-03-09 15:37:48 +0000383void ProfileSaver::Stop(bool dump_info) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000384 ProfileSaver* profile_saver = nullptr;
385 pthread_t profiler_pthread = 0U;
386
387 {
388 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800389 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000390 profile_saver = instance_;
391 profiler_pthread = profiler_pthread_;
392 if (instance_ == nullptr) {
393 DCHECK(false) << "Tried to stop a profile saver which was not started";
394 return;
395 }
396 if (instance_->shutting_down_) {
397 DCHECK(false) << "Tried to stop the profile saver twice";
398 return;
399 }
400 instance_->shutting_down_ = true;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000401 if (dump_info) {
402 instance_->DumpInfo(LOG(INFO));
403 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000404 }
405
406 {
407 // Wake up the saver thread if it is sleeping to allow for a clean exit.
408 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
409 profile_saver->period_condition_.Signal(Thread::Current());
410 }
411
412 // Wait for the saver thread to stop.
413 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
414
415 {
416 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
417 instance_ = nullptr;
418 profiler_pthread_ = 0U;
419 }
420 delete profile_saver;
421}
422
423bool ProfileSaver::ShuttingDown(Thread* self) {
424 MutexLock mu(self, *Locks::profiler_lock_);
425 return shutting_down_;
426}
427
428bool ProfileSaver::IsStarted() {
429 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
430 return instance_ != nullptr;
431}
432
Calin Juravleb4eddd22016-01-13 15:52:33 -0800433void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
Calin Juravle20ae7932016-04-18 18:59:22 +0100434 const std::string& app_data_dir,
Calin Juravleb4eddd22016-01-13 15:52:33 -0800435 const std::vector<std::string>& code_paths) {
436 auto it = tracked_dex_base_locations_.find(output_filename);
437 if (it == tracked_dex_base_locations_.end()) {
438 tracked_dex_base_locations_.Put(output_filename,
439 std::set<std::string>(code_paths.begin(), code_paths.end()));
Calin Juravle20ae7932016-04-18 18:59:22 +0100440 app_data_dirs_.insert(app_data_dir);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800441 } else {
442 it->second.insert(code_paths.begin(), code_paths.end());
443 }
444}
445
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000446void ProfileSaver::NotifyDexUse(const std::string& dex_location) {
Calin Juravle6044fa72016-03-25 17:17:09 +0000447 if (!ShouldProfileLocation(dex_location)) {
448 return;
449 }
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000450 std::set<std::string> app_code_paths;
451 std::string foreign_dex_profile_path;
Calin Juravle20ae7932016-04-18 18:59:22 +0100452 std::set<std::string> app_data_dirs;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000453 {
454 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000455 if (instance_ == nullptr) {
456 return;
457 }
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000458 // Make a copy so that we don't hold the lock while doing I/O.
459 for (const auto& it : instance_->tracked_dex_base_locations_) {
460 app_code_paths.insert(it.second.begin(), it.second.end());
461 }
462 foreign_dex_profile_path = instance_->foreign_dex_profile_path_;
Calin Juravle20ae7932016-04-18 18:59:22 +0100463 app_data_dirs.insert(instance_->app_data_dirs_.begin(), instance_->app_data_dirs_.end());
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000464 }
465
Calin Juravlec19c1c22016-03-09 15:37:48 +0000466 bool mark_created = MaybeRecordDexUseInternal(dex_location,
467 app_code_paths,
468 foreign_dex_profile_path,
Calin Juravle20ae7932016-04-18 18:59:22 +0100469 app_data_dirs);
Calin Juravlec19c1c22016-03-09 15:37:48 +0000470 if (mark_created) {
471 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
472 if (instance_ != nullptr) {
473 instance_->total_number_of_foreign_dex_marks_++;
474 }
475 }
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000476}
477
Calin Juravlec19c1c22016-03-09 15:37:48 +0000478bool ProfileSaver::MaybeRecordDexUseInternal(
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000479 const std::string& dex_location,
480 const std::set<std::string>& app_code_paths,
481 const std::string& foreign_dex_profile_path,
Calin Juravle20ae7932016-04-18 18:59:22 +0100482 const std::set<std::string>& app_data_dirs) {
Calin Juravle1fae45f2016-03-08 12:52:52 +0000483 if (dex_location.empty()) {
484 LOG(WARNING) << "Asked to record foreign dex use with an empty dex location.";
Calin Juravlec19c1c22016-03-09 15:37:48 +0000485 return false;
Calin Juravle1fae45f2016-03-08 12:52:52 +0000486 }
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000487 if (foreign_dex_profile_path.empty()) {
488 LOG(WARNING) << "Asked to record foreign dex use without a valid profile path ";
Calin Juravlec19c1c22016-03-09 15:37:48 +0000489 return false;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000490 }
491
492 UniqueCPtr<const char[]> dex_location_real_path(realpath(dex_location.c_str(), nullptr));
Calin Juravle1fae45f2016-03-08 12:52:52 +0000493 if (dex_location_real_path == nullptr) {
494 PLOG(WARNING) << "Could not get realpath for " << dex_location;
495 }
496 std::string dex_location_real_path_str((dex_location_real_path == nullptr)
497 ? dex_location.c_str()
498 : dex_location_real_path.get());
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000499
Calin Juravle20ae7932016-04-18 18:59:22 +0100500 if (app_data_dirs.find(dex_location_real_path_str) != app_data_dirs.end()) {
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000501 // The dex location is under the application folder. Nothing to record.
Calin Juravlec19c1c22016-03-09 15:37:48 +0000502 return false;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000503 }
504
505 if (app_code_paths.find(dex_location) != app_code_paths.end()) {
506 // The dex location belongs to the application code paths. Nothing to record.
Calin Juravlec19c1c22016-03-09 15:37:48 +0000507 return false;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000508 }
509 // Do another round of checks with the real paths.
510 // Note that we could cache all the real locations in the saver (since it's an expensive
511 // operation). However we expect that app_code_paths is small (usually 1 element), and
512 // NotifyDexUse is called just a few times in the app lifetime. So we make the compromise
513 // to save some bytes of memory usage.
514 for (const auto& app_code_location : app_code_paths) {
515 UniqueCPtr<const char[]> real_app_code_location(realpath(app_code_location.c_str(), nullptr));
Calin Juravle1fae45f2016-03-08 12:52:52 +0000516 if (real_app_code_location == nullptr) {
517 PLOG(WARNING) << "Could not get realpath for " << app_code_location;
518 }
519 std::string real_app_code_location_str((real_app_code_location == nullptr)
520 ? app_code_location.c_str()
521 : real_app_code_location.get());
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000522 if (real_app_code_location_str == dex_location_real_path_str) {
523 // The dex location belongs to the application code paths. Nothing to record.
Calin Juravlec19c1c22016-03-09 15:37:48 +0000524 return false;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000525 }
526 }
527
528 // For foreign dex files we record a flag on disk. PackageManager will (potentially) take this
529 // into account when deciding how to optimize the loaded dex file.
530 // The expected flag name is the canonical path of the apk where '/' is substituted to '@'.
531 // (it needs to be kept in sync with
532 // frameworks/base/services/core/java/com/android/server/pm/PackageDexOptimizer.java)
533 std::replace(dex_location_real_path_str.begin(), dex_location_real_path_str.end(), '/', '@');
534 std::string flag_path = foreign_dex_profile_path + "/" + dex_location_real_path_str;
Richard Uhler12e41572016-05-10 14:01:18 -0700535 // We use O_RDONLY as the access mode because we must supply some access
536 // mode, and there is no access mode that means 'create but do not read' the
537 // file. We will not not actually read from the file.
538 int fd = TEMP_FAILURE_RETRY(open(flag_path.c_str(),
539 O_CREAT | O_RDONLY | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0));
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000540 if (fd != -1) {
541 if (close(fd) != 0) {
542 PLOG(WARNING) << "Could not close file after flagging foreign dex use " << flag_path;
543 }
Calin Juravlec19c1c22016-03-09 15:37:48 +0000544 return true;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000545 } else {
Richard Uhler12e41572016-05-10 14:01:18 -0700546 if (errno != EEXIST && errno != EACCES) {
547 // Another app could have already created the file, and selinux may not
548 // allow the read access to the file implied by the call to open.
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000549 PLOG(WARNING) << "Could not create foreign dex use mark " << flag_path;
Calin Juravlec19c1c22016-03-09 15:37:48 +0000550 return false;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000551 }
Calin Juravlec19c1c22016-03-09 15:37:48 +0000552 return true;
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000553 }
554}
555
Calin Juravlec19c1c22016-03-09 15:37:48 +0000556void ProfileSaver::DumpInstanceInfo(std::ostream& os) {
557 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
558 if (instance_ != nullptr) {
559 instance_->DumpInfo(os);
560 }
561}
562
563void ProfileSaver::DumpInfo(std::ostream& os) {
564 os << "ProfileSaver total_bytes_written=" << total_bytes_written_ << '\n'
565 << "ProfileSaver total_number_of_writes=" << total_number_of_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000566 << "ProfileSaver total_number_of_code_cache_queries="
567 << total_number_of_code_cache_queries_ << '\n'
Calin Juravlec19c1c22016-03-09 15:37:48 +0000568 << "ProfileSaver total_number_of_skipped_writes=" << total_number_of_skipped_writes_ << '\n'
569 << "ProfileSaver total_number_of_failed_writes=" << total_number_of_failed_writes_ << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000570 << "ProfileSaver total_ms_of_sleep=" << total_ms_of_sleep_ << '\n'
Calin Juravle6044fa72016-03-25 17:17:09 +0000571 << "ProfileSaver total_ms_of_work=" << NsToMs(total_ns_of_work_) << '\n'
Calin Juravle85f7bf32016-03-18 16:23:40 +0000572 << "ProfileSaver total_number_of_foreign_dex_marks="
573 << total_number_of_foreign_dex_marks_ << '\n'
574 << "ProfileSaver max_number_profile_entries_cached="
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100575 << max_number_of_profile_entries_cached_ << '\n'
576 << "ProfileSaver total_number_of_hot_spikes=" << total_number_of_hot_spikes_ << '\n'
577 << "ProfileSaver total_number_of_wake_ups=" << total_number_of_wake_ups_ << '\n';
Calin Juravlec19c1c22016-03-09 15:37:48 +0000578}
579
Calin Juravlee5de54c2016-04-20 14:22:09 +0100580
581void ProfileSaver::ForceProcessProfiles() {
582 ProfileSaver* saver = nullptr;
583 {
584 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
585 saver = instance_;
586 }
587 // TODO(calin): this is not actually thread safe as the instance_ may have been deleted,
588 // but we only use this in testing when we now this won't happen.
589 // Refactor the way we handle the instance so that we don't end up in this situation.
590 if (saver != nullptr) {
Calin Juravle5fbb0fe2016-04-29 16:44:11 +0100591 uint16_t new_methods;
592 saver->ProcessProfilingInfo(&new_methods);
Calin Juravlee5de54c2016-04-20 14:22:09 +0100593 }
594}
595
596bool 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 = instance_->GetCachedProfiledInfo(profile);
602 if (info != nullptr) {
603 return info->ContainsMethod(MethodReference(dex_file, method_idx));
604 }
605 }
606 return false;
607}
608
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000609} // namespace art