blob: 5abfa6c6a0c499483f3ef0c9bcc3c0eccaeea066 [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"
24#include "scoped_thread_state_change.h"
25#include "oat_file_manager.h"
26
27namespace art {
28
Calin Juravle932a0512016-01-19 14:32:26 -080029// An arbitrary value to throttle save requests. Set to 2s for now.
Calin Juravle4d77b6a2015-12-01 18:38:09 +000030static constexpr const uint64_t kMilisecondsToNano = 1000000;
Calin Juravle932a0512016-01-19 14:32:26 -080031static constexpr const uint64_t kMinimumTimeBetweenCodeCacheUpdatesNs = 2000 * kMilisecondsToNano;
Calin Juravle4d77b6a2015-12-01 18:38:09 +000032
33// 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 Juravle932a0512016-01-19 14:32:26 -080036static constexpr const uint64_t kRandomDelayMaxMs = 20 * 1000; // 20 seconds
37static constexpr const uint64_t kMaxBackoffMs = 5 * 60 * 1000; // 5 minutes
38static constexpr const uint64_t kSavePeriodMs = 10 * 1000; // 10 seconds
Mathieu Chartierc5dd3192015-12-09 16:38:30 -080039static constexpr const uint64_t kInitialDelayMs = 2 * 1000; // 2 seconds
Calin Juravle4d77b6a2015-12-01 18:38:09 +000040static constexpr const double kBackoffCoef = 1.5;
41
42static constexpr const uint32_t kMinimumNrOrMethodsToSave = 10;
43
44ProfileSaver* ProfileSaver::instance_ = nullptr;
45pthread_t ProfileSaver::profiler_pthread_ = 0U;
46
47ProfileSaver::ProfileSaver(const std::string& output_filename,
48 jit::JitCodeCache* jit_code_cache,
Calin Juravlec90bc922016-02-24 10:13:09 +000049 const std::vector<std::string>& code_paths,
50 const std::string& foreign_dex_profile_path,
51 const std::string& app_data_dir)
Calin Juravleb4eddd22016-01-13 15:52:33 -080052 : jit_code_cache_(jit_code_cache),
Calin Juravlec90bc922016-02-24 10:13:09 +000053 foreign_dex_profile_path_(foreign_dex_profile_path),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000054 code_cache_last_update_time_ns_(0),
55 shutting_down_(false),
Mathieu Chartierc5dd3192015-12-09 16:38:30 -080056 first_profile_(true),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000057 wait_lock_("ProfileSaver wait lock"),
58 period_condition_("ProfileSaver period condition", wait_lock_) {
Calin Juravleb4eddd22016-01-13 15:52:33 -080059 AddTrackedLocations(output_filename, code_paths);
Calin Juravlec90bc922016-02-24 10:13:09 +000060 app_data_dir_ = "";
61 if (!app_data_dir.empty()) {
62 // The application directory is used to determine which dex files are owned by app.
63 // Since it could be a symlink (e.g. /data/data instead of /data/user/0), and we
64 // don't have control over how the dex files are actually loaded (symlink or canonical path),
65 // store it's canonical form to be sure we use the same base when comparing.
66 UniqueCPtr<const char[]> app_data_dir_real_path(realpath(app_data_dir.c_str(), nullptr));
67 if (app_data_dir_real_path != nullptr) {
68 app_data_dir_.assign(app_data_dir_real_path.get());
69 } else {
70 LOG(WARNING) << "Failed to get the real path for app dir: " << app_data_dir_
71 << ". The app dir will not be used to determine which dex files belong to the app";
72 }
73 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000074}
75
76void ProfileSaver::Run() {
77 srand(MicroTime() * getpid());
78 Thread* self = Thread::Current();
79
80 uint64_t save_period_ms = kSavePeriodMs;
81 VLOG(profiler) << "Save profiling information every " << save_period_ms << " ms";
Calin Juravle4d77b6a2015-12-01 18:38:09 +000082
Mathieu Chartierc5dd3192015-12-09 16:38:30 -080083 bool first_iteration = true;
84 while (!ShuttingDown(self)) {
85 uint64_t sleep_time_ms;
86 if (first_iteration) {
87 // Sleep less long for the first iteration since we want to record loaded classes shortly
88 // after app launch.
89 sleep_time_ms = kInitialDelayMs;
90 } else {
91 const uint64_t random_sleep_delay_ms = rand() % kRandomDelayMaxMs;
92 sleep_time_ms = save_period_ms + random_sleep_delay_ms;
93 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000094 {
95 MutexLock mu(self, wait_lock_);
96 period_condition_.TimedWait(self, sleep_time_ms, 0);
97 }
98
99 if (ShuttingDown(self)) {
100 break;
101 }
102
103 if (!ProcessProfilingInfo() && save_period_ms < kMaxBackoffMs) {
104 // If we don't need to save now it is less likely that we will need to do
105 // so in the future. Increase the time between saves according to the
106 // kBackoffCoef, but make it no larger than kMaxBackoffMs.
107 save_period_ms = static_cast<uint64_t>(kBackoffCoef * save_period_ms);
108 } else {
109 // Reset the period to the initial value as it's highly likely to JIT again.
110 save_period_ms = kSavePeriodMs;
111 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800112 first_iteration = false;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000113 }
114}
115
116bool ProfileSaver::ProcessProfilingInfo() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000117 uint64_t last_update_time_ns = jit_code_cache_->GetLastUpdateTimeNs();
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800118 if (!first_profile_ && last_update_time_ns - code_cache_last_update_time_ns_
119 < kMinimumTimeBetweenCodeCacheUpdatesNs) {
Calin Juravle877fd962016-01-05 14:29:29 +0000120 VLOG(profiler) << "Not enough time has passed since the last code cache update."
121 << "Last update: " << last_update_time_ns
122 << " Last save: " << code_cache_last_update_time_ns_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000123 return false;
124 }
125
126 uint64_t start = NanoTime();
127 code_cache_last_update_time_ns_ = last_update_time_ns;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800128 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000129 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800130 // Make a copy so that we don't hold the lock while doing I/O.
131 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
132 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000133 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800134 for (const auto& it : tracked_locations) {
135 if (ShuttingDown(Thread::Current())) {
136 return true;
137 }
138 const std::string& filename = it.first;
139 const std::set<std::string>& locations = it.second;
140 std::vector<ArtMethod*> methods;
141 {
142 ScopedObjectAccess soa(Thread::Current());
143 jit_code_cache_->GetCompiledArtMethods(locations, methods);
144 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800145 // Always save for the first one for loaded classes profile.
146 if (methods.size() < kMinimumNrOrMethodsToSave && !first_profile_) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800147 VLOG(profiler) << "Not enough information to save to: " << filename
148 <<" Nr of methods: " << methods.size();
149 return false;
150 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000151
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800152 std::set<DexCacheResolvedClasses> resolved_classes;
153 if (first_profile_) {
154 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
155 resolved_classes = class_linker->GetResolvedClasses(/*ignore boot classes*/true);
156 }
157
158 if (!ProfileCompilationInfo::SaveProfilingInfo(filename, methods, resolved_classes)) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800159 LOG(WARNING) << "Could not save profiling info to " << filename;
160 return false;
161 }
162
163 VLOG(profiler) << "Profile process time: " << PrettyDuration(NanoTime() - start);
164 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800165 first_profile_ = false;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000166 return true;
167}
168
169void* ProfileSaver::RunProfileSaverThread(void* arg) {
170 Runtime* runtime = Runtime::Current();
171 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
172
173 CHECK(runtime->AttachCurrentThread("Profile Saver",
174 /*as_daemon*/true,
175 runtime->GetSystemThreadGroup(),
176 /*create_peer*/true));
177 profile_saver->Run();
178
179 runtime->DetachCurrentThread();
180 VLOG(profiler) << "Profile saver shutdown";
181 return nullptr;
182}
183
184void ProfileSaver::Start(const std::string& output_filename,
185 jit::JitCodeCache* jit_code_cache,
Calin Juravlec90bc922016-02-24 10:13:09 +0000186 const std::vector<std::string>& code_paths,
187 const std::string& foreign_dex_profile_path,
188 const std::string& app_data_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000189 DCHECK(Runtime::Current()->UseJit());
190 DCHECK(!output_filename.empty());
191 DCHECK(jit_code_cache != nullptr);
192
193 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000194 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800195 // If we already have an instance, make sure it uses the same jit_code_cache.
196 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
197 // apps which share the same runtime).
198 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
199 // Add the code_paths to the tracked locations.
200 instance_->AddTrackedLocations(output_filename, code_paths);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000201 return;
202 }
203
204 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
205 << ". Tracking: " << Join(code_paths, ':');
206
Calin Juravlec90bc922016-02-24 10:13:09 +0000207 instance_ = new ProfileSaver(output_filename,
208 jit_code_cache,
209 code_paths,
210 foreign_dex_profile_path,
211 app_data_dir);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000212
213 // Create a new thread which does the saving.
214 CHECK_PTHREAD_CALL(
215 pthread_create,
216 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
217 "Profile saver thread");
218}
219
220void ProfileSaver::Stop() {
221 ProfileSaver* profile_saver = nullptr;
222 pthread_t profiler_pthread = 0U;
223
224 {
225 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800226 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000227 profile_saver = instance_;
228 profiler_pthread = profiler_pthread_;
229 if (instance_ == nullptr) {
230 DCHECK(false) << "Tried to stop a profile saver which was not started";
231 return;
232 }
233 if (instance_->shutting_down_) {
234 DCHECK(false) << "Tried to stop the profile saver twice";
235 return;
236 }
237 instance_->shutting_down_ = true;
238 }
239
240 {
241 // Wake up the saver thread if it is sleeping to allow for a clean exit.
242 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
243 profile_saver->period_condition_.Signal(Thread::Current());
244 }
245
246 // Wait for the saver thread to stop.
247 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
248
249 {
250 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
251 instance_ = nullptr;
252 profiler_pthread_ = 0U;
253 }
254 delete profile_saver;
255}
256
257bool ProfileSaver::ShuttingDown(Thread* self) {
258 MutexLock mu(self, *Locks::profiler_lock_);
259 return shutting_down_;
260}
261
262bool ProfileSaver::IsStarted() {
263 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
264 return instance_ != nullptr;
265}
266
Calin Juravleb4eddd22016-01-13 15:52:33 -0800267void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
268 const std::vector<std::string>& code_paths) {
269 auto it = tracked_dex_base_locations_.find(output_filename);
270 if (it == tracked_dex_base_locations_.end()) {
271 tracked_dex_base_locations_.Put(output_filename,
272 std::set<std::string>(code_paths.begin(), code_paths.end()));
273 } else {
274 it->second.insert(code_paths.begin(), code_paths.end());
275 }
276}
277
Calin Juravlec90bc922016-02-24 10:13:09 +0000278void ProfileSaver::NotifyDexUse(const std::string& dex_location) {
279 std::set<std::string> app_code_paths;
280 std::string foreign_dex_profile_path;
281 std::string app_data_dir;
282 {
283 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
284 DCHECK(instance_ != nullptr);
285 // Make a copy so that we don't hold the lock while doing I/O.
286 for (const auto& it : instance_->tracked_dex_base_locations_) {
287 app_code_paths.insert(it.second.begin(), it.second.end());
288 }
289 foreign_dex_profile_path = instance_->foreign_dex_profile_path_;
290 app_data_dir = instance_->app_data_dir_;
291 }
292
293 MaybeRecordDexUseInternal(dex_location,
294 app_code_paths,
295 foreign_dex_profile_path,
296 app_data_dir);
297}
298
299void ProfileSaver::MaybeRecordDexUseInternal(
300 const std::string& dex_location,
301 const std::set<std::string>& app_code_paths,
302 const std::string& foreign_dex_profile_path,
303 const std::string& app_data_dir) {
304 if (foreign_dex_profile_path.empty()) {
305 LOG(WARNING) << "Asked to record foreign dex use without a valid profile path ";
306 return;
307 }
308
309 UniqueCPtr<const char[]> dex_location_real_path(realpath(dex_location.c_str(), nullptr));
310 std::string dex_location_real_path_str(dex_location_real_path.get());
311
312 if (dex_location_real_path_str.compare(0, app_data_dir.length(), app_data_dir) == 0) {
313 // The dex location is under the application folder. Nothing to record.
314 return;
315 }
316
317 if (app_code_paths.find(dex_location) != app_code_paths.end()) {
318 // The dex location belongs to the application code paths. Nothing to record.
319 return;
320 }
321 // Do another round of checks with the real paths.
322 // Note that we could cache all the real locations in the saver (since it's an expensive
323 // operation). However we expect that app_code_paths is small (usually 1 element), and
324 // NotifyDexUse is called just a few times in the app lifetime. So we make the compromise
325 // to save some bytes of memory usage.
326 for (const auto& app_code_location : app_code_paths) {
327 UniqueCPtr<const char[]> real_app_code_location(realpath(app_code_location.c_str(), nullptr));
328 std::string real_app_code_location_str(real_app_code_location.get());
329 if (real_app_code_location_str == dex_location_real_path_str) {
330 // The dex location belongs to the application code paths. Nothing to record.
331 return;
332 }
333 }
334
335 // For foreign dex files we record a flag on disk. PackageManager will (potentially) take this
336 // into account when deciding how to optimize the loaded dex file.
337 // The expected flag name is the canonical path of the apk where '/' is substituted to '@'.
338 // (it needs to be kept in sync with
339 // frameworks/base/services/core/java/com/android/server/pm/PackageDexOptimizer.java)
340 std::replace(dex_location_real_path_str.begin(), dex_location_real_path_str.end(), '/', '@');
341 std::string flag_path = foreign_dex_profile_path + "/" + dex_location_real_path_str;
342 // No need to give any sort of access to flag_path. The system has enough permissions
343 // to test for its existence.
344 int fd = TEMP_FAILURE_RETRY(open(flag_path.c_str(), O_CREAT | O_EXCL, 0));
345 if (fd != -1) {
346 if (close(fd) != 0) {
347 PLOG(WARNING) << "Could not close file after flagging foreign dex use " << flag_path;
348 }
349 } else {
350 if (errno != EEXIST) {
351 // Another app could have already created the file.
352 PLOG(WARNING) << "Could not create foreign dex use mark " << flag_path;
353 }
354 }
355}
356
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000357} // namespace art