blob: 8dc696fcac2122b183761a458438b72fdb104d83 [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 Juravle4d77b6a2015-12-01 18:38:09 +000025#include "scoped_thread_state_change.h"
26#include "oat_file_manager.h"
27
28namespace art {
29
Calin Juravle932a0512016-01-19 14:32:26 -080030// An arbitrary value to throttle save requests. Set to 2s for now.
Calin Juravle4d77b6a2015-12-01 18:38:09 +000031static constexpr const uint64_t kMilisecondsToNano = 1000000;
Calin Juravle932a0512016-01-19 14:32:26 -080032static constexpr const uint64_t kMinimumTimeBetweenCodeCacheUpdatesNs = 2000 * kMilisecondsToNano;
Calin Juravle4d77b6a2015-12-01 18:38:09 +000033
34// TODO: read the constants from ProfileOptions,
35// Add a random delay each time we go to sleep so that we don't hammer the CPU
36// with all profile savers running at the same time.
Calin Juravle932a0512016-01-19 14:32:26 -080037static constexpr const uint64_t kRandomDelayMaxMs = 20 * 1000; // 20 seconds
38static constexpr const uint64_t kMaxBackoffMs = 5 * 60 * 1000; // 5 minutes
39static constexpr const uint64_t kSavePeriodMs = 10 * 1000; // 10 seconds
Mathieu Chartier8913fc12015-12-09 16:38:30 -080040static constexpr const uint64_t kInitialDelayMs = 2 * 1000; // 2 seconds
Calin Juravle4d77b6a2015-12-01 18:38:09 +000041static constexpr const double kBackoffCoef = 1.5;
42
43static constexpr const uint32_t kMinimumNrOrMethodsToSave = 10;
44
45ProfileSaver* ProfileSaver::instance_ = nullptr;
46pthread_t ProfileSaver::profiler_pthread_ = 0U;
47
48ProfileSaver::ProfileSaver(const std::string& output_filename,
49 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +000050 const std::vector<std::string>& code_paths,
51 const std::string& foreign_dex_profile_path,
52 const std::string& app_data_dir)
Calin Juravleb4eddd22016-01-13 15:52:33 -080053 : jit_code_cache_(jit_code_cache),
Calin Juravle86a9ebe2016-02-24 10:13:09 +000054 foreign_dex_profile_path_(foreign_dex_profile_path),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000055 code_cache_last_update_time_ns_(0),
56 shutting_down_(false),
Mathieu Chartier8913fc12015-12-09 16:38:30 -080057 first_profile_(true),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000058 wait_lock_("ProfileSaver wait lock"),
59 period_condition_("ProfileSaver period condition", wait_lock_) {
Calin Juravleb4eddd22016-01-13 15:52:33 -080060 AddTrackedLocations(output_filename, code_paths);
Calin Juravle86a9ebe2016-02-24 10:13:09 +000061 app_data_dir_ = "";
62 if (!app_data_dir.empty()) {
63 // The application directory is used to determine which dex files are owned by app.
64 // Since it could be a symlink (e.g. /data/data instead of /data/user/0), and we
65 // don't have control over how the dex files are actually loaded (symlink or canonical path),
66 // store it's canonical form to be sure we use the same base when comparing.
67 UniqueCPtr<const char[]> app_data_dir_real_path(realpath(app_data_dir.c_str(), nullptr));
68 if (app_data_dir_real_path != nullptr) {
69 app_data_dir_.assign(app_data_dir_real_path.get());
70 } else {
71 LOG(WARNING) << "Failed to get the real path for app dir: " << app_data_dir_
72 << ". The app dir will not be used to determine which dex files belong to the app";
73 }
74 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000075}
76
77void ProfileSaver::Run() {
78 srand(MicroTime() * getpid());
79 Thread* self = Thread::Current();
80
81 uint64_t save_period_ms = kSavePeriodMs;
82 VLOG(profiler) << "Save profiling information every " << save_period_ms << " ms";
Calin Juravle4d77b6a2015-12-01 18:38:09 +000083
Mathieu Chartier8913fc12015-12-09 16:38:30 -080084 bool first_iteration = true;
85 while (!ShuttingDown(self)) {
86 uint64_t sleep_time_ms;
87 if (first_iteration) {
88 // Sleep less long for the first iteration since we want to record loaded classes shortly
89 // after app launch.
90 sleep_time_ms = kInitialDelayMs;
91 } else {
92 const uint64_t random_sleep_delay_ms = rand() % kRandomDelayMaxMs;
93 sleep_time_ms = save_period_ms + random_sleep_delay_ms;
94 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000095 {
96 MutexLock mu(self, wait_lock_);
97 period_condition_.TimedWait(self, sleep_time_ms, 0);
98 }
99
100 if (ShuttingDown(self)) {
101 break;
102 }
103
104 if (!ProcessProfilingInfo() && save_period_ms < kMaxBackoffMs) {
105 // If we don't need to save now it is less likely that we will need to do
106 // so in the future. Increase the time between saves according to the
107 // kBackoffCoef, but make it no larger than kMaxBackoffMs.
108 save_period_ms = static_cast<uint64_t>(kBackoffCoef * save_period_ms);
109 } else {
110 // Reset the period to the initial value as it's highly likely to JIT again.
111 save_period_ms = kSavePeriodMs;
112 }
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800113 first_iteration = false;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000114 }
115}
116
117bool ProfileSaver::ProcessProfilingInfo() {
Mathieu Chartierdabdc0f2016-03-04 14:58:03 -0800118 ScopedTrace trace(__PRETTY_FUNCTION__);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000119 uint64_t last_update_time_ns = jit_code_cache_->GetLastUpdateTimeNs();
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800120 if (!first_profile_ && last_update_time_ns - code_cache_last_update_time_ns_
121 < kMinimumTimeBetweenCodeCacheUpdatesNs) {
Calin Juravle877fd962016-01-05 14:29:29 +0000122 VLOG(profiler) << "Not enough time has passed since the last code cache update."
123 << "Last update: " << last_update_time_ns
124 << " Last save: " << code_cache_last_update_time_ns_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000125 return false;
126 }
127
128 uint64_t start = NanoTime();
129 code_cache_last_update_time_ns_ = last_update_time_ns;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800130 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000131 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800132 // Make a copy so that we don't hold the lock while doing I/O.
133 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
134 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000135 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800136 for (const auto& it : tracked_locations) {
137 if (ShuttingDown(Thread::Current())) {
138 return true;
139 }
140 const std::string& filename = it.first;
141 const std::set<std::string>& locations = it.second;
142 std::vector<ArtMethod*> methods;
143 {
144 ScopedObjectAccess soa(Thread::Current());
145 jit_code_cache_->GetCompiledArtMethods(locations, methods);
146 }
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800147 // Always save for the first one for loaded classes profile.
148 if (methods.size() < kMinimumNrOrMethodsToSave && !first_profile_) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800149 VLOG(profiler) << "Not enough information to save to: " << filename
150 <<" Nr of methods: " << methods.size();
151 return false;
152 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000153
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800154 std::set<DexCacheResolvedClasses> resolved_classes;
155 if (first_profile_) {
156 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
157 resolved_classes = class_linker->GetResolvedClasses(/*ignore boot classes*/true);
158 }
159
160 if (!ProfileCompilationInfo::SaveProfilingInfo(filename, methods, resolved_classes)) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800161 LOG(WARNING) << "Could not save profiling info to " << filename;
162 return false;
163 }
164
165 VLOG(profiler) << "Profile process time: " << PrettyDuration(NanoTime() - start);
166 }
Mathieu Chartier8913fc12015-12-09 16:38:30 -0800167 first_profile_ = false;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000168 return true;
169}
170
171void* ProfileSaver::RunProfileSaverThread(void* arg) {
172 Runtime* runtime = Runtime::Current();
173 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
174
175 CHECK(runtime->AttachCurrentThread("Profile Saver",
176 /*as_daemon*/true,
177 runtime->GetSystemThreadGroup(),
178 /*create_peer*/true));
179 profile_saver->Run();
180
181 runtime->DetachCurrentThread();
182 VLOG(profiler) << "Profile saver shutdown";
183 return nullptr;
184}
185
186void ProfileSaver::Start(const std::string& output_filename,
187 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000188 const std::vector<std::string>& code_paths,
189 const std::string& foreign_dex_profile_path,
190 const std::string& app_data_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000191 DCHECK(Runtime::Current()->UseJit());
192 DCHECK(!output_filename.empty());
193 DCHECK(jit_code_cache != nullptr);
194
195 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000196 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800197 // If we already have an instance, make sure it uses the same jit_code_cache.
198 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
199 // apps which share the same runtime).
200 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
201 // Add the code_paths to the tracked locations.
202 instance_->AddTrackedLocations(output_filename, code_paths);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000203 return;
204 }
205
206 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
207 << ". Tracking: " << Join(code_paths, ':');
208
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000209 instance_ = new ProfileSaver(output_filename,
210 jit_code_cache,
211 code_paths,
212 foreign_dex_profile_path,
213 app_data_dir);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000214
215 // Create a new thread which does the saving.
216 CHECK_PTHREAD_CALL(
217 pthread_create,
218 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
219 "Profile saver thread");
220}
221
222void ProfileSaver::Stop() {
223 ProfileSaver* profile_saver = nullptr;
224 pthread_t profiler_pthread = 0U;
225
226 {
227 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800228 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000229 profile_saver = instance_;
230 profiler_pthread = profiler_pthread_;
231 if (instance_ == nullptr) {
232 DCHECK(false) << "Tried to stop a profile saver which was not started";
233 return;
234 }
235 if (instance_->shutting_down_) {
236 DCHECK(false) << "Tried to stop the profile saver twice";
237 return;
238 }
239 instance_->shutting_down_ = true;
240 }
241
242 {
243 // Wake up the saver thread if it is sleeping to allow for a clean exit.
244 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
245 profile_saver->period_condition_.Signal(Thread::Current());
246 }
247
248 // Wait for the saver thread to stop.
249 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
250
251 {
252 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
253 instance_ = nullptr;
254 profiler_pthread_ = 0U;
255 }
256 delete profile_saver;
257}
258
259bool ProfileSaver::ShuttingDown(Thread* self) {
260 MutexLock mu(self, *Locks::profiler_lock_);
261 return shutting_down_;
262}
263
264bool ProfileSaver::IsStarted() {
265 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
266 return instance_ != nullptr;
267}
268
Calin Juravleb4eddd22016-01-13 15:52:33 -0800269void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
270 const std::vector<std::string>& code_paths) {
271 auto it = tracked_dex_base_locations_.find(output_filename);
272 if (it == tracked_dex_base_locations_.end()) {
273 tracked_dex_base_locations_.Put(output_filename,
274 std::set<std::string>(code_paths.begin(), code_paths.end()));
275 } else {
276 it->second.insert(code_paths.begin(), code_paths.end());
277 }
278}
279
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000280void ProfileSaver::NotifyDexUse(const std::string& dex_location) {
281 std::set<std::string> app_code_paths;
282 std::string foreign_dex_profile_path;
283 std::string app_data_dir;
284 {
285 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
286 DCHECK(instance_ != nullptr);
287 // Make a copy so that we don't hold the lock while doing I/O.
288 for (const auto& it : instance_->tracked_dex_base_locations_) {
289 app_code_paths.insert(it.second.begin(), it.second.end());
290 }
291 foreign_dex_profile_path = instance_->foreign_dex_profile_path_;
292 app_data_dir = instance_->app_data_dir_;
293 }
294
295 MaybeRecordDexUseInternal(dex_location,
296 app_code_paths,
297 foreign_dex_profile_path,
298 app_data_dir);
299}
300
301void ProfileSaver::MaybeRecordDexUseInternal(
302 const std::string& dex_location,
303 const std::set<std::string>& app_code_paths,
304 const std::string& foreign_dex_profile_path,
305 const std::string& app_data_dir) {
306 if (foreign_dex_profile_path.empty()) {
307 LOG(WARNING) << "Asked to record foreign dex use without a valid profile path ";
308 return;
309 }
310
311 UniqueCPtr<const char[]> dex_location_real_path(realpath(dex_location.c_str(), nullptr));
312 std::string dex_location_real_path_str(dex_location_real_path.get());
313
314 if (dex_location_real_path_str.compare(0, app_data_dir.length(), app_data_dir) == 0) {
315 // The dex location is under the application folder. Nothing to record.
316 return;
317 }
318
319 if (app_code_paths.find(dex_location) != app_code_paths.end()) {
320 // The dex location belongs to the application code paths. Nothing to record.
321 return;
322 }
323 // Do another round of checks with the real paths.
324 // Note that we could cache all the real locations in the saver (since it's an expensive
325 // operation). However we expect that app_code_paths is small (usually 1 element), and
326 // NotifyDexUse is called just a few times in the app lifetime. So we make the compromise
327 // to save some bytes of memory usage.
328 for (const auto& app_code_location : app_code_paths) {
329 UniqueCPtr<const char[]> real_app_code_location(realpath(app_code_location.c_str(), nullptr));
330 std::string real_app_code_location_str(real_app_code_location.get());
331 if (real_app_code_location_str == dex_location_real_path_str) {
332 // The dex location belongs to the application code paths. Nothing to record.
333 return;
334 }
335 }
336
337 // For foreign dex files we record a flag on disk. PackageManager will (potentially) take this
338 // into account when deciding how to optimize the loaded dex file.
339 // The expected flag name is the canonical path of the apk where '/' is substituted to '@'.
340 // (it needs to be kept in sync with
341 // frameworks/base/services/core/java/com/android/server/pm/PackageDexOptimizer.java)
342 std::replace(dex_location_real_path_str.begin(), dex_location_real_path_str.end(), '/', '@');
343 std::string flag_path = foreign_dex_profile_path + "/" + dex_location_real_path_str;
344 // No need to give any sort of access to flag_path. The system has enough permissions
345 // to test for its existence.
346 int fd = TEMP_FAILURE_RETRY(open(flag_path.c_str(), O_CREAT | O_EXCL, 0));
347 if (fd != -1) {
348 if (close(fd) != 0) {
349 PLOG(WARNING) << "Could not close file after flagging foreign dex use " << flag_path;
350 }
351 } else {
352 if (errno != EEXIST) {
353 // Another app could have already created the file.
354 PLOG(WARNING) << "Could not create foreign dex use mark " << flag_path;
355 }
356 }
357}
358
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000359} // namespace art