blob: b7c0e66e241b65e61fa13d70502cad2d7e4ccaf7 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 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 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Jeff Sharkey90aff262016-12-12 14:28:24 -070018#include <fcntl.h>
Keun young Park65578d62021-06-28 17:52:05 -070019#include <signal.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Keun young Park65578d62021-06-28 17:52:05 -070031#include <array>
Andreas Gampe023b2242018-02-28 16:03:25 -080032#include <iomanip>
Keun young Park65578d62021-06-28 17:52:05 -070033#include <mutex>
34#include <unordered_set>
Andreas Gampe023b2242018-02-28 16:03:25 -080035
Alan Stokesa25d90c2017-10-16 10:56:00 +010036#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070037#include <android-base/logging.h>
Keun young Park65578d62021-06-28 17:52:05 -070038#include <android-base/no_destructor.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070039#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070040#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
Martijn Coenen6de402a2021-04-26 16:23:40 +020043#include <async_safe/log.h>
Calin Juravle80a21252017-01-17 14:43:25 -080044#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <cutils/properties.h>
46#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070047#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010048#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <private/android_filesystem_config.h>
Wei Wang0efe8d52021-07-07 17:32:38 -070050#include <processgroup/processgroup.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070051#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000052#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070053#include <system/thread_defs.h>
Keun young Park65578d62021-06-28 17:52:05 -070054#include <utils/Mutex.h>
Yang Tianping8f2a40e2021-10-29 14:39:02 +080055#include <ziparchive/zip_archive.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070056
57#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080058#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070059#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060060#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070061#include "installd_deps.h"
Calin Juravle3b758282021-06-08 08:04:52 -070062#include "installd_constants.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070063#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070064#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070065#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066#include "utils.h"
67
Victor Hsieh76f19ba2020-08-10 14:37:26 -070068using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070069using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070070using android::base::GetBoolProperty;
71using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000072using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010073using android::base::ReadFully;
74using android::base::StringPrintf;
75using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080076using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070077
Keun young Park65578d62021-06-28 17:52:05 -070078namespace {
79
80class DexOptStatus {
81 public:
82 // Check if dexopt is cancelled and fork if it is not cancelled.
83 // cancelled is set to true if cancelled. Otherwise it will be set to false.
84 // If it is not cancelled, it will return the return value of fork() call.
85 // If cancelled, fork will not happen and it will return -1.
86 pid_t check_cancellation_and_fork(/* out */ bool *cancelled) {
87 std::lock_guard<std::mutex> lock(dexopt_lock_);
88 if (dexopt_blocked_) {
89 *cancelled = true;
90 return -1;
91 }
92 pid_t pid = fork();
93 *cancelled = false;
94 if (pid > 0) { // parent
95 dexopt_pids_.insert(pid);
96 }
97 return pid;
98 }
99
100 // Returns true if pid was killed (is in killed list). It could have finished if killing
101 // happened after the process is finished.
102 bool check_if_killed_and_remove_dexopt_pid(pid_t pid) {
103 std::lock_guard<std::mutex> lock(dexopt_lock_);
104 dexopt_pids_.erase(pid);
105 if (dexopt_killed_pids_.erase(pid) == 1) {
106 return true;
107 }
108 return false;
109 }
110
111 // Tells whether dexopt is blocked or not.
112 bool is_dexopt_blocked() {
113 std::lock_guard<std::mutex> lock(dexopt_lock_);
114 return dexopt_blocked_;
115 }
116
117 // Enable or disable dexopt blocking.
118 void control_dexopt_blocking(bool block) {
119 std::lock_guard<std::mutex> lock(dexopt_lock_);
120 dexopt_blocked_ = block;
121 if (!block) {
122 return;
123 }
124 // Blocked, also kill currently running tasks
125 for (auto pid : dexopt_pids_) {
126 LOG(INFO) << "control_dexopt_blocking kill pid:" << pid;
127 kill(pid, SIGKILL);
128 dexopt_killed_pids_.insert(pid);
129 }
130 dexopt_pids_.clear();
131 }
132
133 private:
134 std::mutex dexopt_lock_;
135 // when true, dexopt is blocked and will not run.
136 bool dexopt_blocked_ GUARDED_BY(dexopt_lock_) = false;
137 // PIDs of child process while runinng dexopt.
138 // If the child process is finished, it should be removed.
139 std::unordered_set<pid_t> dexopt_pids_ GUARDED_BY(dexopt_lock_);
140 // PIDs of child processes killed by cancellation.
141 std::unordered_set<pid_t> dexopt_killed_pids_ GUARDED_BY(dexopt_lock_);
142};
143
144android::base::NoDestructor<DexOptStatus> dexopt_status_;
145
146} // namespace
147
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700148namespace android {
149namespace installd {
150
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800151
Calin Juravle114f0812017-03-08 19:05:07 -0800152// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
153struct FreeDelete {
154 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
155 void operator()(const void* ptr) const {
156 free(const_cast<void*>(ptr));
157 }
158};
159
160// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
161template <typename T>
162using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
163
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800164static unique_fd invalid_unique_fd() {
165 return unique_fd(-1);
166}
167
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700168static bool is_debug_runtime() {
169 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
170}
171
David Sehra3b5ab62017-10-25 14:27:29 -0700172static bool is_debuggable_build() {
173 return android::base::GetBoolProperty("ro.debuggable", false);
174}
175
Jeff Sharkey90aff262016-12-12 14:28:24 -0700176static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800177 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700178 if (ufd.get() < 0) {
179 if (errno != ENOENT) {
180 PLOG(WARNING) << "Could not open profile " << profile;
181 return false;
182 } else {
183 // Nothing to clear. That's ok.
184 return true;
185 }
186 }
187
188 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
189 if (errno != EWOULDBLOCK) {
190 PLOG(WARNING) << "Error locking profile " << profile;
191 }
192 // This implies that the app owning this profile is running
193 // (and has acquired the lock).
194 //
195 // If we can't acquire the lock bail out since clearing is useless anyway
196 // (the app will write again to the profile).
197 //
198 // Note:
199 // This does not impact the this is not an issue for the profiling correctness.
200 // In case this is needed because of an app upgrade, profiles will still be
201 // eventually cleared by the app itself due to checksum mismatch.
202 // If this is needed because profman advised, then keeping the data around
203 // until the next run is again not an issue.
204 //
205 // If the app attempts to acquire a lock while we've held one here,
206 // it will simply skip the current write cycle.
207 return false;
208 }
209
210 bool truncated = ftruncate(ufd.get(), 0) == 0;
211 if (!truncated) {
212 PLOG(WARNING) << "Could not truncate " << profile;
213 }
214 if (flock(ufd.get(), LOCK_UN) != 0) {
215 PLOG(WARNING) << "Error unlocking profile " << profile;
216 }
217 return truncated;
218}
219
Calin Juravle114f0812017-03-08 19:05:07 -0800220// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800221// The location is the profile name for primary apks or the dex path for secondary dex files.
222static bool clear_reference_profile(const std::string& package_name, const std::string& location,
223 bool is_secondary_dex) {
224 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700225}
226
Calin Juravle114f0812017-03-08 19:05:07 -0800227// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800228// The location is the profile name for primary apks or the dex path for secondary dex files.
229static bool clear_current_profile(const std::string& package_name, const std::string& location,
230 userid_t user, bool is_secondary_dex) {
231 return clear_profile(create_current_profile_path(user, package_name, location,
232 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700233}
234
Calin Juravle114f0812017-03-08 19:05:07 -0800235// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800236// The location is the profile name for primary apks or the dex path for secondary dex files.
237bool clear_primary_reference_profile(const std::string& package_name,
238 const std::string& location) {
239 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800240}
241
242// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800243// The location is the profile name for primary apks or the dex path for secondary dex files.
244bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700245 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800246 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700247 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
248 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800249 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700250 }
251 return success;
252}
253
Calin Juravle114f0812017-03-08 19:05:07 -0800254// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800255bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
256 userid_t user) {
257 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800258}
259
Calin Juravlef74a7372019-02-28 20:29:41 -0800260// Determines which binary we should use for execution (the debug or non-debug version).
261// e.g. dex2oatd vs dex2oat
262static const char* select_execution_binary(const char* binary, const char* debug_binary,
263 bool background_job_compile) {
264 return select_execution_binary(
265 binary,
266 debug_binary,
267 background_job_compile,
268 is_debug_runtime(),
269 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
270 is_debuggable_build());
271}
272
273// Determines which binary we should use for execution (the debug or non-debug version).
274// e.g. dex2oatd vs dex2oat
275// This is convenient method which is much easier to test because it doesn't read
276// system properties.
277const char* select_execution_binary(
278 const char* binary,
279 const char* debug_binary,
280 bool background_job_compile,
281 bool is_debug_runtime,
282 bool is_release,
283 bool is_debuggable_build) {
284 // Do not use debug binaries for release candidates (to give more soak time).
285 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
286
287 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
288 // the file is present (it may not be on images with very little space available).
289 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
290
291 return useDebug ? debug_binary : binary;
292}
293
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000294// Namespace for Android Runtime flags applied during boot time.
295static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
296// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000297static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000298
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700299// Phenotype property name for enabling profiling the boot class path.
300static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
301
Calin Juravlef85ddb92020-05-01 14:05:40 -0700302static bool IsBootClassPathProfilingEnable() {
303 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
304 profile_boot_class_path =
305 server_configurable_flags::GetServerConfigurableFlag(
306 RUNTIME_NATIVE_BOOT_NAMESPACE,
307 PROFILE_BOOT_CLASS_PATH,
308 /*default_value=*/ profile_boot_class_path);
309 return profile_boot_class_path == "true";
310}
311
Victor Hsiehcb35a062020-08-13 16:11:13 -0700312static void UnlinkIgnoreResult(const std::string& path) {
313 if (unlink(path.c_str()) < 0) {
314 PLOG(ERROR) << "Failed to unlink " << path;
315 }
316}
317
Jeff Sharkey90aff262016-12-12 14:28:24 -0700318/*
319 * Whether dexopt should use a swap file when compiling an APK.
320 *
321 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
322 * itself, anyways).
323 *
324 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
325 *
326 * Otherwise, return true if this is a low-mem device.
327 *
328 * Otherwise, return default value.
329 */
330static bool kAlwaysProvideSwapFile = false;
331static bool kDefaultProvideSwapFile = true;
332
333static bool ShouldUseSwapFileForDexopt() {
334 if (kAlwaysProvideSwapFile) {
335 return true;
336 }
337
338 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700339 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
340 if (!dex2oat_prop_buf.empty()) {
341 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342 }
343
344 // Shortcut for default value. This is an implementation optimization for the process sketched
345 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
346 // as low-mem is never returning false. The compiler will optimize this away if it can.
347 if (kDefaultProvideSwapFile) {
348 return true;
349 }
350
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700351 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700352 return true;
353 }
354
355 // Default value must be false here.
356 return kDefaultProvideSwapFile;
357}
358
Richard Uhler76cc0272016-12-08 10:46:35 +0000359static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700360 if (set_to_bg) {
Wei Wang0efe8d52021-07-07 17:32:38 -0700361 if (!SetTaskProfiles(0, {"Dex2OatBootComplete"})) {
362 LOG(ERROR) << "Failed to set dex2oat task profile";
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800363 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700364 }
365 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800366 PLOG(ERROR) << "setpriority failed";
367 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700368 }
369 }
370}
371
Calin Juravlee01f8712021-06-03 18:16:54 -0700372static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
373 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, mode)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800374 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800375 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800376 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800377 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800378 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700379 }
Calin Juravle114f0812017-03-08 19:05:07 -0800380 // Profiles should belong to the app; make sure of that by giving ownership to
381 // the app uid. If we cannot do that, there's no point in returning the fd
382 // since dex2oat/profman will fail with SElinux denials.
383 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000384 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800385 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800386 }
Calin Juravle29591732017-11-20 17:46:19 -0800387 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800388}
389
Calin Juravlee01f8712021-06-03 18:16:54 -0700390static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
Calin Juravle114f0812017-03-08 19:05:07 -0800391 // Do not follow symlinks when opening a profile:
392 // - primary profiles should not contain symlinks in their paths
393 // - secondary dex paths should have been already resolved and validated
394 flags |= O_NOFOLLOW;
395
Calin Juravle29591732017-11-20 17:46:19 -0800396 // Check if we need to create the profile
397 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
398 unique_fd fd;
399 if ((flags & O_CREAT) != 0) {
Calin Juravlee01f8712021-06-03 18:16:54 -0700400 fd = create_profile(uid, profile, flags, mode);
Calin Juravle29591732017-11-20 17:46:19 -0800401 } else {
402 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
403 }
404
Calin Juravle114f0812017-03-08 19:05:07 -0800405 if (fd.get() < 0) {
406 if (errno != ENOENT) {
407 // Profiles might be missing for various reasons. For example, in a
408 // multi-user environment, the profile directory for one user can be created
409 // after we start a merge. In this case the current profile for that user
410 // will not be found.
411 // Also, the secondary dex profiles might be deleted by the app at any time,
412 // so we can't we need to prepare if they are missing.
413 PLOG(ERROR) << "Failed to open profile " << profile;
414 }
415 return invalid_unique_fd();
Calin Juravlee01f8712021-06-03 18:16:54 -0700416 } else {
417 // If we just create the file we need to set its mode because on Android
418 // open has a mask that only allows owner access.
419 if ((flags & O_CREAT) != 0) {
420 if (fchmod(fd.get(), mode) != 0) {
421 PLOG(ERROR) << "Could not set mode " << std::hex << mode << std::dec
422 << " on profile" << profile;
423 // Not a terminal failure.
424 }
425 }
Calin Juravle114f0812017-03-08 19:05:07 -0800426 }
427
Jeff Sharkey90aff262016-12-12 14:28:24 -0700428 return fd;
429}
430
Calin Juravle824a64d2018-01-18 20:23:17 -0800431static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
432 const std::string& location, bool is_secondary_dex) {
433 std::string profile = create_current_profile_path(user, package_name, location,
434 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700435 return open_profile(uid, profile, O_RDONLY, /*mode=*/ 0);
Calin Juravle114f0812017-03-08 19:05:07 -0800436}
437
Calin Juravle824a64d2018-01-18 20:23:17 -0800438static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
439 const std::string& location, bool read_write, bool is_secondary_dex) {
440 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700441 return open_profile(
442 uid,
443 profile,
444 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
445 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
Calin Juravle29591732017-11-20 17:46:19 -0800446}
447
Victor Hsiehcb35a062020-08-13 16:11:13 -0700448static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
449 const std::string& location, bool read_write, bool is_secondary_dex) {
450 std::string profile_path = create_reference_profile_path(package_name, location,
451 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700452 unique_fd ufd = open_profile(
453 uid,
454 profile_path,
455 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
456 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
457
Victor Hsiehcb35a062020-08-13 16:11:13 -0700458 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
459 clear_profile(path);
460 });
461}
462
Calin Juravle29591732017-11-20 17:46:19 -0800463static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800464 const std::string& location) {
465 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravlee01f8712021-06-03 18:16:54 -0700466 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
Calin Juravle114f0812017-03-08 19:05:07 -0800467}
468
Calin Juravle824a64d2018-01-18 20:23:17 -0800469static void open_profile_files(uid_t uid, const std::string& package_name,
470 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800471 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700472 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800473 *reference_profile_fd = open_reference_profile(uid, package_name, location,
474 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700475
Calin Juravle114f0812017-03-08 19:05:07 -0800476 // For secondary dex files, we don't really need the user but we use it for sanity checks.
477 // Note: the user owning the dex file should be the current user.
478 std::vector<userid_t> users;
479 if (is_secondary_dex){
480 users.push_back(multiuser_get_user_id(uid));
481 } else {
482 users = get_known_users(/*volume_uuid*/ nullptr);
483 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700484 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800485 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
486 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700487 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800488 if (profile_fd.get() >= 0) {
489 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700490 }
491 }
492}
493
Calin Juravle76561322019-11-14 09:08:52 -0800494static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
495static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
Calin Juravle3b758282021-06-08 08:04:52 -0700496static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
Calin Juravle76561322019-11-14 09:08:52 -0800497static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
498static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
499static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
500static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Calin Juravle3b758282021-06-08 08:04:52 -0700501static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700502
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800503class RunProfman : public ExecVHelper {
504 public:
505 void SetupArgs(const std::vector<unique_fd>& profile_fds,
506 const unique_fd& reference_profile_fd,
507 const std::vector<unique_fd>& apk_fds,
508 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800509 bool copy_and_update,
510 bool for_snapshot,
511 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800512
513 // TODO(calin): Assume for now we run in the bg compile job (which is in
514 // most of the invocation). With the current data flow, is not very easy or
515 // clean to discover this in RunProfman (it will require quite a messy refactoring).
516 const char* profman_bin = select_execution_binary(
517 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700518
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800519 if (copy_and_update) {
520 CHECK_EQ(1u, profile_fds.size());
521 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000522 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800523 if (reference_profile_fd != -1) {
524 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000525 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800526
527 for (const unique_fd& fd : profile_fds) {
528 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
529 }
530
531 for (const unique_fd& fd : apk_fds) {
532 AddArg("--apk-fd=" + std::to_string(fd.get()));
533 }
534
535 for (const std::string& dex_location : dex_locations) {
536 AddArg("--dex-location=" + dex_location);
537 }
538
539 if (copy_and_update) {
540 AddArg("--copy-and-update-profile-key");
541 }
542
Calin Juravle78728f32019-11-08 17:55:46 -0800543 if (for_snapshot) {
544 AddArg("--force-merge");
545 }
546
547 if (for_boot_image) {
548 AddArg("--boot-image-merge");
549 }
550
yawannga27559e2020-11-13 19:17:44 +0000551 // The percent won't exceed 100, otherwise, don't set it and use the
552 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000553 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000554 "dalvik.vm.bgdexopt.new-classes-percent",
555 /*default*/std::numeric_limits<uint32_t>::max());
556 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000557 AddArg("--min-new-classes-percent-change=" +
558 std::to_string(min_new_classes_percent_change));
559 }
560
yawannga27559e2020-11-13 19:17:44 +0000561 // The percent won't exceed 100, otherwise, don't set it and use the
562 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000563 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000564 "dalvik.vm.bgdexopt.new-methods-percent",
565 /*default*/std::numeric_limits<uint32_t>::max());
566 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000567 AddArg("--min-new-methods-percent-change=" +
568 std::to_string(min_new_methods_percent_change));
569 }
570
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800571 // Do not add after dex2oat_flags, they should override others for debugging.
572 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800573 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700574
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800575 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
576 const unique_fd& reference_profile_fd,
577 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800578 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
579 bool for_snapshot = false,
580 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800581 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800582 reference_profile_fd,
583 apk_fds,
584 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800585 /*copy_and_update=*/ false,
586 for_snapshot,
587 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800588 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700589
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800590 void SetupCopyAndUpdate(unique_fd&& profile_fd,
591 unique_fd&& reference_profile_fd,
592 unique_fd&& apk_fd,
593 const std::string& dex_location) {
594 // The fds need to stay open longer than the scope of the function, so put them into a local
595 // variable vector.
596 profiles_fd_.push_back(std::move(profile_fd));
597 apk_fds_.push_back(std::move(apk_fd));
598 reference_profile_fd_ = std::move(reference_profile_fd);
599 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800600 SetupArgs(profiles_fd_,
601 reference_profile_fd_,
602 apk_fds_,
603 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800604 /*copy_and_update=*/true,
605 /*for_snapshot*/false,
606 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800607 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000608
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800609 void SetupDump(const std::vector<unique_fd>& profiles_fd,
610 const unique_fd& reference_profile_fd,
611 const std::vector<std::string>& dex_locations,
612 const std::vector<unique_fd>& apk_fds,
613 const unique_fd& output_fd) {
614 AddArg("--dump-only");
615 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800616 SetupArgs(profiles_fd,
617 reference_profile_fd,
618 apk_fds,
619 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800620 /*copy_and_update=*/false,
621 /*for_snapshot*/false,
622 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800623 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000624
Victor Hsiehc9821f12020-08-07 11:32:29 -0700625 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800626 void Exec() {
627 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
628 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000629
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800630 private:
631 unique_fd reference_profile_fd_;
632 std::vector<unique_fd> profiles_fd_;
633 std::vector<unique_fd> apk_fds_;
634};
Mathieu Chartier31636522018-11-09 23:53:07 +0000635
Calin Juravle3b758282021-06-08 08:04:52 -0700636static int analyze_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800637 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800638 std::vector<unique_fd> profiles_fd;
639 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800640 open_profile_files(uid, package_name, location, is_secondary_dex,
641 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800642 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700643 // Skip profile guided compilation because no profiles were found.
644 // Or if the reference profile info couldn't be opened.
Calin Juravle3b758282021-06-08 08:04:52 -0700645 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646 }
647
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800648 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700649 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
650 const std::vector<std::string>& dex_locations = std::vector<std::string>();
651 profman_merge.SetupMerge(
652 profiles_fd,
653 reference_profile_fd,
654 apk_fds,
655 dex_locations,
656 /* for_snapshot= */ false,
657 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700658 pid_t pid = fork();
659 if (pid == 0) {
660 /* child -- drop privileges before continuing */
661 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800662 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700663 }
664 /* parent */
665 int return_code = wait_child(pid);
666 bool need_to_compile = false;
Calin Juravle3b758282021-06-08 08:04:52 -0700667 bool empty_profiles = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700668 bool should_clear_current_profiles = false;
669 bool should_clear_reference_profile = false;
670 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800671 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700672 } else {
673 return_code = WEXITSTATUS(return_code);
674 switch (return_code) {
675 case PROFMAN_BIN_RETURN_CODE_COMPILE:
676 need_to_compile = true;
677 should_clear_current_profiles = true;
678 should_clear_reference_profile = false;
679 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700680 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
Jeff Sharkey90aff262016-12-12 14:28:24 -0700681 need_to_compile = false;
682 should_clear_current_profiles = false;
683 should_clear_reference_profile = false;
684 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700685 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
686 need_to_compile = false;
687 empty_profiles = true;
688 should_clear_current_profiles = false;
689 should_clear_reference_profile = false;
690 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700691 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800692 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700693 need_to_compile = false;
694 should_clear_current_profiles = true;
695 should_clear_reference_profile = true;
696 break;
697 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
698 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
699 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800700 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701 need_to_compile = false;
702 should_clear_current_profiles = false;
703 should_clear_reference_profile = false;
704 break;
Calin Juravle76561322019-11-14 09:08:52 -0800705 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
706 need_to_compile = false;
707 should_clear_current_profiles = true;
708 should_clear_reference_profile = true;
709 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700710 default:
711 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800712 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800713 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700714 need_to_compile = false;
715 should_clear_current_profiles = true;
716 should_clear_reference_profile = true;
717 break;
718 }
719 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800720
Jeff Sharkey90aff262016-12-12 14:28:24 -0700721 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800722 if (is_secondary_dex) {
723 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800724 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
725 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800726 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800727 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800728 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700729 }
730 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800731 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700732 }
Calin Juravle3b758282021-06-08 08:04:52 -0700733 int result = 0;
734 if (need_to_compile) {
735 result = PROFILES_ANALYSIS_OPTIMIZE;
736 } else if (empty_profiles) {
737 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
738 } else {
739 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
740 }
741 return result;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742}
743
Calin Juravle114f0812017-03-08 19:05:07 -0800744// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle3b758282021-06-08 08:04:52 -0700745// The analysis is done for a single profile name (which corresponds to a single code path).
746//
747// Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
748// that makes it worth to recompile the package.
749// If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
750// merged into the reference profiles accessible with open_reference_profile().
751//
752// Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
753// As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
754// empty.
755int analyze_primary_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800756 const std::string& profile_name) {
757 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800758}
759
Calin Juravle408cd4a2018-01-20 23:34:18 -0800760bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
761 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800762 std::vector<unique_fd> profile_fds;
763 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800764 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
765 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700766
Calin Juravle408cd4a2018-01-20 23:34:18 -0800767 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800768 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800770 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700771 const bool has_profiles = !profile_fds.empty();
772
773 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800774 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 return false;
776 }
777
Calin Juravle114f0812017-03-08 19:05:07 -0800778 unique_fd output_fd(open(out_file_name.c_str(),
779 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700780 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800781 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700782 return false;
783 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800784
Jeff Sharkey90aff262016-12-12 14:28:24 -0700785 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800786 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800787 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
788 if (apk_fd == -1) {
789 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
790 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700791 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700792 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800793 apk_fds.push_back(std::move(apk_fd));
794
Jeff Sharkey90aff262016-12-12 14:28:24 -0700795
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800796 RunProfman profman_dump;
797 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700798 pid_t pid = fork();
799 if (pid == 0) {
800 /* child -- drop privileges before continuing */
801 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800802 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700803 }
804 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700805 int return_code = wait_child(pid);
806 if (!WIFEXITED(return_code)) {
807 LOG(WARNING) << "profman failed for package " << pkgname << ": "
808 << return_code;
809 return false;
810 }
811 return true;
812}
813
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700814bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800815 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700816 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
817 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800818 package_name,
819 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700820 /*read_write*/ true,
821 /*secondary*/ false));
822 if (in_fd.get() < 0) {
823 PLOG(WARNING) << "Could not open profile " << system_profile;
824 return false;
825 }
826 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800827 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700828 return false;
829 }
830
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700831 // As a security measure we want to write the profile information with the reduced capabilities
832 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700833 pid_t pid = fork();
834 if (pid == 0) {
835 /* child -- drop privileges before continuing */
836 drop_capabilities(packageUid);
837
838 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
839 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200840 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
841 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700842 }
843 // This implies that the app owning this profile is running
844 // (and has acquired the lock).
845 //
846 // The app never acquires the lock for the reference profiles of primary apks.
847 // Only dex2oat from installd will do that. Since installd is single threaded
848 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200849 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
850 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700851 return false;
852 }
853
854 bool truncated = ftruncate(out_fd.get(), 0) == 0;
855 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200856 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
857 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700858 }
859
860 // Copy over data.
861 static constexpr size_t kBufferSize = 4 * 1024;
862 char buffer[kBufferSize];
863 while (true) {
864 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
865 if (bytes == 0) {
866 break;
867 }
868 write(out_fd.get(), buffer, bytes);
869 }
870 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200871 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
872 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700873 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700874 // Use _exit since we don't want to run the global destructors in the child.
875 // b/62597429
876 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700877 }
878 /* parent */
879 int return_code = wait_child(pid);
880 return return_code == 0;
881}
882
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
884 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
885 if (EndsWith(oat_path, ".dex")) {
886 std::string new_path = oat_path;
887 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800888 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700889 return new_path;
890 }
891
892 // An odex entry. Not that this may not be an extension, e.g., in the OTA
893 // case (where the base name will have an extension for the B artifact).
894 size_t odex_pos = oat_path.rfind(".odex");
895 if (odex_pos != std::string::npos) {
896 std::string new_path = oat_path;
897 new_path.replace(odex_pos, strlen(".odex"), new_ext);
898 CHECK_NE(new_path.find(new_ext), std::string::npos);
899 return new_path;
900 }
901
902 // Don't know how to handle this.
903 return "";
904}
905
906// Translate the given oat path to an art (app image) path. An empty string
907// denotes an error.
908static std::string create_image_filename(const std::string& oat_path) {
909 return replace_file_extension(oat_path, ".art");
910}
911
912// Translate the given oat path to a vdex path. An empty string denotes an error.
913static std::string create_vdex_filename(const std::string& oat_path) {
914 return replace_file_extension(oat_path, ".vdex");
915}
916
Jeff Sharkey90aff262016-12-12 14:28:24 -0700917static int open_output_file(const char* file_name, bool recreate, int permissions) {
918 int flags = O_RDWR | O_CREAT;
919 if (recreate) {
920 if (unlink(file_name) < 0) {
921 if (errno != ENOENT) {
922 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
923 }
924 }
925 flags |= O_EXCL;
926 }
927 return open(file_name, flags, permissions);
928}
929
Calin Juravle2289c0a2017-02-15 12:44:14 -0800930static bool set_permissions_and_ownership(
931 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
932 // Primary apks are owned by the system. Secondary dex files are owned by the app.
933 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934 if (fchmod(fd,
935 S_IRUSR|S_IWUSR|S_IRGRP |
936 (is_public ? S_IROTH : 0)) < 0) {
937 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
938 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800939 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940 ALOGE("installd cannot chown '%s' during dexopt\n", path);
941 return false;
942 }
943 return true;
944}
945
946static bool IsOutputDalvikCache(const char* oat_dir) {
947 // InstallerConnection.java (which invokes installd) transforms Java null arguments
948 // into '!'. Play it safe by handling it both.
949 // TODO: ensure we never get null.
950 // TODO: pass a flag instead of inferring if the output is dalvik cache.
951 return oat_dir == nullptr || oat_dir[0] == '!';
952}
953
Calin Juravled23dee72017-07-06 16:29:11 -0700954// Best-effort check whether we can fit the the path into our buffers.
955// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
956// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
957// extension to the cache path (5 bytes).
958// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
959static bool validate_dex_path_size(const std::string& dex_path) {
960 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
961 LOG(ERROR) << "dex_path too long: " << dex_path;
962 return false;
963 }
964 return true;
965}
966
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800968 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700969 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700970 return false;
971 }
972
973 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800974 // Oat dirs for secondary dex files are already validated.
975 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700976 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
977 return false;
978 }
979 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
980 return false;
981 }
982 } else {
983 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
984 return false;
985 }
986 }
987 return true;
988}
989
Calin Juravle7a570e82017-01-14 16:23:30 -0800990// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700991UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700992 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100993
Calin Juravle7a570e82017-01-14 16:23:30 -0800994 const std::string image_path = create_image_filename(out_oat_path);
995 if (image_path.empty()) {
996 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700997 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800998 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100999
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001000 // In case there is a stale image, remove it now. Ignore any error.
1001 unlink(image_path.c_str());
1002
1003 // Not enabled, exit.
1004 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001005 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001006 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001007 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1008 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001009 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001010 }
1011 // Recreate is true since we do not want to modify a mapped image. If the app is
1012 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001013 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001014 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001015 image_path,
1016 UnlinkIgnoreResult);
1017 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001018 // Could not create application image file. Go on since we can compile without it.
1019 LOG(ERROR) << "installd could not create '" << image_path
1020 << "' for image file during dexopt";
1021 // If we have a valid image file path but no image fd, explicitly erase the image file.
1022 if (unlink(image_path.c_str()) < 0) {
1023 if (errno != ENOENT) {
1024 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1025 }
1026 }
1027 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001028 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001029 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001030 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001031 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001032
Victor Hsiehcb35a062020-08-13 16:11:13 -07001033 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -08001034}
1035
1036// Creates the dexopt swap file if necessary and return its fd.
1037// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001038unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001039 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001040 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001041 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001042 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001043 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001044 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001045 if (swap_fd.get() < 0) {
1046 // Could not create swap file. Optimistically go on and hope that we can compile
1047 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001048 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001049 } else {
1050 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001051 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001052 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1053 }
1054 }
1055 return swap_fd;
1056}
1057
1058// Opens the reference profiles if needed.
1059// Note that the reference profile might not exist so it's OK if the fd will be -1.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001060UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001061 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001062 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001063 // If we are not profile guided compilation, or we are compiling system server
1064 // do not bother to open the profiles; we won't be using them.
1065 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001066 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +00001067 }
1068
1069 // If this is a secondary dex path which is public do not open the profile.
1070 // We cannot compile public secondary dex paths with profiles. That's because
1071 // it will expose how the dex files are used by their owner.
1072 //
1073 // Note that the PackageManager is responsible to set the is_public flag for
1074 // primary apks and we do not check it here. In some cases, e.g. when
1075 // compiling with a public profile from the .dm file the PackageManager will
1076 // set is_public toghether with the profile guided compilation.
1077 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001078 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001079 }
Calin Juravle114f0812017-03-08 19:05:07 -08001080
1081 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001082 std::string location;
1083 if (is_secondary_dex) {
1084 location = dex_path;
1085 } else {
1086 if (profile_name == nullptr) {
1087 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001088 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001089 } else {
1090 location = profile_name;
1091 }
1092 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001093 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
1094 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001095}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001096
Victor Hsiehcb35a062020-08-13 16:11:13 -07001097// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1098// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001099bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001100 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -07001101 bool profile_guided, UniqueFile* in_vdex_wrapper,
1102 UniqueFile* out_vdex_wrapper) {
1103 CHECK(in_vdex_wrapper != nullptr);
1104 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001105 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1106 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001107 char in_odex_path[PKG_PATH_MAX];
1108 int dexopt_action = abs(dexopt_needed);
1109 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001110
1111 // Infer the name of the output VDEX.
1112 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1113 if (out_vdex_path_str.empty()) {
1114 return false;
1115 }
1116
1117 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001118 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001119 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1120 const char* path = nullptr;
1121 if (is_odex_location) {
1122 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1123 path = in_odex_path;
1124 } else {
1125 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001126 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 }
1128 } else {
1129 path = out_oat_path;
1130 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001131 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132 if (in_vdex_path_str.empty()) {
1133 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001134 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001136 // We can update in place when all these conditions are met:
1137 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1138 // on /system typically cannot be updated in place).
1139 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1140 // cannot be currently used by a running process.
1141 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1142 // different vdex files to operate.
1143 update_vdex_in_place =
1144 (in_vdex_path_str == out_vdex_path_str) &&
1145 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1146 !profile_guided;
1147 if (update_vdex_in_place) {
1148 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001149 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1150 in_vdex_path_str);
1151 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001152 // If we failed to open the file, we cannot update it in place.
1153 update_vdex_in_place = false;
1154 }
1155 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001156 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1157 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001158 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001159 }
1160
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001161 // If we are updating the vdex in place, we do not need to recreate a vdex,
1162 // and can use the same existing one.
1163 if (update_vdex_in_place) {
1164 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1165 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001166 out_vdex_wrapper->reset(
1167 in_vdex_wrapper->fd(),
1168 out_vdex_path_str,
1169 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001170 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1171 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001172 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001173 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001174 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001175 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001176 out_vdex_path_str,
1177 UnlinkIgnoreResult);
1178 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001179 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1180 return false;
1181 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001182 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001183 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001184 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001185 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1186 return false;
1187 }
1188
1189 // If we got here we successfully opened the vdex files.
1190 return true;
1191}
1192
1193// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001194UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1195 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1196 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001197 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001198 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001199 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001200 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001202 out_oat_path,
1203 UnlinkIgnoreResult);
1204 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001205 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001206 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001207 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001208 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001209 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001210 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001211 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001212}
1213
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001214// Creates RDONLY fds for oat and vdex files, if exist.
1215// Returns false if it fails to create oat out path for the given apk path.
1216// Note that the method returns true even if the files could not be opened.
1217bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1218 const std::string& oat_dir,
1219 const std::string& instruction_set,
1220 bool is_secondary_dex,
1221 unique_fd* oat_file_fd,
1222 unique_fd* vdex_file_fd) {
1223 char oat_path[PKG_PATH_MAX];
1224 if (!create_oat_out_path(apk_path.c_str(),
1225 instruction_set.c_str(),
1226 oat_dir.c_str(),
1227 is_secondary_dex,
1228 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001229 LOG(ERROR) << "Could not create oat out path for "
1230 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001231 return false;
1232 }
1233 oat_file_fd->reset(open(oat_path, O_RDONLY));
1234 if (oat_file_fd->get() < 0) {
1235 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1236 }
1237
1238 std::string vdex_filename = create_vdex_filename(oat_path);
1239 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1240 if (vdex_file_fd->get() < 0) {
1241 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1242 }
1243
1244 return true;
1245}
1246
Calin Juravle80a21252017-01-17 14:43:25 -08001247// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001248// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1249// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1250// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001251class RunDexoptAnalyzer : public ExecVHelper {
1252 public:
1253 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001254 int vdex_fd,
1255 int oat_fd,
1256 int zip_fd,
1257 const std::string& instruction_set,
1258 const std::string& compiler_filter,
Calin Juravle3b758282021-06-08 08:04:52 -07001259 int profile_analysis_result,
David Brazdil4f6027a2019-03-19 11:44:21 +00001260 bool downgrade,
1261 const char* class_loader_context,
1262 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001263 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001264
1265 // We always run the analyzer in the background job.
1266 const char* dexoptanalyzer_bin = select_execution_binary(
1267 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001268
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001269 std::string dex_file_arg = "--dex-file=" + dex_file;
1270 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1271 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1272 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1273 std::string isa_arg = "--isa=" + instruction_set;
1274 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle3b758282021-06-08 08:04:52 -07001275 std::string profile_analysis_arg = "--profile-analysis-result="
1276 + std::to_string(profile_analysis_result);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001277 const char* downgrade_flag = "--downgrade";
1278 std::string class_loader_context_arg = "--class-loader-context=";
1279 if (class_loader_context != nullptr) {
1280 class_loader_context_arg += class_loader_context;
1281 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001282 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1283 if (!class_loader_context_fds.empty()) {
1284 class_loader_context_fds_arg += class_loader_context_fds;
1285 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001286
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001287 // program name, dex file, isa, filter
1288 AddArg(dex_file_arg);
1289 AddArg(isa_arg);
1290 AddArg(compiler_filter_arg);
1291 if (oat_fd >= 0) {
1292 AddArg(oat_fd_arg);
1293 }
1294 if (vdex_fd >= 0) {
1295 AddArg(vdex_fd_arg);
1296 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001297 AddArg(zip_fd_arg);
Calin Juravle3b758282021-06-08 08:04:52 -07001298 AddArg(profile_analysis_arg);
1299
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001300 if (downgrade) {
1301 AddArg(downgrade_flag);
1302 }
1303 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001304 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001305 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001306 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001307 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001308 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001309
Orion Hodson5f6b3ad2021-07-01 12:12:40 +01001310 // On-device signing related. odsign sets the system property odsign.verification.success if
1311 // AOT artifacts have the expected signatures.
1312 const bool trust_art_apex_data_files =
1313 ::android::base::GetBoolProperty("odsign.verification.success", false);
1314 if (!trust_art_apex_data_files) {
1315 AddRuntimeArg("-Xdeny-art-apex-data-files");
1316 }
1317
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001318 PrepareArgs(dexoptanalyzer_bin);
1319 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001320
1321 // Dexoptanalyzer mode which flattens the given class loader context and
1322 // prints a list of its dex files in that flattened order.
1323 RunDexoptAnalyzer(const char* class_loader_context) {
1324 CHECK(class_loader_context != nullptr);
1325
1326 // We always run the analyzer in the background job.
1327 const char* dexoptanalyzer_bin = select_execution_binary(
1328 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1329
1330 AddArg("--flatten-class-loader-context");
1331 AddArg(std::string("--class-loader-context=") + class_loader_context);
1332 PrepareArgs(dexoptanalyzer_bin);
1333 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001334};
Calin Juravle80a21252017-01-17 14:43:25 -08001335
1336// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001337static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001338 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001339 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001340 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001341 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001342 return false;
1343 }
Calin Juravle114f0812017-03-08 19:05:07 -08001344 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001345
Calin Juravle80a21252017-01-17 14:43:25 -08001346 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001347 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1348 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001349 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001350 return false;
1351 }
1352
1353 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001354 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001355
Calin Juravle7d765462017-09-04 15:57:10 -07001356 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001357 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001358 return false;
1359 }
1360
1361 return true;
1362}
1363
Calin Juravle7d765462017-09-04 15:57:10 -07001364// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1365// secondary dex files. This return codes are returned by the child process created for
1366// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001367
Andreas Gampe194fe422018-02-28 20:16:19 -08001368enum DexoptAnalyzerSkipCodes {
1369 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001370 // Specific errors are encoded in the name.
1371 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1372 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1373 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1374 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1375 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001376 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001377 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001378};
Calin Juravle7d765462017-09-04 15:57:10 -07001379
1380// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001381// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1382// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001383// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1384// of dexoptanalyzer.
1385static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001386 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001387 // The result values are defined in dexoptanalyzer.
1388 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001389 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001390 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001391 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001392 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001393 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001394 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001395 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001396 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001397 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1398 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001399 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1400 " Expected odex file status for secondary dex %s"
1401 " : dexoptanalyzer result=%d",
1402 dex_path.c_str(),
1403 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001404 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001405 }
1406
1407 // Use a second switch for enum switch-case analysis.
1408 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001409 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001410 // If the file does not exist there's no need for dexopt.
1411 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1412 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001413
1414 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1415 *error_msg = "Dexoptanalyzer path validation failed";
1416 return false;
1417 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1418 *error_msg = "Dexoptanalyzer open zip failed";
1419 return false;
1420 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1421 *error_msg = "Dexoptanalyzer dir preparation failed";
1422 return false;
1423 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1424 *error_msg = "Dexoptanalyzer open output failed";
1425 return false;
1426 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1427 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001428 return false;
1429 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001430
1431 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1432 dex_path.c_str(),
1433 result);
1434 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001435}
1436
Calin Juravle7d765462017-09-04 15:57:10 -07001437enum SecondaryDexAccess {
1438 kSecondaryDexAccessReadOk = 0,
1439 kSecondaryDexAccessDoesNotExist = 1,
1440 kSecondaryDexAccessPermissionError = 2,
1441 kSecondaryDexAccessIOError = 3
1442};
1443
1444static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1445 // Check if the path exists and can be read. If not, there's nothing to do.
1446 if (access(dex_path.c_str(), R_OK) == 0) {
1447 return kSecondaryDexAccessReadOk;
1448 } else {
1449 if (errno == ENOENT) {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001450 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1451 "Secondary dex does not exist: %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001452 return kSecondaryDexAccessDoesNotExist;
1453 } else {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001454 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1455 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
Calin Juravle7d765462017-09-04 15:57:10 -07001456 return errno == EACCES
1457 ? kSecondaryDexAccessPermissionError
1458 : kSecondaryDexAccessIOError;
1459 }
1460 }
1461}
1462
1463static bool is_file_public(const std::string& filename) {
1464 struct stat file_stat;
1465 if (stat(filename.c_str(), &file_stat) == 0) {
1466 return (file_stat.st_mode & S_IROTH) != 0;
1467 }
1468 return false;
1469}
1470
1471// Create the oat file structure for the secondary dex 'dex_path' and assign
1472// the individual path component to the 'out_' parameters.
1473static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001474 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001475 size_t dirIndex = dex_path.rfind('/');
1476 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001477 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001478 return false;
1479 }
1480 // TODO(calin): we have similar computations in at lest 3 other places
1481 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1482 // using string append.
1483 std::string apk_dir = dex_path.substr(0, dirIndex);
1484 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1485 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1486
1487 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1488 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001489 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001490 return false;
1491 }
1492 return true;
1493}
1494
1495// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1496// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001497static bool validate_dexopt_storage_flags(int dexopt_flags,
1498 int* out_storage_flag,
1499 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001500 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1501 *out_storage_flag = FLAG_STORAGE_CE;
1502 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001503 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001504 return false;
1505 }
1506 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1507 *out_storage_flag = FLAG_STORAGE_DE;
1508 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001509 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001510 return false;
1511 }
1512 return true;
1513}
1514
David Brazdil4f6027a2019-03-19 11:44:21 +00001515static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1516 /* out */ std::vector<std::string>* context_dex_paths) {
1517 if (class_loader_context == nullptr) {
1518 return true;
1519 }
1520
1521 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1522
1523 // Pipe to get the hash result back from our child process.
1524 unique_fd pipe_read, pipe_write;
1525 if (!Pipe(&pipe_read, &pipe_write)) {
1526 PLOG(ERROR) << "Failed to create pipe";
1527 return false;
1528 }
1529
1530 pid_t pid = fork();
1531 if (pid == 0) {
1532 // child -- drop privileges before continuing.
1533 drop_capabilities(uid);
1534
1535 // Route stdout to `pipe_write`
1536 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1537 pipe_write.reset();
1538 pipe_read.reset();
1539
1540 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1541 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1542 }
1543
1544 /* parent */
1545 pipe_write.reset();
1546
1547 std::string str_dex_paths;
1548 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1549 PLOG(ERROR) << "Failed to read from pipe";
1550 return false;
1551 }
1552 pipe_read.reset();
1553
1554 int return_code = wait_child(pid);
1555 if (!WIFEXITED(return_code)) {
1556 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1557 return false;
1558 }
1559
1560 constexpr int kFlattenClassLoaderContextSuccess = 50;
1561 return_code = WEXITSTATUS(return_code);
1562 if (return_code != kFlattenClassLoaderContextSuccess) {
1563 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1564 return false;
1565 }
1566
1567 if (!str_dex_paths.empty()) {
1568 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1569 }
1570 return true;
1571}
1572
1573static int open_dex_paths(const std::vector<std::string>& dex_paths,
1574 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1575 for (const std::string& dex_path : dex_paths) {
1576 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1577 if (zip_fds->back().get() < 0) {
1578 *error_msg = StringPrintf(
1579 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1580 if (errno == ENOENT) {
1581 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1582 } else {
1583 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1584 }
1585 }
1586 }
1587 return 0;
1588}
1589
1590static std::string join_fds(const std::vector<unique_fd>& fds) {
1591 std::stringstream ss;
1592 bool is_first = true;
1593 for (const unique_fd& fd : fds) {
1594 if (is_first) {
1595 is_first = false;
1596 } else {
1597 ss << ":";
1598 }
1599 ss << fd.get();
1600 }
1601 return ss.str();
1602}
1603
Keun young Park65578d62021-06-28 17:52:05 -07001604void control_dexopt_blocking(bool block) {
1605 dexopt_status_->control_dexopt_blocking(block);
1606}
1607
1608bool is_dexopt_blocked() {
1609 return dexopt_status_->is_dexopt_blocked();
1610}
1611
1612enum SecondaryDexOptProcessResult {
1613 kSecondaryDexOptProcessOk = 0,
1614 kSecondaryDexOptProcessCancelled = 1,
1615 kSecondaryDexOptProcessError = 2
1616};
1617
Calin Juravlec9eab382017-01-25 01:17:17 -08001618// Processes the dex_path as a secondary dex files and return true if the path dex file should
Keun young Park65578d62021-06-28 17:52:05 -07001619// be compiled.
1620// Returns: kSecondaryDexOptProcessError for errors (logged).
1621// kSecondaryDexOptProcessOk if the secondary dex path was process successfully.
1622// kSecondaryDexOptProcessCancelled if the processing was cancelled.
1623//
1624// When returning kSecondaryDexOptProcessOk, the output parameters will be:
Calin Juravleebc8a792017-04-04 20:21:05 -07001625// - is_public_out: whether or not the oat file should not be made public
1626// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1627// - oat_dir_out: the oat dir path where the oat file should be stored
Keun young Park65578d62021-06-28 17:52:05 -07001628static SecondaryDexOptProcessResult process_secondary_dex_dexopt(const std::string& dex_path,
1629 const char* pkgname, int dexopt_flags, const char* volume_uuid, int uid,
1630 const char* instruction_set, const char* compiler_filter, bool* is_public_out,
1631 int* dexopt_needed_out, std::string* oat_dir_out, bool downgrade,
1632 const char* class_loader_context, const std::vector<std::string>& context_dex_paths,
1633 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001634 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Keun young Park65578d62021-06-28 17:52:05 -07001635
1636 if (dexopt_status_->is_dexopt_blocked()) {
1637 return kSecondaryDexOptProcessCancelled;
1638 }
1639
Calin Juravle80a21252017-01-17 14:43:25 -08001640 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001641 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1642 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001643 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001644 }
Calin Juravle7d765462017-09-04 15:57:10 -07001645 // Compute the oat dir as it's not easy to extract it from the child computation.
1646 char oat_path[PKG_PATH_MAX];
1647 char oat_dir[PKG_PATH_MAX];
1648 char oat_isa_dir[PKG_PATH_MAX];
1649 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001650 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1651 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001652 return kSecondaryDexOptProcessError;
Calin Juravled23dee72017-07-06 16:29:11 -07001653 }
Calin Juravle7d765462017-09-04 15:57:10 -07001654 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001655
Keun young Park65578d62021-06-28 17:52:05 -07001656 bool cancelled = false;
1657 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1658 if (cancelled) {
1659 return kSecondaryDexOptProcessCancelled;
1660 }
Calin Juravle80a21252017-01-17 14:43:25 -08001661 if (pid == 0) {
1662 // child -- drop privileges before continuing.
1663 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001664
1665 // Validate the path structure.
1666 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001667 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1668 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001669 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001670 }
1671
1672 // Open the dex file.
1673 unique_fd zip_fd;
1674 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1675 if (zip_fd.get() < 0) {
1676 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001677 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001678 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001679 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001680 }
1681 }
1682
David Brazdil4f6027a2019-03-19 11:44:21 +00001683 // Open class loader context dex files.
1684 std::vector<unique_fd> context_zip_fds;
1685 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1686 if (open_dex_paths_rc != 0) {
1687 _exit(open_dex_paths_rc);
1688 }
1689
Calin Juravle7d765462017-09-04 15:57:10 -07001690 // Prepare the oat directories.
1691 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001692 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001693 }
1694
1695 // Open the vdex/oat files if any.
1696 unique_fd oat_file_fd;
1697 unique_fd vdex_file_fd;
1698 if (!maybe_open_oat_and_vdex_file(dex_path,
1699 *oat_dir_out,
1700 instruction_set,
1701 true /* is_secondary_dex */,
1702 &oat_file_fd,
1703 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001704 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001705 }
1706
1707 // Analyze profiles.
Calin Juravle3b758282021-06-08 08:04:52 -07001708 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
Calin Juravle824a64d2018-01-18 20:23:17 -08001709 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001710
1711 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001712 // Note that we do not do it before the fork since opening the files is required to happen
1713 // after forking.
1714 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1715 vdex_file_fd.get(),
1716 oat_file_fd.get(),
1717 zip_fd.get(),
1718 instruction_set,
Calin Juravle3b758282021-06-08 08:04:52 -07001719 compiler_filter,
1720 profile_analysis_result,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001721 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001722 class_loader_context,
1723 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001724 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001725 }
1726
1727 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001728 int result = wait_child(pid);
Keun young Park65578d62021-06-28 17:52:05 -07001729 cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Calin Juravle80a21252017-01-17 14:43:25 -08001730 if (!WIFEXITED(result)) {
Keun young Park65578d62021-06-28 17:52:05 -07001731 if ((WTERMSIG(result) == SIGKILL) && cancelled) {
1732 LOG(INFO) << "dexoptanalyzer cancelled for path:" << dex_path;
1733 return kSecondaryDexOptProcessCancelled;
1734 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001735 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1736 dex_path.c_str(),
1737 result);
1738 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001739 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001740 }
1741 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001742 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001743 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1744 result,
1745 dexopt_needed_out,
1746 error_msg);
1747 if (!success) {
1748 LOG(ERROR) << *error_msg;
1749 }
Calin Juravle7d765462017-09-04 15:57:10 -07001750
1751 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1752
Calin Juravle80a21252017-01-17 14:43:25 -08001753 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001754 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1755 // makes the code simpler; force compilation is only needed during tests).
1756 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001757 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001758 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001759 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1760 }
1761
Calin Juravle7d765462017-09-04 15:57:10 -07001762 // Check if we should make the oat file public.
1763 // Note that if the dex file is not public the compiled code cannot be made public.
1764 // It is ok to check this flag outside in the parent process.
1765 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1766
Keun young Park65578d62021-06-28 17:52:05 -07001767 return success ? kSecondaryDexOptProcessOk : kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001768}
1769
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001770static std::string format_dexopt_error(int status, const char* dex_path) {
1771 if (WIFEXITED(status)) {
1772 int int_code = WEXITSTATUS(status);
1773 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1774 if (code_name != nullptr) {
1775 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1776 }
1777 }
1778 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001779}
1780
Keun young Park65578d62021-06-28 17:52:05 -07001781
Calin Juravlec9eab382017-01-25 01:17:17 -08001782int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001783 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001784 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001785 bool downgrade, int target_sdk_version, const char* profile_name,
Keun young Park65578d62021-06-28 17:52:05 -07001786 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg,
1787 /* out */ bool* completed) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001788 CHECK(pkgname != nullptr);
1789 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001790 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001791 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1792 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001793
Keun young Park65578d62021-06-28 17:52:05 -07001794 bool local_completed; // local placeholder for nullptr case
1795 if (completed == nullptr) {
1796 completed = &local_completed;
1797 }
1798 *completed = true;
1799 if (dexopt_status_->is_dexopt_blocked()) {
1800 *completed = false;
1801 return 0;
1802 }
1803
Calin Juravled23dee72017-07-06 16:29:11 -07001804 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001805 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001806 return -1;
1807 }
1808
1809 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001810 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1811 class_loader_context);
1812 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001813 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001814 }
1815
Calin Juravleebc8a792017-04-04 20:21:05 -07001816 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001817 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1818 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1819 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001820 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001821 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001822 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001823 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001824 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001825 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001826
1827 // Check if we're dealing with a secondary dex file and if we need to compile it.
1828 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001829 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001830 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001831 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1832 *error_msg = "Failed acquiring context dex paths";
1833 return -1; // We had an error, logged in the process method.
1834 }
Keun young Park65578d62021-06-28 17:52:05 -07001835 SecondaryDexOptProcessResult sec_dex_result = process_secondary_dex_dexopt(dex_path,
1836 pkgname, dexopt_flags, volume_uuid, uid,instruction_set, compiler_filter,
1837 &is_public, &dexopt_needed, &oat_dir_str, downgrade, class_loader_context,
1838 context_dex_paths, error_msg);
1839 if (sec_dex_result == kSecondaryDexOptProcessOk) {
Calin Juravle80a21252017-01-17 14:43:25 -08001840 oat_dir = oat_dir_str.c_str();
1841 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1842 return 0; // Nothing to do, report success.
1843 }
Keun young Park65578d62021-06-28 17:52:05 -07001844 } else if (sec_dex_result == kSecondaryDexOptProcessCancelled) {
1845 // cancelled, not an error.
1846 *completed = false;
1847 return 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001848 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001849 if (error_msg->empty()) { // TODO: Make this a CHECK.
1850 *error_msg = "Failed processing secondary.";
1851 }
Calin Juravle80a21252017-01-17 14:43:25 -08001852 return -1; // We had an error, logged in the process method.
1853 }
1854 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001855 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001856 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001857 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1858 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1859 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001860
1861 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001862 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1863 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001864 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1865 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001866 return -1;
1867 }
1868
David Brazdil4f6027a2019-03-19 11:44:21 +00001869 // Open class loader context dex files.
1870 std::vector<unique_fd> context_input_fds;
1871 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1872 LOG(ERROR) << *error_msg;
1873 return -1;
1874 }
1875
Calin Juravle7a570e82017-01-14 16:23:30 -08001876 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001877 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1878 instruction_set, is_secondary_dex);
1879 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001880 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001881 return -1;
1882 }
1883
1884 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001885 UniqueFile in_vdex;
1886 UniqueFile out_vdex;
1887 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1888 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1889 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001890 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001891 return -1;
1892 }
1893
Calin Juravlecb556e32017-04-04 20:22:50 -07001894 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1895 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1896 // fully inherit their parent context).
1897 // Note that for primary apk the oat files are created before, in a separate installd
1898 // call which also does the restorecon. TODO(calin): unify the paths.
1899 if (is_secondary_dex) {
1900 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1901 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001902 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1903 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001904 return -1;
1905 }
1906 }
1907
Jeff Sharkey90aff262016-12-12 14:28:24 -07001908 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001909 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001910
Calin Juravle7a570e82017-01-14 16:23:30 -08001911 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001912 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001913 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001914
Victor Hsiehcb35a062020-08-13 16:11:13 -07001915 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001916 // We don't create an app image without reference profile since there is no speedup from
1917 // loading it in that case and instead will be a small overhead.
1918 generate_app_image = false;
1919 }
1920
1921 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001922 UniqueFile out_image = maybe_open_app_image(
1923 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001924
Victor Hsiehcb35a062020-08-13 16:11:13 -07001925 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001926 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001927 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1928 dex_metadata_path);
1929 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001930 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1931 }
1932 }
1933
Victor Hsieh8948a862020-08-07 11:30:55 -07001934 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1935 RUNTIME_NATIVE_BOOT_NAMESPACE,
1936 ENABLE_JITZYGOTE_IMAGE,
1937 /*default_value=*/ "");
1938 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1939
Victor Hsiehe98e6512020-08-10 15:39:22 -07001940 // Decide whether to use dex2oat64.
1941 bool use_dex2oat64 = false;
1942 // Check whether the device even supports 64-bit ABIs.
1943 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1944 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1945 }
1946 const char* dex2oat_bin = select_execution_binary(
1947 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1948 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1949 background_job_compile);
1950
Victor Hsiehc9821f12020-08-07 11:32:29 -07001951 auto execv_helper = std::make_unique<ExecVHelper>();
1952
Andreas Gampe023b2242018-02-28 16:03:25 -08001953 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001954
Victor Hsiehc9821f12020-08-07 11:32:29 -07001955 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001956 runner.Initialize(out_oat,
1957 out_vdex,
1958 out_image,
1959 in_dex,
1960 in_vdex,
1961 dex_metadata,
1962 reference_profile,
1963 class_loader_context,
1964 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001965 swap_fd.get(),
1966 instruction_set,
1967 compiler_filter,
1968 debuggable,
1969 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001970 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001971 target_sdk_version,
1972 enable_hidden_api_checks,
1973 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001974 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001975 compilation_reason);
1976
Keun young Park65578d62021-06-28 17:52:05 -07001977 bool cancelled = false;
1978 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1979 if (cancelled) {
1980 return 0;
1981 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001983 // Need to set schedpolicy before dropping privileges
1984 // for cgroup migration. See details at b/175178520.
1985 SetDex2OatScheduling(boot_complete);
1986
Jeff Sharkey90aff262016-12-12 14:28:24 -07001987 /* child -- drop privileges before continuing */
1988 drop_capabilities(uid);
1989
Victor Hsiehcb35a062020-08-13 16:11:13 -07001990 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001991 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1992 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001993 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001994 }
1995
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001996 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001997 } else {
1998 int res = wait_child(pid);
Keun young Park65578d62021-06-28 17:52:05 -07001999 bool cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002000 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002001 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002002 } else {
Keun young Park65578d62021-06-28 17:52:05 -07002003 if ((WTERMSIG(res) == SIGKILL) && cancelled) {
2004 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- cancelled";
2005 // cancelled, not an error
2006 *completed = false;
2007 return 0;
2008 }
Andreas Gampe023b2242018-02-28 16:03:25 -08002009 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2010 << std::hex << std::setw(4) << res << ", process failed";
2011 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002012 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002013 }
2014 }
2015
Keun young Park65578d62021-06-28 17:52:05 -07002016 // TODO(b/156537504) Implement SWAP of completed files
Jeff Sharkey90aff262016-12-12 14:28:24 -07002017 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07002018 out_oat.DisableCleanup();
2019 out_vdex.DisableCleanup();
2020 out_image.DisableCleanup();
2021 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07002022
Keun young Park65578d62021-06-28 17:52:05 -07002023 *completed = true;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002024 return 0;
2025}
2026
Calin Juravlec9eab382017-01-25 01:17:17 -08002027// Try to remove the given directory. Log an error if the directory exists
2028// and is empty but could not be removed.
2029static bool rmdir_if_empty(const char* dir) {
2030 if (rmdir(dir) == 0) {
2031 return true;
2032 }
2033 if (errno == ENOENT || errno == ENOTEMPTY) {
2034 return true;
2035 }
2036 PLOG(ERROR) << "Failed to remove dir: " << dir;
2037 return false;
2038}
2039
2040// Try to unlink the given file. Log an error if the file exists and could not
2041// be unlinked.
2042static bool unlink_if_exists(const std::string& file) {
2043 if (unlink(file.c_str()) == 0) {
2044 return true;
2045 }
2046 if (errno == ENOENT) {
2047 return true;
2048
2049 }
2050 PLOG(ERROR) << "Could not unlink: " << file;
2051 return false;
2052}
2053
Calin Juravle7d765462017-09-04 15:57:10 -07002054enum ReconcileSecondaryDexResult {
2055 kReconcileSecondaryDexExists = 0,
2056 kReconcileSecondaryDexCleanedUp = 1,
2057 kReconcileSecondaryDexValidationError = 2,
2058 kReconcileSecondaryDexCleanUpError = 3,
2059 kReconcileSecondaryDexAccessIOError = 4,
2060};
Calin Juravlec9eab382017-01-25 01:17:17 -08002061
2062// Reconcile the secondary dex 'dex_path' and its generated oat files.
2063// Return true if all the parameters are valid and the secondary dex file was
2064// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2065// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2066// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2067// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2068// Return false if there were errors during processing. In this case
2069// out_secondary_dex_exists will be set to false.
2070bool reconcile_secondary_dex_file(const std::string& dex_path,
2071 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002072 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002073 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002074 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002075 if (isas.size() == 0) {
2076 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2077 return false;
2078 }
2079
Calin Juravle7d765462017-09-04 15:57:10 -07002080 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2081 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2082 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002083 return false;
2084 }
2085
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002086 // As a security measure we want to unlink art artifacts with the reduced capabilities
2087 // of the package user id. So we fork and drop capabilities in the child.
2088 pid_t pid = fork();
2089 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002090 /* child -- drop privileges before continuing */
2091 drop_capabilities(uid);
2092
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002093 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002094 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002095 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002096 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2097 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002098 _exit(kReconcileSecondaryDexValidationError);
2099 }
2100
2101 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2102 switch (access_check) {
2103 case kSecondaryDexAccessDoesNotExist:
2104 // File does not exist. Proceed with cleaning.
2105 break;
2106 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2107 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2108 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2109 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02002110 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2111 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07002112 _exit(kReconcileSecondaryDexValidationError);
2113 }
2114
2115 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002116 char oat_path[PKG_PATH_MAX];
2117 char oat_dir[PKG_PATH_MAX];
2118 char oat_isa_dir[PKG_PATH_MAX];
2119 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002120 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002121 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002122 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002123 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002124 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002125 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002126 }
Calin Juravle51314092017-05-18 15:33:05 -07002127
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002128 // Delete oat/vdex/art files.
2129 result = unlink_if_exists(oat_path) && result;
2130 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2131 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002132
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002133 // Delete profiles.
2134 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002135 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002136 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002137 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002138 result = unlink_if_exists(current_profile) && result;
2139 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002140
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002141 // We upgraded once the location of current profile for secondary dex files.
2142 // Check for any previous left-overs and remove them as well.
2143 std::string old_current_profile = dex_path + ".prof";
2144 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002145
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002146 // Try removing the directories as well, they might be empty.
2147 result = rmdir_if_empty(oat_isa_dir) && result;
2148 result = rmdir_if_empty(oat_dir) && result;
2149 }
Calin Juravle7d765462017-09-04 15:57:10 -07002150 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002151 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2152 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002153 }
2154 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002155 }
2156
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002157 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002158 if (!WIFEXITED(return_code)) {
2159 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2160 } else {
2161 return_code = WEXITSTATUS(return_code);
2162 }
2163
2164 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2165
2166 switch (return_code) {
2167 case kReconcileSecondaryDexCleanedUp:
2168 case kReconcileSecondaryDexValidationError:
2169 // If we couldn't validate assume the dex file does not exist.
2170 // This will purge the entry from the PM records.
2171 *out_secondary_dex_exists = false;
2172 return true;
2173 case kReconcileSecondaryDexExists:
2174 *out_secondary_dex_exists = true;
2175 return true;
2176 case kReconcileSecondaryDexAccessIOError:
2177 // We had an access IO error.
2178 // Return false so that we can try again.
2179 // The value of out_secondary_dex_exists does not matter in this case and by convention
2180 // is set to false.
2181 *out_secondary_dex_exists = false;
2182 return false;
2183 default:
2184 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2185 *out_secondary_dex_exists = false;
2186 return false;
2187 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002188}
2189
Alan Stokesa25d90c2017-10-16 10:56:00 +01002190// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2191// Returns true if all parameters are valid and the hash successfully computed and stored in
2192// out_secondary_dex_hash.
2193// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2194// the app.
2195// For any other errors (e.g. if any of the parameters are invalid) returns false.
2196bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002197 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002198 std::vector<uint8_t>* out_secondary_dex_hash) {
2199 out_secondary_dex_hash->clear();
2200
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002201 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002202
2203 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2204 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2205 << storage_flag;
2206 return false;
2207 }
2208
2209 // Pipe to get the hash result back from our child process.
2210 unique_fd pipe_read, pipe_write;
2211 if (!Pipe(&pipe_read, &pipe_write)) {
2212 PLOG(ERROR) << "Failed to create pipe";
2213 return false;
2214 }
2215
2216 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2217 // access data the app itself can access.
2218 pid_t pid = fork();
2219 if (pid == 0) {
2220 // child -- drop privileges before continuing
2221 drop_capabilities(uid);
2222 pipe_read.reset();
2223
2224 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002225 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2226 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002227 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002228 }
2229
2230 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2231 if (fd == -1) {
2232 if (errno == EACCES || errno == ENOENT) {
2233 // Not treated as an error.
2234 _exit(0);
2235 }
2236 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002237 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2238 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002239 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002240 }
2241
2242 SHA256_CTX ctx;
2243 SHA256_Init(&ctx);
2244
2245 std::vector<uint8_t> buffer(65536);
2246 while (true) {
2247 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2248 if (bytes_read == 0) {
2249 break;
2250 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002251 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2252 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002253 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002254 }
2255
2256 SHA256_Update(&ctx, buffer.data(), bytes_read);
2257 }
2258
2259 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2260 SHA256_Final(hash.data(), &ctx);
2261 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002262 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002263 }
2264
2265 _exit(0);
2266 }
2267
2268 // parent
2269 pipe_write.reset();
2270
2271 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2272 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2273 out_secondary_dex_hash->clear();
2274 }
2275 return wait_child(pid) == 0;
2276}
2277
Jeff Sharkey90aff262016-12-12 14:28:24 -07002278// Helper for move_ab, so that we can have common failure-case cleanup.
2279static bool unlink_and_rename(const char* from, const char* to) {
2280 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2281 // return a failure.
2282 struct stat s;
2283 if (stat(to, &s) == 0) {
2284 if (!S_ISREG(s.st_mode)) {
2285 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2286 return false;
2287 }
2288 if (unlink(to) != 0) {
2289 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2290 return false;
2291 }
2292 } else {
2293 // This may be a permission problem. We could investigate the error code, but we'll just
2294 // let the rename failure do the work for us.
2295 }
2296
2297 // Try to rename "to" to "from."
2298 if (rename(from, to) != 0) {
2299 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2300 return false;
2301 }
2302 return true;
2303}
2304
2305// Move/rename a B artifact (from) to an A artifact (to).
2306static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2307 // Check whether B exists.
2308 {
2309 struct stat s;
2310 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002311 // Ignore for now. The service calling this isn't smart enough to
2312 // understand lack of artifacts at the moment.
2313 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002314 return false;
2315 }
2316 if (!S_ISREG(s.st_mode)) {
2317 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2318 // Try to unlink, but swallow errors.
2319 unlink(b_path.c_str());
2320 return false;
2321 }
2322 }
2323
2324 // Rename B to A.
2325 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2326 // Delete the b_path so we don't try again (or fail earlier).
2327 if (unlink(b_path.c_str()) != 0) {
2328 PLOG(ERROR) << "Could not unlink " << b_path;
2329 }
2330
2331 return false;
2332 }
2333
2334 return true;
2335}
2336
2337bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2338 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002339 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2340 if (slot_suffix.empty()) {
2341 return false;
2342 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002343
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002344 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2345 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2346 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002347 }
2348
2349 // Validate other inputs.
2350 if (validate_apk_path(apk_path) != 0) {
2351 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2352 return false;
2353 }
2354 if (validate_apk_path(oat_dir) != 0) {
2355 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2356 return false;
2357 }
2358
2359 char a_path[PKG_PATH_MAX];
2360 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2361 return false;
2362 }
2363 const std::string a_vdex_path = create_vdex_filename(a_path);
2364 const std::string a_image_path = create_image_filename(a_path);
2365
2366 // B path = A path + slot suffix.
2367 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2368 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2369 const std::string b_image_path = StringPrintf("%s.%s",
2370 a_image_path.c_str(),
2371 slot_suffix.c_str());
2372
2373 bool success = true;
2374 if (move_ab_path(b_path, a_path)) {
2375 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2376 // Note: we can live without an app image. As such, ignore failure to move the image file.
2377 // If we decide to require the app image, or the app image being moved correctly,
2378 // then change accordingly.
2379 constexpr bool kIgnoreAppImageFailure = true;
2380
2381 if (!a_image_path.empty()) {
2382 if (!move_ab_path(b_image_path, a_image_path)) {
2383 unlink(a_image_path.c_str());
2384 if (!kIgnoreAppImageFailure) {
2385 success = false;
2386 }
2387 }
2388 }
2389 } else {
2390 // Cleanup: delete B image, ignore errors.
2391 unlink(b_image_path.c_str());
2392 success = false;
2393 }
2394 } else {
2395 // Cleanup: delete B image, ignore errors.
2396 unlink(b_vdex_path.c_str());
2397 unlink(b_image_path.c_str());
2398 success = false;
2399 }
2400 return success;
2401}
2402
Calin Juravleea214ad2021-06-11 09:17:20 -07002403int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002404 // Delete the oat/odex file.
2405 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002406 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002407 /*is_secondary_dex*/false, out_path)) {
Calin Juravleea214ad2021-06-11 09:17:20 -07002408 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2409 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002410 }
2411
2412 // In case of a permission failure report the issue. Otherwise just print a warning.
Calin Juravleea214ad2021-06-11 09:17:20 -07002413 auto unlink_and_check = [](const char* path) -> int64_t {
2414 struct stat file_stat;
2415 if (stat(path, &file_stat) != 0) {
2416 if (errno != ENOENT) {
2417 PLOG(ERROR) << "Could not stat " << path;
2418 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002419 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002420 return 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002421 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002422
2423 if (unlink(path) != 0) {
2424 if (errno != ENOENT) {
2425 PLOG(ERROR) << "Could not unlink " << path;
2426 return -1;
2427 }
2428 }
2429 return static_cast<int64_t>(file_stat.st_size);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002430 };
2431
2432 // Delete the oat/odex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002433 int64_t return_value_oat = unlink_and_check(out_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002434
2435 // Derive and delete the app image.
Calin Juravleea214ad2021-06-11 09:17:20 -07002436 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07002437
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002438 // Derive and delete the vdex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002439 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002440
Calin Juravleea214ad2021-06-11 09:17:20 -07002441 // Report result
2442 if (return_value_oat == -1
2443 || return_value_art == -1
2444 || return_value_vdex == -1) {
2445 return -1;
2446 }
2447
2448 return return_value_oat + return_value_art + return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002449}
2450
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002451static bool is_absolute_path(const std::string& path) {
2452 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2453 LOG(ERROR) << "Invalid absolute path " << path;
2454 return false;
2455 } else {
2456 return true;
2457 }
2458}
2459
2460static bool is_valid_instruction_set(const std::string& instruction_set) {
2461 // TODO: add explicit whitelisting of instruction sets
2462 if (instruction_set.find('/') != std::string::npos) {
2463 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2464 return false;
2465 } else {
2466 return true;
2467 }
2468}
2469
2470bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2471 const char *apk_path, const char *instruction_set) {
2472 std::string oat_dir_ = oat_dir;
2473 std::string apk_path_ = apk_path;
2474 std::string instruction_set_ = instruction_set;
2475
2476 if (!is_absolute_path(oat_dir_)) return false;
2477 if (!is_absolute_path(apk_path_)) return false;
2478 if (!is_valid_instruction_set(instruction_set_)) return false;
2479
2480 std::string::size_type end = apk_path_.rfind('.');
2481 std::string::size_type start = apk_path_.rfind('/', end);
2482 if (end == std::string::npos || start == std::string::npos) {
2483 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2484 return false;
2485 }
2486
2487 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2488 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2489 const char* res = res_.c_str();
2490 if (strlen(res) >= PKG_PATH_MAX) {
2491 LOG(ERROR) << "Result too large";
2492 return false;
2493 } else {
2494 strlcpy(path, res, PKG_PATH_MAX);
2495 return true;
2496 }
2497}
2498
2499bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2500 const char *instruction_set) {
2501 std::string apk_path_ = apk_path;
2502 std::string instruction_set_ = instruction_set;
2503
2504 if (!is_absolute_path(apk_path_)) return false;
2505 if (!is_valid_instruction_set(instruction_set_)) return false;
2506
2507 std::string::size_type end = apk_path_.rfind('.');
2508 std::string::size_type start = apk_path_.rfind('/', end);
2509 if (end == std::string::npos || start == std::string::npos) {
2510 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2511 return false;
2512 }
2513
2514 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2515 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2516}
2517
2518bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2519 const char *instruction_set) {
2520 std::string src_ = src;
2521 std::string instruction_set_ = instruction_set;
2522
2523 if (!is_absolute_path(src_)) return false;
2524 if (!is_valid_instruction_set(instruction_set_)) return false;
2525
2526 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2527 if (*it == '/') {
2528 *it = '@';
2529 }
2530 }
2531
2532 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2533 + DALVIK_CACHE_POSTFIX;
2534 const char* res = res_.c_str();
2535 if (strlen(res) >= PKG_PATH_MAX) {
2536 LOG(ERROR) << "Result too large";
2537 return false;
2538 } else {
2539 strlcpy(path, res, PKG_PATH_MAX);
2540 return true;
2541 }
2542}
2543
Calin Juravle59f7ab82018-04-27 17:50:23 -07002544bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2545 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002546 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2547 for (const std::string& elem : classpaths_elems) {
2548 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2549 if (fd < 0) {
2550 PLOG(ERROR) << "Could not open classpath elem " << elem;
2551 return false;
2552 } else {
2553 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002554 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002555 }
2556 }
2557 return true;
2558}
2559
2560static bool create_app_profile_snapshot(int32_t app_id,
2561 const std::string& package_name,
2562 const std::string& profile_name,
2563 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002564 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2565
Calin Juravle824a64d2018-01-18 20:23:17 -08002566 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002567 if (snapshot_fd < 0) {
2568 return false;
2569 }
2570
2571 std::vector<unique_fd> profiles_fd;
2572 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002573 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2574 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002575 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2576 return false;
2577 }
2578
2579 profiles_fd.push_back(std::move(reference_profile_fd));
2580
Calin Juravle0d0a4922018-01-23 19:54:11 -08002581 // Open the class paths elements. These will be used to filter out profile data that does
2582 // not belong to the classpath during merge.
2583 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002584 std::vector<std::string> dex_locations;
2585 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002586 return false;
2587 }
2588
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002589 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002590 // This is specifically a snapshot for an app, so don't use boot image profiles.
2591 args.SetupMerge(profiles_fd,
2592 snapshot_fd,
2593 apk_fds,
2594 dex_locations,
2595 /* for_snapshot= */ true,
2596 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002597 pid_t pid = fork();
2598 if (pid == 0) {
2599 /* child -- drop privileges before continuing */
2600 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002601 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002602 }
2603
2604 /* parent */
2605 int return_code = wait_child(pid);
2606 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002607 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002608 return false;
2609 }
2610
Calin Juravle78728f32019-11-08 17:55:46 -08002611 // Verify that profman finished successfully.
2612 int profman_code = WEXITSTATUS(return_code);
2613 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2614 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2615 << ":" << profman_code;
2616 return false;
2617 }
Calin Juravle29591732017-11-20 17:46:19 -08002618 return true;
2619}
2620
Calin Juravle0d0a4922018-01-23 19:54:11 -08002621static bool create_boot_image_profile_snapshot(const std::string& package_name,
2622 const std::string& profile_name,
2623 const std::string& classpath) {
2624 // The reference profile directory for the android package might not be prepared. Do it now.
2625 const std::string ref_profile_dir =
2626 create_primary_reference_profile_package_dir_path(package_name);
2627 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2628 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2629 return false;
2630 }
2631
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002632 // Return false for empty class path since it may otherwise return true below if profiles is
2633 // empty.
2634 if (classpath.empty()) {
2635 PLOG(ERROR) << "Class path is empty";
2636 return false;
2637 }
2638
Calin Juravle0d0a4922018-01-23 19:54:11 -08002639 // Open and create the snapshot profile.
2640 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2641
2642 // Collect all non empty profiles.
2643 // The collection will traverse all applications profiles and find the non empty files.
2644 // This has the potential of inspecting a large number of files and directories (depending
2645 // on the number of applications and users). So there is a slight increase in the chance
2646 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2647 // fail the snapshot and aggregate whatever profile we could open.
2648 //
2649 // The profile snapshot is a best effort based on available data it's ok if some data
2650 // from some apps is missing. It will be counter productive for the snapshot to fail
2651 // because we could not open or read some of the files.
2652 std::vector<std::string> profiles;
2653 if (!collect_profiles(&profiles)) {
2654 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2655 }
2656
2657 // If we have no profiles return early.
2658 if (profiles.empty()) {
2659 return true;
2660 }
2661
2662 // Open the classpath elements. These will be used to filter out profile data that does
2663 // not belong to the classpath during merge.
2664 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002665 std::vector<std::string> dex_locations;
2666 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002667 return false;
2668 }
2669
2670 // If we could not open any files from the classpath return an error.
2671 if (apk_fds.empty()) {
2672 LOG(ERROR) << "Could not open any of the classpath elements.";
2673 return false;
2674 }
2675
2676 // Aggregate the profiles in batches of kAggregationBatchSize.
2677 // We do this to avoid opening a huge a amount of files.
2678 static constexpr size_t kAggregationBatchSize = 10;
2679
Calin Juravle0d0a4922018-01-23 19:54:11 -08002680 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002681 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002682 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
Calin Juravlee01f8712021-06-03 18:16:54 -07002683 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002684 if (fd.get() >= 0) {
2685 profiles_fd.push_back(std::move(fd));
2686 }
2687 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002688
2689 // We aggregate (read & write) into the same fd multiple times in a row.
2690 // We need to reset the cursor every time to ensure we read the whole file every time.
2691 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2692 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2693 return false;
2694 }
2695
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002696 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002697 args.SetupMerge(profiles_fd,
2698 snapshot_fd,
2699 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002700 dex_locations,
2701 /*for_snapshot=*/true,
2702 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002703 pid_t pid = fork();
2704 if (pid == 0) {
2705 /* child -- drop privileges before continuing */
2706 drop_capabilities(AID_SYSTEM);
2707
Calin Juravle59f7ab82018-04-27 17:50:23 -07002708 // The introduction of new access flags into boot jars causes them to
2709 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002710 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002711 }
2712
2713 /* parent */
2714 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002715
Calin Juravle0d0a4922018-01-23 19:54:11 -08002716 if (!WIFEXITED(return_code)) {
2717 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2718 return false;
2719 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002720
2721 // Verify that profman finished successfully.
2722 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002723 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2724 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2725 << ":" << profman_code;
2726 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002727 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002728 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002729
Calin Juravle0d0a4922018-01-23 19:54:11 -08002730 return true;
2731}
2732
2733bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2734 const std::string& profile_name, const std::string& classpath) {
2735 if (app_id == -1) {
2736 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2737 } else {
2738 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2739 }
2740}
2741
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002742static bool check_profile_exists_in_dexmetadata(const std::string& dex_metadata) {
2743 ZipArchiveHandle zip = nullptr;
2744 if (OpenArchive(dex_metadata.c_str(), &zip) != 0) {
2745 PLOG(ERROR) << "Failed to open dm '" << dex_metadata << "'";
2746 return false;
2747 }
2748
2749 ZipEntry64 entry;
2750 int result = FindEntry(zip, "primary.prof", &entry);
2751 CloseArchive(zip);
2752
2753 return result != 0 ? false : true;
2754}
2755
Calin Juravlec3b049e2018-01-18 22:32:58 -08002756bool prepare_app_profile(const std::string& package_name,
2757 userid_t user_id,
2758 appid_t app_id,
2759 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002760 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002761 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002762 // Prepare the current profile.
2763 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2764 /*is_secondary_dex*/ false);
2765 uid_t uid = multiuser_get_uid(user_id, app_id);
2766 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2767 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2768 return false;
2769 }
2770
2771 // Check if we need to install the profile from the dex metadata.
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002772 if (!dex_metadata || !check_profile_exists_in_dexmetadata(dex_metadata->c_str())) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002773 return true;
2774 }
2775
2776 // We have a dex metdata. Merge the profile into the reference profile.
2777 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2778 /*read_write*/ true, /*is_secondary_dex*/ false);
2779 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2780 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002781 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2782 if (apk_fd < 0) {
2783 PLOG(ERROR) << "Could not open code path " << code_path;
2784 return false;
2785 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002786
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002787 RunProfman args;
2788 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2789 std::move(ref_profile_fd),
2790 std::move(apk_fd),
2791 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002792 pid_t pid = fork();
2793 if (pid == 0) {
2794 /* child -- drop privileges before continuing */
2795 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2796 drop_capabilities(app_shared_gid);
2797
Calin Juravlef63d4792018-01-30 17:43:34 +00002798 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002799 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002800 }
2801
2802 /* parent */
2803 int return_code = wait_child(pid);
2804 if (!WIFEXITED(return_code)) {
2805 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2806 return false;
2807 }
2808 return true;
2809}
2810
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002811} // namespace installd
2812} // namespace android