blob: 7bb9bef6584fca35bfa56b25dead4f101bd39a09 [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>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000050#include <processgroup/sched_policy.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>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070055
56#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080057#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070058#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060059#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070060#include "installd_deps.h"
Calin Juravlee90de862021-06-08 08:04:52 -070061#include "installd_constants.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070062#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070063#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070064#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070065#include "utils.h"
66
Victor Hsieh76f19ba2020-08-10 14:37:26 -070067using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070068using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070069using android::base::GetBoolProperty;
70using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000071using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010072using android::base::ReadFully;
73using android::base::StringPrintf;
74using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080075using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070076
Keun young Park65578d62021-06-28 17:52:05 -070077namespace {
78
79class DexOptStatus {
80 public:
81 // Check if dexopt is cancelled and fork if it is not cancelled.
82 // cancelled is set to true if cancelled. Otherwise it will be set to false.
83 // If it is not cancelled, it will return the return value of fork() call.
84 // If cancelled, fork will not happen and it will return -1.
85 pid_t check_cancellation_and_fork(/* out */ bool *cancelled) {
86 std::lock_guard<std::mutex> lock(dexopt_lock_);
87 if (dexopt_blocked_) {
88 *cancelled = true;
89 return -1;
90 }
91 pid_t pid = fork();
92 *cancelled = false;
93 if (pid > 0) { // parent
94 dexopt_pids_.insert(pid);
95 }
96 return pid;
97 }
98
99 // Returns true if pid was killed (is in killed list). It could have finished if killing
100 // happened after the process is finished.
101 bool check_if_killed_and_remove_dexopt_pid(pid_t pid) {
102 std::lock_guard<std::mutex> lock(dexopt_lock_);
103 dexopt_pids_.erase(pid);
104 if (dexopt_killed_pids_.erase(pid) == 1) {
105 return true;
106 }
107 return false;
108 }
109
110 // Tells whether dexopt is blocked or not.
111 bool is_dexopt_blocked() {
112 std::lock_guard<std::mutex> lock(dexopt_lock_);
113 return dexopt_blocked_;
114 }
115
116 // Enable or disable dexopt blocking.
117 void control_dexopt_blocking(bool block) {
118 std::lock_guard<std::mutex> lock(dexopt_lock_);
119 dexopt_blocked_ = block;
120 if (!block) {
121 return;
122 }
123 // Blocked, also kill currently running tasks
124 for (auto pid : dexopt_pids_) {
125 LOG(INFO) << "control_dexopt_blocking kill pid:" << pid;
126 kill(pid, SIGKILL);
127 dexopt_killed_pids_.insert(pid);
128 }
129 dexopt_pids_.clear();
130 }
131
132 private:
133 std::mutex dexopt_lock_;
134 // when true, dexopt is blocked and will not run.
135 bool dexopt_blocked_ GUARDED_BY(dexopt_lock_) = false;
136 // PIDs of child process while runinng dexopt.
137 // If the child process is finished, it should be removed.
138 std::unordered_set<pid_t> dexopt_pids_ GUARDED_BY(dexopt_lock_);
139 // PIDs of child processes killed by cancellation.
140 std::unordered_set<pid_t> dexopt_killed_pids_ GUARDED_BY(dexopt_lock_);
141};
142
143android::base::NoDestructor<DexOptStatus> dexopt_status_;
144
145} // namespace
146
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700147namespace android {
148namespace installd {
149
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800150
Calin Juravle114f0812017-03-08 19:05:07 -0800151// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
152struct FreeDelete {
153 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
154 void operator()(const void* ptr) const {
155 free(const_cast<void*>(ptr));
156 }
157};
158
159// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
160template <typename T>
161using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
162
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800163static unique_fd invalid_unique_fd() {
164 return unique_fd(-1);
165}
166
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700167static bool is_debug_runtime() {
168 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
169}
170
David Sehra3b5ab62017-10-25 14:27:29 -0700171static bool is_debuggable_build() {
172 return android::base::GetBoolProperty("ro.debuggable", false);
173}
174
Jeff Sharkey90aff262016-12-12 14:28:24 -0700175static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800176 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700177 if (ufd.get() < 0) {
178 if (errno != ENOENT) {
179 PLOG(WARNING) << "Could not open profile " << profile;
180 return false;
181 } else {
182 // Nothing to clear. That's ok.
183 return true;
184 }
185 }
186
187 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
188 if (errno != EWOULDBLOCK) {
189 PLOG(WARNING) << "Error locking profile " << profile;
190 }
191 // This implies that the app owning this profile is running
192 // (and has acquired the lock).
193 //
194 // If we can't acquire the lock bail out since clearing is useless anyway
195 // (the app will write again to the profile).
196 //
197 // Note:
198 // This does not impact the this is not an issue for the profiling correctness.
199 // In case this is needed because of an app upgrade, profiles will still be
200 // eventually cleared by the app itself due to checksum mismatch.
201 // If this is needed because profman advised, then keeping the data around
202 // until the next run is again not an issue.
203 //
204 // If the app attempts to acquire a lock while we've held one here,
205 // it will simply skip the current write cycle.
206 return false;
207 }
208
209 bool truncated = ftruncate(ufd.get(), 0) == 0;
210 if (!truncated) {
211 PLOG(WARNING) << "Could not truncate " << profile;
212 }
213 if (flock(ufd.get(), LOCK_UN) != 0) {
214 PLOG(WARNING) << "Error unlocking profile " << profile;
215 }
216 return truncated;
217}
218
Calin Juravle114f0812017-03-08 19:05:07 -0800219// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800220// The location is the profile name for primary apks or the dex path for secondary dex files.
221static bool clear_reference_profile(const std::string& package_name, const std::string& location,
222 bool is_secondary_dex) {
223 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700224}
225
Calin Juravle114f0812017-03-08 19:05:07 -0800226// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800227// The location is the profile name for primary apks or the dex path for secondary dex files.
228static bool clear_current_profile(const std::string& package_name, const std::string& location,
229 userid_t user, bool is_secondary_dex) {
230 return clear_profile(create_current_profile_path(user, package_name, location,
231 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700232}
233
Calin Juravle114f0812017-03-08 19:05:07 -0800234// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800235// The location is the profile name for primary apks or the dex path for secondary dex files.
236bool clear_primary_reference_profile(const std::string& package_name,
237 const std::string& location) {
238 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800239}
240
241// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800242// The location is the profile name for primary apks or the dex path for secondary dex files.
243bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700244 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800245 // 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 -0700246 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
247 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800248 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700249 }
250 return success;
251}
252
Calin Juravle114f0812017-03-08 19:05:07 -0800253// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800254bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
255 userid_t user) {
256 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800257}
258
Calin Juravlef74a7372019-02-28 20:29:41 -0800259// Determines which binary we should use for execution (the debug or non-debug version).
260// e.g. dex2oatd vs dex2oat
261static const char* select_execution_binary(const char* binary, const char* debug_binary,
262 bool background_job_compile) {
263 return select_execution_binary(
264 binary,
265 debug_binary,
266 background_job_compile,
267 is_debug_runtime(),
268 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
269 is_debuggable_build());
270}
271
272// Determines which binary we should use for execution (the debug or non-debug version).
273// e.g. dex2oatd vs dex2oat
274// This is convenient method which is much easier to test because it doesn't read
275// system properties.
276const char* select_execution_binary(
277 const char* binary,
278 const char* debug_binary,
279 bool background_job_compile,
280 bool is_debug_runtime,
281 bool is_release,
282 bool is_debuggable_build) {
283 // Do not use debug binaries for release candidates (to give more soak time).
284 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
285
286 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
287 // the file is present (it may not be on images with very little space available).
288 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
289
290 return useDebug ? debug_binary : binary;
291}
292
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000293// Namespace for Android Runtime flags applied during boot time.
294static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
295// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000296static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000297
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700298// Phenotype property name for enabling profiling the boot class path.
299static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
300
Calin Juravlef85ddb92020-05-01 14:05:40 -0700301static bool IsBootClassPathProfilingEnable() {
302 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
303 profile_boot_class_path =
304 server_configurable_flags::GetServerConfigurableFlag(
305 RUNTIME_NATIVE_BOOT_NAMESPACE,
306 PROFILE_BOOT_CLASS_PATH,
307 /*default_value=*/ profile_boot_class_path);
308 return profile_boot_class_path == "true";
309}
310
Victor Hsiehcb35a062020-08-13 16:11:13 -0700311static void UnlinkIgnoreResult(const std::string& path) {
312 if (unlink(path.c_str()) < 0) {
313 PLOG(ERROR) << "Failed to unlink " << path;
314 }
315}
316
Jeff Sharkey90aff262016-12-12 14:28:24 -0700317/*
318 * Whether dexopt should use a swap file when compiling an APK.
319 *
320 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
321 * itself, anyways).
322 *
323 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
324 *
325 * Otherwise, return true if this is a low-mem device.
326 *
327 * Otherwise, return default value.
328 */
329static bool kAlwaysProvideSwapFile = false;
330static bool kDefaultProvideSwapFile = true;
331
332static bool ShouldUseSwapFileForDexopt() {
333 if (kAlwaysProvideSwapFile) {
334 return true;
335 }
336
337 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700338 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
339 if (!dex2oat_prop_buf.empty()) {
340 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700341 }
342
343 // Shortcut for default value. This is an implementation optimization for the process sketched
344 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
345 // as low-mem is never returning false. The compiler will optimize this away if it can.
346 if (kDefaultProvideSwapFile) {
347 return true;
348 }
349
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700350 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700351 return true;
352 }
353
354 // Default value must be false here.
355 return kDefaultProvideSwapFile;
356}
357
Richard Uhler76cc0272016-12-08 10:46:35 +0000358static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700359 if (set_to_bg) {
360 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800361 PLOG(ERROR) << "set_sched_policy failed";
362 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700363 }
364 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800365 PLOG(ERROR) << "setpriority failed";
366 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700367 }
368 }
369}
370
Calin Juravle31c68e72021-06-03 18:16:54 -0700371static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
372 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, mode)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800373 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800374 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800375 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800376 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800377 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700378 }
Calin Juravle114f0812017-03-08 19:05:07 -0800379 // Profiles should belong to the app; make sure of that by giving ownership to
380 // the app uid. If we cannot do that, there's no point in returning the fd
381 // since dex2oat/profman will fail with SElinux denials.
382 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000383 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800384 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800385 }
Calin Juravle29591732017-11-20 17:46:19 -0800386 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800387}
388
Calin Juravle31c68e72021-06-03 18:16:54 -0700389static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
Calin Juravle114f0812017-03-08 19:05:07 -0800390 // Do not follow symlinks when opening a profile:
391 // - primary profiles should not contain symlinks in their paths
392 // - secondary dex paths should have been already resolved and validated
393 flags |= O_NOFOLLOW;
394
Calin Juravle29591732017-11-20 17:46:19 -0800395 // Check if we need to create the profile
396 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
397 unique_fd fd;
398 if ((flags & O_CREAT) != 0) {
Calin Juravle31c68e72021-06-03 18:16:54 -0700399 fd = create_profile(uid, profile, flags, mode);
Calin Juravle29591732017-11-20 17:46:19 -0800400 } else {
401 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
402 }
403
Calin Juravle114f0812017-03-08 19:05:07 -0800404 if (fd.get() < 0) {
405 if (errno != ENOENT) {
406 // Profiles might be missing for various reasons. For example, in a
407 // multi-user environment, the profile directory for one user can be created
408 // after we start a merge. In this case the current profile for that user
409 // will not be found.
410 // Also, the secondary dex profiles might be deleted by the app at any time,
411 // so we can't we need to prepare if they are missing.
412 PLOG(ERROR) << "Failed to open profile " << profile;
413 }
414 return invalid_unique_fd();
Calin Juravle31c68e72021-06-03 18:16:54 -0700415 } else {
416 // If we just create the file we need to set its mode because on Android
417 // open has a mask that only allows owner access.
418 if ((flags & O_CREAT) != 0) {
419 if (fchmod(fd.get(), mode) != 0) {
420 PLOG(ERROR) << "Could not set mode " << std::hex << mode << std::dec
421 << " on profile" << profile;
422 // Not a terminal failure.
423 }
424 }
Calin Juravle114f0812017-03-08 19:05:07 -0800425 }
426
Jeff Sharkey90aff262016-12-12 14:28:24 -0700427 return fd;
428}
429
Calin Juravle824a64d2018-01-18 20:23:17 -0800430static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
431 const std::string& location, bool is_secondary_dex) {
432 std::string profile = create_current_profile_path(user, package_name, location,
433 is_secondary_dex);
Calin Juravle31c68e72021-06-03 18:16:54 -0700434 return open_profile(uid, profile, O_RDONLY, /*mode=*/ 0);
Calin Juravle114f0812017-03-08 19:05:07 -0800435}
436
Calin Juravle824a64d2018-01-18 20:23:17 -0800437static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
438 const std::string& location, bool read_write, bool is_secondary_dex) {
439 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle31c68e72021-06-03 18:16:54 -0700440 return open_profile(
441 uid,
442 profile,
443 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
444 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
Calin Juravle29591732017-11-20 17:46:19 -0800445}
446
Victor Hsiehcb35a062020-08-13 16:11:13 -0700447static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
448 const std::string& location, bool read_write, bool is_secondary_dex) {
449 std::string profile_path = create_reference_profile_path(package_name, location,
450 is_secondary_dex);
Calin Juravle31c68e72021-06-03 18:16:54 -0700451 unique_fd ufd = open_profile(
452 uid,
453 profile_path,
454 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
455 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
456
Victor Hsiehcb35a062020-08-13 16:11:13 -0700457 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
458 clear_profile(path);
459 });
460}
461
Calin Juravle29591732017-11-20 17:46:19 -0800462static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800463 const std::string& location) {
464 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle31c68e72021-06-03 18:16:54 -0700465 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
Calin Juravle114f0812017-03-08 19:05:07 -0800466}
467
Calin Juravle824a64d2018-01-18 20:23:17 -0800468static void open_profile_files(uid_t uid, const std::string& package_name,
469 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800470 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700471 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800472 *reference_profile_fd = open_reference_profile(uid, package_name, location,
473 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700474
Calin Juravle114f0812017-03-08 19:05:07 -0800475 // For secondary dex files, we don't really need the user but we use it for sanity checks.
476 // Note: the user owning the dex file should be the current user.
477 std::vector<userid_t> users;
478 if (is_secondary_dex){
479 users.push_back(multiuser_get_user_id(uid));
480 } else {
481 users = get_known_users(/*volume_uuid*/ nullptr);
482 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700483 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800484 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
485 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700486 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800487 if (profile_fd.get() >= 0) {
488 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700489 }
490 }
491}
492
Calin Juravle76561322019-11-14 09:08:52 -0800493static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
494static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
Calin Juravlee90de862021-06-08 08:04:52 -0700495static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
Calin Juravle76561322019-11-14 09:08:52 -0800496static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
497static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
498static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
499static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Calin Juravlee90de862021-06-08 08:04:52 -0700500static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700501
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800502class RunProfman : public ExecVHelper {
503 public:
504 void SetupArgs(const std::vector<unique_fd>& profile_fds,
505 const unique_fd& reference_profile_fd,
506 const std::vector<unique_fd>& apk_fds,
507 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800508 bool copy_and_update,
509 bool for_snapshot,
510 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800511
512 // TODO(calin): Assume for now we run in the bg compile job (which is in
513 // most of the invocation). With the current data flow, is not very easy or
514 // clean to discover this in RunProfman (it will require quite a messy refactoring).
515 const char* profman_bin = select_execution_binary(
516 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700517
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800518 if (copy_and_update) {
519 CHECK_EQ(1u, profile_fds.size());
520 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000521 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800522 if (reference_profile_fd != -1) {
523 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000524 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800525
526 for (const unique_fd& fd : profile_fds) {
527 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
528 }
529
530 for (const unique_fd& fd : apk_fds) {
531 AddArg("--apk-fd=" + std::to_string(fd.get()));
532 }
533
534 for (const std::string& dex_location : dex_locations) {
535 AddArg("--dex-location=" + dex_location);
536 }
537
538 if (copy_and_update) {
539 AddArg("--copy-and-update-profile-key");
540 }
541
Calin Juravle78728f32019-11-08 17:55:46 -0800542 if (for_snapshot) {
543 AddArg("--force-merge");
544 }
545
546 if (for_boot_image) {
547 AddArg("--boot-image-merge");
548 }
549
yawannga27559e2020-11-13 19:17:44 +0000550 // The percent won't exceed 100, otherwise, don't set it and use the
551 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000552 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000553 "dalvik.vm.bgdexopt.new-classes-percent",
554 /*default*/std::numeric_limits<uint32_t>::max());
555 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000556 AddArg("--min-new-classes-percent-change=" +
557 std::to_string(min_new_classes_percent_change));
558 }
559
yawannga27559e2020-11-13 19:17:44 +0000560 // The percent won't exceed 100, otherwise, don't set it and use the
561 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000562 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000563 "dalvik.vm.bgdexopt.new-methods-percent",
564 /*default*/std::numeric_limits<uint32_t>::max());
565 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000566 AddArg("--min-new-methods-percent-change=" +
567 std::to_string(min_new_methods_percent_change));
568 }
569
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800570 // Do not add after dex2oat_flags, they should override others for debugging.
571 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800572 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700573
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800574 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
575 const unique_fd& reference_profile_fd,
576 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800577 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
578 bool for_snapshot = false,
579 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800580 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800581 reference_profile_fd,
582 apk_fds,
583 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800584 /*copy_and_update=*/ false,
585 for_snapshot,
586 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800587 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700588
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800589 void SetupCopyAndUpdate(unique_fd&& profile_fd,
590 unique_fd&& reference_profile_fd,
591 unique_fd&& apk_fd,
592 const std::string& dex_location) {
593 // The fds need to stay open longer than the scope of the function, so put them into a local
594 // variable vector.
595 profiles_fd_.push_back(std::move(profile_fd));
596 apk_fds_.push_back(std::move(apk_fd));
597 reference_profile_fd_ = std::move(reference_profile_fd);
598 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800599 SetupArgs(profiles_fd_,
600 reference_profile_fd_,
601 apk_fds_,
602 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800603 /*copy_and_update=*/true,
604 /*for_snapshot*/false,
605 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800606 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000607
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800608 void SetupDump(const std::vector<unique_fd>& profiles_fd,
609 const unique_fd& reference_profile_fd,
610 const std::vector<std::string>& dex_locations,
611 const std::vector<unique_fd>& apk_fds,
612 const unique_fd& output_fd) {
613 AddArg("--dump-only");
614 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800615 SetupArgs(profiles_fd,
616 reference_profile_fd,
617 apk_fds,
618 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800619 /*copy_and_update=*/false,
620 /*for_snapshot*/false,
621 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800622 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000623
Victor Hsiehc9821f12020-08-07 11:32:29 -0700624 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800625 void Exec() {
626 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
627 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000628
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800629 private:
630 unique_fd reference_profile_fd_;
631 std::vector<unique_fd> profiles_fd_;
632 std::vector<unique_fd> apk_fds_;
633};
Mathieu Chartier31636522018-11-09 23:53:07 +0000634
Calin Juravlee90de862021-06-08 08:04:52 -0700635static int analyze_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800636 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800637 std::vector<unique_fd> profiles_fd;
638 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800639 open_profile_files(uid, package_name, location, is_secondary_dex,
640 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800641 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700642 // Skip profile guided compilation because no profiles were found.
643 // Or if the reference profile info couldn't be opened.
Calin Juravlee90de862021-06-08 08:04:52 -0700644 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700645 }
646
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800647 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700648 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
649 const std::vector<std::string>& dex_locations = std::vector<std::string>();
650 profman_merge.SetupMerge(
651 profiles_fd,
652 reference_profile_fd,
653 apk_fds,
654 dex_locations,
655 /* for_snapshot= */ false,
656 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700657 pid_t pid = fork();
658 if (pid == 0) {
659 /* child -- drop privileges before continuing */
660 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800661 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700662 }
663 /* parent */
664 int return_code = wait_child(pid);
665 bool need_to_compile = false;
Calin Juravlee90de862021-06-08 08:04:52 -0700666 bool empty_profiles = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700667 bool should_clear_current_profiles = false;
668 bool should_clear_reference_profile = false;
669 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800670 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 } else {
672 return_code = WEXITSTATUS(return_code);
673 switch (return_code) {
674 case PROFMAN_BIN_RETURN_CODE_COMPILE:
675 need_to_compile = true;
676 should_clear_current_profiles = true;
677 should_clear_reference_profile = false;
678 break;
Calin Juravlee90de862021-06-08 08:04:52 -0700679 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
Jeff Sharkey90aff262016-12-12 14:28:24 -0700680 need_to_compile = false;
681 should_clear_current_profiles = false;
682 should_clear_reference_profile = false;
683 break;
Calin Juravlee90de862021-06-08 08:04:52 -0700684 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
685 need_to_compile = false;
686 empty_profiles = true;
687 should_clear_current_profiles = false;
688 should_clear_reference_profile = false;
689 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800691 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692 need_to_compile = false;
693 should_clear_current_profiles = true;
694 should_clear_reference_profile = true;
695 break;
696 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
697 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
698 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800699 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700700 need_to_compile = false;
701 should_clear_current_profiles = false;
702 should_clear_reference_profile = false;
703 break;
Calin Juravle76561322019-11-14 09:08:52 -0800704 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
705 need_to_compile = false;
706 should_clear_current_profiles = true;
707 should_clear_reference_profile = true;
708 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700709 default:
710 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800711 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800712 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700713 need_to_compile = false;
714 should_clear_current_profiles = true;
715 should_clear_reference_profile = true;
716 break;
717 }
718 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800719
Jeff Sharkey90aff262016-12-12 14:28:24 -0700720 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800721 if (is_secondary_dex) {
722 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800723 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
724 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800725 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800726 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800727 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700728 }
729 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800730 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700731 }
Calin Juravlee90de862021-06-08 08:04:52 -0700732 int result = 0;
733 if (need_to_compile) {
734 result = PROFILES_ANALYSIS_OPTIMIZE;
735 } else if (empty_profiles) {
736 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
737 } else {
738 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
739 }
740 return result;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700741}
742
Calin Juravle114f0812017-03-08 19:05:07 -0800743// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravlee90de862021-06-08 08:04:52 -0700744// The analysis is done for a single profile name (which corresponds to a single code path).
745//
746// Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
747// that makes it worth to recompile the package.
748// If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
749// merged into the reference profiles accessible with open_reference_profile().
750//
751// Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
752// As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
753// empty.
754int analyze_primary_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800755 const std::string& profile_name) {
756 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800757}
758
Calin Juravle408cd4a2018-01-20 23:34:18 -0800759bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
760 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800761 std::vector<unique_fd> profile_fds;
762 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800763 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
764 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700765
Calin Juravle408cd4a2018-01-20 23:34:18 -0800766 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800767 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700768
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800769 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700770 const bool has_profiles = !profile_fds.empty();
771
772 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800773 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774 return false;
775 }
776
Calin Juravle114f0812017-03-08 19:05:07 -0800777 unique_fd output_fd(open(out_file_name.c_str(),
778 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800780 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700781 return false;
782 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800783
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800785 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800786 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
787 if (apk_fd == -1) {
788 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
789 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700790 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700791 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800792 apk_fds.push_back(std::move(apk_fd));
793
Jeff Sharkey90aff262016-12-12 14:28:24 -0700794
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800795 RunProfman profman_dump;
796 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700797 pid_t pid = fork();
798 if (pid == 0) {
799 /* child -- drop privileges before continuing */
800 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800801 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700802 }
803 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700804 int return_code = wait_child(pid);
805 if (!WIFEXITED(return_code)) {
806 LOG(WARNING) << "profman failed for package " << pkgname << ": "
807 << return_code;
808 return false;
809 }
810 return true;
811}
812
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700813bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800814 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700815 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
816 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800817 package_name,
818 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700819 /*read_write*/ true,
820 /*secondary*/ false));
821 if (in_fd.get() < 0) {
822 PLOG(WARNING) << "Could not open profile " << system_profile;
823 return false;
824 }
825 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800826 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700827 return false;
828 }
829
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700830 // As a security measure we want to write the profile information with the reduced capabilities
831 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700832 pid_t pid = fork();
833 if (pid == 0) {
834 /* child -- drop privileges before continuing */
835 drop_capabilities(packageUid);
836
837 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
838 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200839 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
840 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700841 }
842 // This implies that the app owning this profile is running
843 // (and has acquired the lock).
844 //
845 // The app never acquires the lock for the reference profiles of primary apks.
846 // Only dex2oat from installd will do that. Since installd is single threaded
847 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200848 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
849 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700850 return false;
851 }
852
853 bool truncated = ftruncate(out_fd.get(), 0) == 0;
854 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200855 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
856 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700857 }
858
859 // Copy over data.
860 static constexpr size_t kBufferSize = 4 * 1024;
861 char buffer[kBufferSize];
862 while (true) {
863 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
864 if (bytes == 0) {
865 break;
866 }
867 write(out_fd.get(), buffer, bytes);
868 }
869 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200870 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
871 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700872 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700873 // Use _exit since we don't want to run the global destructors in the child.
874 // b/62597429
875 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700876 }
877 /* parent */
878 int return_code = wait_child(pid);
879 return return_code == 0;
880}
881
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
883 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
884 if (EndsWith(oat_path, ".dex")) {
885 std::string new_path = oat_path;
886 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800887 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 return new_path;
889 }
890
891 // An odex entry. Not that this may not be an extension, e.g., in the OTA
892 // case (where the base name will have an extension for the B artifact).
893 size_t odex_pos = oat_path.rfind(".odex");
894 if (odex_pos != std::string::npos) {
895 std::string new_path = oat_path;
896 new_path.replace(odex_pos, strlen(".odex"), new_ext);
897 CHECK_NE(new_path.find(new_ext), std::string::npos);
898 return new_path;
899 }
900
901 // Don't know how to handle this.
902 return "";
903}
904
905// Translate the given oat path to an art (app image) path. An empty string
906// denotes an error.
907static std::string create_image_filename(const std::string& oat_path) {
908 return replace_file_extension(oat_path, ".art");
909}
910
911// Translate the given oat path to a vdex path. An empty string denotes an error.
912static std::string create_vdex_filename(const std::string& oat_path) {
913 return replace_file_extension(oat_path, ".vdex");
914}
915
Jeff Sharkey90aff262016-12-12 14:28:24 -0700916static int open_output_file(const char* file_name, bool recreate, int permissions) {
917 int flags = O_RDWR | O_CREAT;
918 if (recreate) {
919 if (unlink(file_name) < 0) {
920 if (errno != ENOENT) {
921 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
922 }
923 }
924 flags |= O_EXCL;
925 }
926 return open(file_name, flags, permissions);
927}
928
Calin Juravle2289c0a2017-02-15 12:44:14 -0800929static bool set_permissions_and_ownership(
930 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
931 // Primary apks are owned by the system. Secondary dex files are owned by the app.
932 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 if (fchmod(fd,
934 S_IRUSR|S_IWUSR|S_IRGRP |
935 (is_public ? S_IROTH : 0)) < 0) {
936 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
937 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800938 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700939 ALOGE("installd cannot chown '%s' during dexopt\n", path);
940 return false;
941 }
942 return true;
943}
944
945static bool IsOutputDalvikCache(const char* oat_dir) {
946 // InstallerConnection.java (which invokes installd) transforms Java null arguments
947 // into '!'. Play it safe by handling it both.
948 // TODO: ensure we never get null.
949 // TODO: pass a flag instead of inferring if the output is dalvik cache.
950 return oat_dir == nullptr || oat_dir[0] == '!';
951}
952
Calin Juravled23dee72017-07-06 16:29:11 -0700953// Best-effort check whether we can fit the the path into our buffers.
954// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
955// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
956// extension to the cache path (5 bytes).
957// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
958static bool validate_dex_path_size(const std::string& dex_path) {
959 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
960 LOG(ERROR) << "dex_path too long: " << dex_path;
961 return false;
962 }
963 return true;
964}
965
Jeff Sharkey90aff262016-12-12 14:28:24 -0700966static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800967 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700968 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700969 return false;
970 }
971
972 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800973 // Oat dirs for secondary dex files are already validated.
974 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700975 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
976 return false;
977 }
978 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
979 return false;
980 }
981 } else {
982 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
983 return false;
984 }
985 }
986 return true;
987}
988
Calin Juravle7a570e82017-01-14 16:23:30 -0800989// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700990UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700991 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100992
Calin Juravle7a570e82017-01-14 16:23:30 -0800993 const std::string image_path = create_image_filename(out_oat_path);
994 if (image_path.empty()) {
995 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700996 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800997 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100998
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700999 // In case there is a stale image, remove it now. Ignore any error.
1000 unlink(image_path.c_str());
1001
1002 // Not enabled, exit.
1003 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001004 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001005 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001006 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1007 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001008 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001009 }
1010 // Recreate is true since we do not want to modify a mapped image. If the app is
1011 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001012 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001013 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001014 image_path,
1015 UnlinkIgnoreResult);
1016 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001017 // Could not create application image file. Go on since we can compile without it.
1018 LOG(ERROR) << "installd could not create '" << image_path
1019 << "' for image file during dexopt";
1020 // If we have a valid image file path but no image fd, explicitly erase the image file.
1021 if (unlink(image_path.c_str()) < 0) {
1022 if (errno != ENOENT) {
1023 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1024 }
1025 }
1026 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001027 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001028 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001029 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001030 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001031
Victor Hsiehcb35a062020-08-13 16:11:13 -07001032 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -08001033}
1034
1035// Creates the dexopt swap file if necessary and return its fd.
1036// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001037unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001038 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001039 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001040 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001041 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001042 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001043 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001044 if (swap_fd.get() < 0) {
1045 // Could not create swap file. Optimistically go on and hope that we can compile
1046 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001047 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001048 } else {
1049 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001050 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001051 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1052 }
1053 }
1054 return swap_fd;
1055}
1056
1057// Opens the reference profiles if needed.
1058// 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 -07001059UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001060 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001061 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001062 // If we are not profile guided compilation, or we are compiling system server
1063 // do not bother to open the profiles; we won't be using them.
1064 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001065 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +00001066 }
1067
1068 // If this is a secondary dex path which is public do not open the profile.
1069 // We cannot compile public secondary dex paths with profiles. That's because
1070 // it will expose how the dex files are used by their owner.
1071 //
1072 // Note that the PackageManager is responsible to set the is_public flag for
1073 // primary apks and we do not check it here. In some cases, e.g. when
1074 // compiling with a public profile from the .dm file the PackageManager will
1075 // set is_public toghether with the profile guided compilation.
1076 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001077 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001078 }
Calin Juravle114f0812017-03-08 19:05:07 -08001079
1080 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001081 std::string location;
1082 if (is_secondary_dex) {
1083 location = dex_path;
1084 } else {
1085 if (profile_name == nullptr) {
1086 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001087 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001088 } else {
1089 location = profile_name;
1090 }
1091 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001092 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
1093 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001094}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001095
Victor Hsiehcb35a062020-08-13 16:11:13 -07001096// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1097// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001098bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001099 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -07001100 bool profile_guided, UniqueFile* in_vdex_wrapper,
1101 UniqueFile* out_vdex_wrapper) {
1102 CHECK(in_vdex_wrapper != nullptr);
1103 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1105 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001106 char in_odex_path[PKG_PATH_MAX];
1107 int dexopt_action = abs(dexopt_needed);
1108 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001109
1110 // Infer the name of the output VDEX.
1111 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1112 if (out_vdex_path_str.empty()) {
1113 return false;
1114 }
1115
1116 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001117 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1119 const char* path = nullptr;
1120 if (is_odex_location) {
1121 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1122 path = in_odex_path;
1123 } else {
1124 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001125 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001126 }
1127 } else {
1128 path = out_oat_path;
1129 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001130 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131 if (in_vdex_path_str.empty()) {
1132 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001133 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001134 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001135 // We can update in place when all these conditions are met:
1136 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1137 // on /system typically cannot be updated in place).
1138 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1139 // cannot be currently used by a running process.
1140 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1141 // different vdex files to operate.
1142 update_vdex_in_place =
1143 (in_vdex_path_str == out_vdex_path_str) &&
1144 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1145 !profile_guided;
1146 if (update_vdex_in_place) {
1147 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001148 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1149 in_vdex_path_str);
1150 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001151 // If we failed to open the file, we cannot update it in place.
1152 update_vdex_in_place = false;
1153 }
1154 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001155 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1156 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001157 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158 }
1159
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001160 // If we are updating the vdex in place, we do not need to recreate a vdex,
1161 // and can use the same existing one.
1162 if (update_vdex_in_place) {
1163 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1164 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001165 out_vdex_wrapper->reset(
1166 in_vdex_wrapper->fd(),
1167 out_vdex_path_str,
1168 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001169 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1170 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001171 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001172 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001173 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001174 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001175 out_vdex_path_str,
1176 UnlinkIgnoreResult);
1177 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001178 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1179 return false;
1180 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001181 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001182 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001183 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1185 return false;
1186 }
1187
1188 // If we got here we successfully opened the vdex files.
1189 return true;
1190}
1191
1192// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001193UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1194 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1195 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001196 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001197 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001198 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001199 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001200 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001201 out_oat_path,
1202 UnlinkIgnoreResult);
1203 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001204 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001205 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001206 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001208 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001209 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001210 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001211}
1212
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001213// Creates RDONLY fds for oat and vdex files, if exist.
1214// Returns false if it fails to create oat out path for the given apk path.
1215// Note that the method returns true even if the files could not be opened.
1216bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1217 const std::string& oat_dir,
1218 const std::string& instruction_set,
1219 bool is_secondary_dex,
1220 unique_fd* oat_file_fd,
1221 unique_fd* vdex_file_fd) {
1222 char oat_path[PKG_PATH_MAX];
1223 if (!create_oat_out_path(apk_path.c_str(),
1224 instruction_set.c_str(),
1225 oat_dir.c_str(),
1226 is_secondary_dex,
1227 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001228 LOG(ERROR) << "Could not create oat out path for "
1229 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001230 return false;
1231 }
1232 oat_file_fd->reset(open(oat_path, O_RDONLY));
1233 if (oat_file_fd->get() < 0) {
1234 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1235 }
1236
1237 std::string vdex_filename = create_vdex_filename(oat_path);
1238 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1239 if (vdex_file_fd->get() < 0) {
1240 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1241 }
1242
1243 return true;
1244}
1245
Calin Juravle80a21252017-01-17 14:43:25 -08001246// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001247// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1248// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1249// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001250class RunDexoptAnalyzer : public ExecVHelper {
1251 public:
1252 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001253 int vdex_fd,
1254 int oat_fd,
1255 int zip_fd,
1256 const std::string& instruction_set,
1257 const std::string& compiler_filter,
Calin Juravlee90de862021-06-08 08:04:52 -07001258 int profile_analysis_result,
David Brazdil4f6027a2019-03-19 11:44:21 +00001259 bool downgrade,
1260 const char* class_loader_context,
1261 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001262 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001263
1264 // We always run the analyzer in the background job.
1265 const char* dexoptanalyzer_bin = select_execution_binary(
1266 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001267
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001268 std::string dex_file_arg = "--dex-file=" + dex_file;
1269 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1270 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1271 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1272 std::string isa_arg = "--isa=" + instruction_set;
1273 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravlee90de862021-06-08 08:04:52 -07001274 std::string profile_analysis_arg = "--profile-analysis-result="
1275 + std::to_string(profile_analysis_result);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001276 const char* downgrade_flag = "--downgrade";
1277 std::string class_loader_context_arg = "--class-loader-context=";
1278 if (class_loader_context != nullptr) {
1279 class_loader_context_arg += class_loader_context;
1280 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001281 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1282 if (!class_loader_context_fds.empty()) {
1283 class_loader_context_fds_arg += class_loader_context_fds;
1284 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001285
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001286 // program name, dex file, isa, filter
1287 AddArg(dex_file_arg);
1288 AddArg(isa_arg);
1289 AddArg(compiler_filter_arg);
1290 if (oat_fd >= 0) {
1291 AddArg(oat_fd_arg);
1292 }
1293 if (vdex_fd >= 0) {
1294 AddArg(vdex_fd_arg);
1295 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001296 AddArg(zip_fd_arg);
Calin Juravlee90de862021-06-08 08:04:52 -07001297 AddArg(profile_analysis_arg);
1298
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001299 if (downgrade) {
1300 AddArg(downgrade_flag);
1301 }
1302 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001303 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001304 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001305 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001306 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001307 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001308
Orion Hodson2b12e7c2021-07-01 12:12:40 +01001309 // On-device signing related. odsign sets the system property odsign.verification.success if
1310 // AOT artifacts have the expected signatures.
1311 const bool trust_art_apex_data_files =
1312 ::android::base::GetBoolProperty("odsign.verification.success", false);
1313 if (!trust_art_apex_data_files) {
1314 AddRuntimeArg("-Xdeny-art-apex-data-files");
1315 }
1316
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001317 PrepareArgs(dexoptanalyzer_bin);
1318 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001319
1320 // Dexoptanalyzer mode which flattens the given class loader context and
1321 // prints a list of its dex files in that flattened order.
1322 RunDexoptAnalyzer(const char* class_loader_context) {
1323 CHECK(class_loader_context != nullptr);
1324
1325 // We always run the analyzer in the background job.
1326 const char* dexoptanalyzer_bin = select_execution_binary(
1327 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1328
1329 AddArg("--flatten-class-loader-context");
1330 AddArg(std::string("--class-loader-context=") + class_loader_context);
1331 PrepareArgs(dexoptanalyzer_bin);
1332 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001333};
Calin Juravle80a21252017-01-17 14:43:25 -08001334
1335// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001336static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001337 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001338 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001339 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001340 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001341 return false;
1342 }
Calin Juravle114f0812017-03-08 19:05:07 -08001343 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001344
Calin Juravle80a21252017-01-17 14:43:25 -08001345 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001346 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1347 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001348 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001349 return false;
1350 }
1351
1352 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001353 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001354
Calin Juravle7d765462017-09-04 15:57:10 -07001355 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001356 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001357 return false;
1358 }
1359
1360 return true;
1361}
1362
Calin Juravle7d765462017-09-04 15:57:10 -07001363// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1364// secondary dex files. This return codes are returned by the child process created for
1365// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001366
Andreas Gampe194fe422018-02-28 20:16:19 -08001367enum DexoptAnalyzerSkipCodes {
1368 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001369 // Specific errors are encoded in the name.
1370 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1371 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1372 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1373 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1374 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001375 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001376 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001377};
Calin Juravle7d765462017-09-04 15:57:10 -07001378
1379// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001380// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1381// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001382// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1383// of dexoptanalyzer.
1384static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001385 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001386 // The result values are defined in dexoptanalyzer.
1387 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001388 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001389 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001390 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001391 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001392 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001393 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001394 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001395 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001396 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1397 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001398 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1399 " Expected odex file status for secondary dex %s"
1400 " : dexoptanalyzer result=%d",
1401 dex_path.c_str(),
1402 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001403 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001404 }
1405
1406 // Use a second switch for enum switch-case analysis.
1407 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001408 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001409 // If the file does not exist there's no need for dexopt.
1410 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1411 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001412
1413 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1414 *error_msg = "Dexoptanalyzer path validation failed";
1415 return false;
1416 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1417 *error_msg = "Dexoptanalyzer open zip failed";
1418 return false;
1419 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1420 *error_msg = "Dexoptanalyzer dir preparation failed";
1421 return false;
1422 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1423 *error_msg = "Dexoptanalyzer open output failed";
1424 return false;
1425 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1426 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001427 return false;
1428 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001429
1430 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1431 dex_path.c_str(),
1432 result);
1433 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001434}
1435
Calin Juravle7d765462017-09-04 15:57:10 -07001436enum SecondaryDexAccess {
1437 kSecondaryDexAccessReadOk = 0,
1438 kSecondaryDexAccessDoesNotExist = 1,
1439 kSecondaryDexAccessPermissionError = 2,
1440 kSecondaryDexAccessIOError = 3
1441};
1442
1443static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1444 // Check if the path exists and can be read. If not, there's nothing to do.
1445 if (access(dex_path.c_str(), R_OK) == 0) {
1446 return kSecondaryDexAccessReadOk;
1447 } else {
1448 if (errno == ENOENT) {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001449 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1450 "Secondary dex does not exist: %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001451 return kSecondaryDexAccessDoesNotExist;
1452 } else {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001453 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1454 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
Calin Juravle7d765462017-09-04 15:57:10 -07001455 return errno == EACCES
1456 ? kSecondaryDexAccessPermissionError
1457 : kSecondaryDexAccessIOError;
1458 }
1459 }
1460}
1461
1462static bool is_file_public(const std::string& filename) {
1463 struct stat file_stat;
1464 if (stat(filename.c_str(), &file_stat) == 0) {
1465 return (file_stat.st_mode & S_IROTH) != 0;
1466 }
1467 return false;
1468}
1469
1470// Create the oat file structure for the secondary dex 'dex_path' and assign
1471// the individual path component to the 'out_' parameters.
1472static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001473 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001474 size_t dirIndex = dex_path.rfind('/');
1475 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001476 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001477 return false;
1478 }
1479 // TODO(calin): we have similar computations in at lest 3 other places
1480 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1481 // using string append.
1482 std::string apk_dir = dex_path.substr(0, dirIndex);
1483 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1484 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1485
1486 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1487 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001488 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001489 return false;
1490 }
1491 return true;
1492}
1493
1494// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1495// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001496static bool validate_dexopt_storage_flags(int dexopt_flags,
1497 int* out_storage_flag,
1498 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001499 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1500 *out_storage_flag = FLAG_STORAGE_CE;
1501 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001502 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001503 return false;
1504 }
1505 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1506 *out_storage_flag = FLAG_STORAGE_DE;
1507 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001508 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001509 return false;
1510 }
1511 return true;
1512}
1513
David Brazdil4f6027a2019-03-19 11:44:21 +00001514static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1515 /* out */ std::vector<std::string>* context_dex_paths) {
1516 if (class_loader_context == nullptr) {
1517 return true;
1518 }
1519
1520 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1521
1522 // Pipe to get the hash result back from our child process.
1523 unique_fd pipe_read, pipe_write;
1524 if (!Pipe(&pipe_read, &pipe_write)) {
1525 PLOG(ERROR) << "Failed to create pipe";
1526 return false;
1527 }
1528
1529 pid_t pid = fork();
1530 if (pid == 0) {
1531 // child -- drop privileges before continuing.
1532 drop_capabilities(uid);
1533
1534 // Route stdout to `pipe_write`
1535 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1536 pipe_write.reset();
1537 pipe_read.reset();
1538
1539 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1540 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1541 }
1542
1543 /* parent */
1544 pipe_write.reset();
1545
1546 std::string str_dex_paths;
1547 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1548 PLOG(ERROR) << "Failed to read from pipe";
1549 return false;
1550 }
1551 pipe_read.reset();
1552
1553 int return_code = wait_child(pid);
1554 if (!WIFEXITED(return_code)) {
1555 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1556 return false;
1557 }
1558
1559 constexpr int kFlattenClassLoaderContextSuccess = 50;
1560 return_code = WEXITSTATUS(return_code);
1561 if (return_code != kFlattenClassLoaderContextSuccess) {
1562 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1563 return false;
1564 }
1565
1566 if (!str_dex_paths.empty()) {
1567 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1568 }
1569 return true;
1570}
1571
1572static int open_dex_paths(const std::vector<std::string>& dex_paths,
1573 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1574 for (const std::string& dex_path : dex_paths) {
1575 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1576 if (zip_fds->back().get() < 0) {
1577 *error_msg = StringPrintf(
1578 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1579 if (errno == ENOENT) {
1580 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1581 } else {
1582 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1583 }
1584 }
1585 }
1586 return 0;
1587}
1588
1589static std::string join_fds(const std::vector<unique_fd>& fds) {
1590 std::stringstream ss;
1591 bool is_first = true;
1592 for (const unique_fd& fd : fds) {
1593 if (is_first) {
1594 is_first = false;
1595 } else {
1596 ss << ":";
1597 }
1598 ss << fd.get();
1599 }
1600 return ss.str();
1601}
1602
Keun young Park65578d62021-06-28 17:52:05 -07001603void control_dexopt_blocking(bool block) {
1604 dexopt_status_->control_dexopt_blocking(block);
1605}
1606
1607bool is_dexopt_blocked() {
1608 return dexopt_status_->is_dexopt_blocked();
1609}
1610
1611enum SecondaryDexOptProcessResult {
1612 kSecondaryDexOptProcessOk = 0,
1613 kSecondaryDexOptProcessCancelled = 1,
1614 kSecondaryDexOptProcessError = 2
1615};
1616
Calin Juravlec9eab382017-01-25 01:17:17 -08001617// 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 -07001618// be compiled.
1619// Returns: kSecondaryDexOptProcessError for errors (logged).
1620// kSecondaryDexOptProcessOk if the secondary dex path was process successfully.
1621// kSecondaryDexOptProcessCancelled if the processing was cancelled.
1622//
1623// When returning kSecondaryDexOptProcessOk, the output parameters will be:
Calin Juravleebc8a792017-04-04 20:21:05 -07001624// - is_public_out: whether or not the oat file should not be made public
1625// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1626// - oat_dir_out: the oat dir path where the oat file should be stored
Keun young Park65578d62021-06-28 17:52:05 -07001627static SecondaryDexOptProcessResult process_secondary_dex_dexopt(const std::string& dex_path,
1628 const char* pkgname, int dexopt_flags, const char* volume_uuid, int uid,
1629 const char* instruction_set, const char* compiler_filter, bool* is_public_out,
1630 int* dexopt_needed_out, std::string* oat_dir_out, bool downgrade,
1631 const char* class_loader_context, const std::vector<std::string>& context_dex_paths,
1632 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001633 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Keun young Park65578d62021-06-28 17:52:05 -07001634
1635 if (dexopt_status_->is_dexopt_blocked()) {
1636 return kSecondaryDexOptProcessCancelled;
1637 }
1638
Calin Juravle80a21252017-01-17 14:43:25 -08001639 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001640 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1641 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001642 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001643 }
Calin Juravle7d765462017-09-04 15:57:10 -07001644 // Compute the oat dir as it's not easy to extract it from the child computation.
1645 char oat_path[PKG_PATH_MAX];
1646 char oat_dir[PKG_PATH_MAX];
1647 char oat_isa_dir[PKG_PATH_MAX];
1648 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001649 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1650 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001651 return kSecondaryDexOptProcessError;
Calin Juravled23dee72017-07-06 16:29:11 -07001652 }
Calin Juravle7d765462017-09-04 15:57:10 -07001653 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001654
Keun young Park65578d62021-06-28 17:52:05 -07001655 bool cancelled = false;
1656 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1657 if (cancelled) {
1658 return kSecondaryDexOptProcessCancelled;
1659 }
Calin Juravle80a21252017-01-17 14:43:25 -08001660 if (pid == 0) {
1661 // child -- drop privileges before continuing.
1662 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001663
1664 // Validate the path structure.
1665 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001666 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1667 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001668 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001669 }
1670
1671 // Open the dex file.
1672 unique_fd zip_fd;
1673 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1674 if (zip_fd.get() < 0) {
1675 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001676 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001677 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001678 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001679 }
1680 }
1681
David Brazdil4f6027a2019-03-19 11:44:21 +00001682 // Open class loader context dex files.
1683 std::vector<unique_fd> context_zip_fds;
1684 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1685 if (open_dex_paths_rc != 0) {
1686 _exit(open_dex_paths_rc);
1687 }
1688
Calin Juravle7d765462017-09-04 15:57:10 -07001689 // Prepare the oat directories.
1690 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001691 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001692 }
1693
1694 // Open the vdex/oat files if any.
1695 unique_fd oat_file_fd;
1696 unique_fd vdex_file_fd;
1697 if (!maybe_open_oat_and_vdex_file(dex_path,
1698 *oat_dir_out,
1699 instruction_set,
1700 true /* is_secondary_dex */,
1701 &oat_file_fd,
1702 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001703 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001704 }
1705
1706 // Analyze profiles.
Calin Juravlee90de862021-06-08 08:04:52 -07001707 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
Calin Juravle824a64d2018-01-18 20:23:17 -08001708 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001709
1710 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001711 // Note that we do not do it before the fork since opening the files is required to happen
1712 // after forking.
1713 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1714 vdex_file_fd.get(),
1715 oat_file_fd.get(),
1716 zip_fd.get(),
1717 instruction_set,
Calin Juravlee90de862021-06-08 08:04:52 -07001718 compiler_filter,
1719 profile_analysis_result,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001720 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001721 class_loader_context,
1722 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001723 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001724 }
1725
1726 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001727 int result = wait_child(pid);
Keun young Park65578d62021-06-28 17:52:05 -07001728 cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Calin Juravle80a21252017-01-17 14:43:25 -08001729 if (!WIFEXITED(result)) {
Keun young Park65578d62021-06-28 17:52:05 -07001730 if ((WTERMSIG(result) == SIGKILL) && cancelled) {
1731 LOG(INFO) << "dexoptanalyzer cancelled for path:" << dex_path;
1732 return kSecondaryDexOptProcessCancelled;
1733 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001734 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1735 dex_path.c_str(),
1736 result);
1737 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001738 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001739 }
1740 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001741 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001742 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1743 result,
1744 dexopt_needed_out,
1745 error_msg);
1746 if (!success) {
1747 LOG(ERROR) << *error_msg;
1748 }
Calin Juravle7d765462017-09-04 15:57:10 -07001749
1750 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1751
Calin Juravle80a21252017-01-17 14:43:25 -08001752 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001753 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1754 // makes the code simpler; force compilation is only needed during tests).
1755 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001756 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001757 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001758 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1759 }
1760
Calin Juravle7d765462017-09-04 15:57:10 -07001761 // Check if we should make the oat file public.
1762 // Note that if the dex file is not public the compiled code cannot be made public.
1763 // It is ok to check this flag outside in the parent process.
1764 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1765
Keun young Park65578d62021-06-28 17:52:05 -07001766 return success ? kSecondaryDexOptProcessOk : kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001767}
1768
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001769static std::string format_dexopt_error(int status, const char* dex_path) {
1770 if (WIFEXITED(status)) {
1771 int int_code = WEXITSTATUS(status);
1772 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1773 if (code_name != nullptr) {
1774 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1775 }
1776 }
1777 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001778}
1779
Keun young Park65578d62021-06-28 17:52:05 -07001780
Calin Juravlec9eab382017-01-25 01:17:17 -08001781int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001782 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001783 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001784 bool downgrade, int target_sdk_version, const char* profile_name,
Keun young Park65578d62021-06-28 17:52:05 -07001785 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg,
1786 /* out */ bool* completed) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001787 CHECK(pkgname != nullptr);
1788 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001789 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001790 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1791 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001792
Keun young Park65578d62021-06-28 17:52:05 -07001793 bool local_completed; // local placeholder for nullptr case
1794 if (completed == nullptr) {
1795 completed = &local_completed;
1796 }
1797 *completed = true;
1798 if (dexopt_status_->is_dexopt_blocked()) {
1799 *completed = false;
1800 return 0;
1801 }
1802
Calin Juravled23dee72017-07-06 16:29:11 -07001803 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001804 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001805 return -1;
1806 }
1807
1808 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001809 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1810 class_loader_context);
1811 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001812 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001813 }
1814
Calin Juravleebc8a792017-04-04 20:21:05 -07001815 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001816 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1817 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1818 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001819 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001820 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001821 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001822 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001823 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001824 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001825
1826 // Check if we're dealing with a secondary dex file and if we need to compile it.
1827 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001828 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001829 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001830 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1831 *error_msg = "Failed acquiring context dex paths";
1832 return -1; // We had an error, logged in the process method.
1833 }
Keun young Park65578d62021-06-28 17:52:05 -07001834 SecondaryDexOptProcessResult sec_dex_result = process_secondary_dex_dexopt(dex_path,
1835 pkgname, dexopt_flags, volume_uuid, uid,instruction_set, compiler_filter,
1836 &is_public, &dexopt_needed, &oat_dir_str, downgrade, class_loader_context,
1837 context_dex_paths, error_msg);
1838 if (sec_dex_result == kSecondaryDexOptProcessOk) {
Calin Juravle80a21252017-01-17 14:43:25 -08001839 oat_dir = oat_dir_str.c_str();
1840 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1841 return 0; // Nothing to do, report success.
1842 }
Keun young Park65578d62021-06-28 17:52:05 -07001843 } else if (sec_dex_result == kSecondaryDexOptProcessCancelled) {
1844 // cancelled, not an error.
1845 *completed = false;
1846 return 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001847 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001848 if (error_msg->empty()) { // TODO: Make this a CHECK.
1849 *error_msg = "Failed processing secondary.";
1850 }
Calin Juravle80a21252017-01-17 14:43:25 -08001851 return -1; // We had an error, logged in the process method.
1852 }
1853 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001854 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001855 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001856 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1857 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1858 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001859
1860 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001861 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1862 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001863 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1864 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001865 return -1;
1866 }
1867
David Brazdil4f6027a2019-03-19 11:44:21 +00001868 // Open class loader context dex files.
1869 std::vector<unique_fd> context_input_fds;
1870 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1871 LOG(ERROR) << *error_msg;
1872 return -1;
1873 }
1874
Calin Juravle7a570e82017-01-14 16:23:30 -08001875 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001876 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1877 instruction_set, is_secondary_dex);
1878 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001879 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001880 return -1;
1881 }
1882
1883 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001884 UniqueFile in_vdex;
1885 UniqueFile out_vdex;
1886 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1887 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1888 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001889 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001890 return -1;
1891 }
1892
Calin Juravlecb556e32017-04-04 20:22:50 -07001893 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1894 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1895 // fully inherit their parent context).
1896 // Note that for primary apk the oat files are created before, in a separate installd
1897 // call which also does the restorecon. TODO(calin): unify the paths.
1898 if (is_secondary_dex) {
1899 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1900 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001901 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1902 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001903 return -1;
1904 }
1905 }
1906
Jeff Sharkey90aff262016-12-12 14:28:24 -07001907 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001908 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001909
Calin Juravle7a570e82017-01-14 16:23:30 -08001910 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001911 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001912 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001913
Victor Hsiehcb35a062020-08-13 16:11:13 -07001914 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001915 // We don't create an app image without reference profile since there is no speedup from
1916 // loading it in that case and instead will be a small overhead.
1917 generate_app_image = false;
1918 }
1919
1920 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001921 UniqueFile out_image = maybe_open_app_image(
1922 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001923
Victor Hsiehcb35a062020-08-13 16:11:13 -07001924 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001925 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001926 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1927 dex_metadata_path);
1928 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001929 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1930 }
1931 }
1932
Victor Hsieh8948a862020-08-07 11:30:55 -07001933 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1934 RUNTIME_NATIVE_BOOT_NAMESPACE,
1935 ENABLE_JITZYGOTE_IMAGE,
1936 /*default_value=*/ "");
1937 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1938
Victor Hsiehe98e6512020-08-10 15:39:22 -07001939 // Decide whether to use dex2oat64.
1940 bool use_dex2oat64 = false;
1941 // Check whether the device even supports 64-bit ABIs.
1942 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1943 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1944 }
1945 const char* dex2oat_bin = select_execution_binary(
1946 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1947 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1948 background_job_compile);
1949
Victor Hsiehc9821f12020-08-07 11:32:29 -07001950 auto execv_helper = std::make_unique<ExecVHelper>();
1951
Andreas Gampe023b2242018-02-28 16:03:25 -08001952 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001953
Victor Hsiehc9821f12020-08-07 11:32:29 -07001954 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001955 runner.Initialize(out_oat,
1956 out_vdex,
1957 out_image,
1958 in_dex,
1959 in_vdex,
1960 dex_metadata,
1961 reference_profile,
1962 class_loader_context,
1963 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001964 swap_fd.get(),
1965 instruction_set,
1966 compiler_filter,
1967 debuggable,
1968 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001969 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001970 target_sdk_version,
1971 enable_hidden_api_checks,
1972 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001973 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001974 compilation_reason);
1975
Keun young Park65578d62021-06-28 17:52:05 -07001976 bool cancelled = false;
1977 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1978 if (cancelled) {
1979 return 0;
1980 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001981 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001982 // Need to set schedpolicy before dropping privileges
1983 // for cgroup migration. See details at b/175178520.
1984 SetDex2OatScheduling(boot_complete);
1985
Jeff Sharkey90aff262016-12-12 14:28:24 -07001986 /* child -- drop privileges before continuing */
1987 drop_capabilities(uid);
1988
Victor Hsiehcb35a062020-08-13 16:11:13 -07001989 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001990 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1991 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001992 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001993 }
1994
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001995 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001996 } else {
1997 int res = wait_child(pid);
Keun young Park65578d62021-06-28 17:52:05 -07001998 bool cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001999 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002000 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002001 } else {
Keun young Park65578d62021-06-28 17:52:05 -07002002 if ((WTERMSIG(res) == SIGKILL) && cancelled) {
2003 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- cancelled";
2004 // cancelled, not an error
2005 *completed = false;
2006 return 0;
2007 }
Andreas Gampe023b2242018-02-28 16:03:25 -08002008 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2009 << std::hex << std::setw(4) << res << ", process failed";
2010 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002011 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002012 }
2013 }
2014
Keun young Park65578d62021-06-28 17:52:05 -07002015 // TODO(b/156537504) Implement SWAP of completed files
Jeff Sharkey90aff262016-12-12 14:28:24 -07002016 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07002017 out_oat.DisableCleanup();
2018 out_vdex.DisableCleanup();
2019 out_image.DisableCleanup();
2020 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07002021
Keun young Park65578d62021-06-28 17:52:05 -07002022 *completed = true;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002023 return 0;
2024}
2025
Calin Juravlec9eab382017-01-25 01:17:17 -08002026// Try to remove the given directory. Log an error if the directory exists
2027// and is empty but could not be removed.
2028static bool rmdir_if_empty(const char* dir) {
2029 if (rmdir(dir) == 0) {
2030 return true;
2031 }
2032 if (errno == ENOENT || errno == ENOTEMPTY) {
2033 return true;
2034 }
2035 PLOG(ERROR) << "Failed to remove dir: " << dir;
2036 return false;
2037}
2038
2039// Try to unlink the given file. Log an error if the file exists and could not
2040// be unlinked.
2041static bool unlink_if_exists(const std::string& file) {
2042 if (unlink(file.c_str()) == 0) {
2043 return true;
2044 }
2045 if (errno == ENOENT) {
2046 return true;
2047
2048 }
2049 PLOG(ERROR) << "Could not unlink: " << file;
2050 return false;
2051}
2052
Calin Juravle7d765462017-09-04 15:57:10 -07002053enum ReconcileSecondaryDexResult {
2054 kReconcileSecondaryDexExists = 0,
2055 kReconcileSecondaryDexCleanedUp = 1,
2056 kReconcileSecondaryDexValidationError = 2,
2057 kReconcileSecondaryDexCleanUpError = 3,
2058 kReconcileSecondaryDexAccessIOError = 4,
2059};
Calin Juravlec9eab382017-01-25 01:17:17 -08002060
2061// Reconcile the secondary dex 'dex_path' and its generated oat files.
2062// Return true if all the parameters are valid and the secondary dex file was
2063// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2064// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2065// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2066// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2067// Return false if there were errors during processing. In this case
2068// out_secondary_dex_exists will be set to false.
2069bool reconcile_secondary_dex_file(const std::string& dex_path,
2070 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002071 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002072 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002073 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002074 if (isas.size() == 0) {
2075 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2076 return false;
2077 }
2078
Calin Juravle7d765462017-09-04 15:57:10 -07002079 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2080 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2081 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002082 return false;
2083 }
2084
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002085 // As a security measure we want to unlink art artifacts with the reduced capabilities
2086 // of the package user id. So we fork and drop capabilities in the child.
2087 pid_t pid = fork();
2088 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002089 /* child -- drop privileges before continuing */
2090 drop_capabilities(uid);
2091
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002092 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002093 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002094 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002095 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2096 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002097 _exit(kReconcileSecondaryDexValidationError);
2098 }
2099
2100 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2101 switch (access_check) {
2102 case kSecondaryDexAccessDoesNotExist:
2103 // File does not exist. Proceed with cleaning.
2104 break;
2105 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2106 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2107 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2108 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02002109 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2110 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07002111 _exit(kReconcileSecondaryDexValidationError);
2112 }
2113
2114 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002115 char oat_path[PKG_PATH_MAX];
2116 char oat_dir[PKG_PATH_MAX];
2117 char oat_isa_dir[PKG_PATH_MAX];
2118 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002119 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002120 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002121 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002122 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002123 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002124 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002125 }
Calin Juravle51314092017-05-18 15:33:05 -07002126
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002127 // Delete oat/vdex/art files.
2128 result = unlink_if_exists(oat_path) && result;
2129 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2130 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002131
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002132 // Delete profiles.
2133 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002134 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002135 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002136 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002137 result = unlink_if_exists(current_profile) && result;
2138 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002139
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002140 // We upgraded once the location of current profile for secondary dex files.
2141 // Check for any previous left-overs and remove them as well.
2142 std::string old_current_profile = dex_path + ".prof";
2143 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002144
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002145 // Try removing the directories as well, they might be empty.
2146 result = rmdir_if_empty(oat_isa_dir) && result;
2147 result = rmdir_if_empty(oat_dir) && result;
2148 }
Calin Juravle7d765462017-09-04 15:57:10 -07002149 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002150 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2151 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002152 }
2153 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002154 }
2155
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002156 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002157 if (!WIFEXITED(return_code)) {
2158 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2159 } else {
2160 return_code = WEXITSTATUS(return_code);
2161 }
2162
2163 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2164
2165 switch (return_code) {
2166 case kReconcileSecondaryDexCleanedUp:
2167 case kReconcileSecondaryDexValidationError:
2168 // If we couldn't validate assume the dex file does not exist.
2169 // This will purge the entry from the PM records.
2170 *out_secondary_dex_exists = false;
2171 return true;
2172 case kReconcileSecondaryDexExists:
2173 *out_secondary_dex_exists = true;
2174 return true;
2175 case kReconcileSecondaryDexAccessIOError:
2176 // We had an access IO error.
2177 // Return false so that we can try again.
2178 // The value of out_secondary_dex_exists does not matter in this case and by convention
2179 // is set to false.
2180 *out_secondary_dex_exists = false;
2181 return false;
2182 default:
2183 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2184 *out_secondary_dex_exists = false;
2185 return false;
2186 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002187}
2188
Alan Stokesa25d90c2017-10-16 10:56:00 +01002189// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2190// Returns true if all parameters are valid and the hash successfully computed and stored in
2191// out_secondary_dex_hash.
2192// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2193// the app.
2194// For any other errors (e.g. if any of the parameters are invalid) returns false.
2195bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002196 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002197 std::vector<uint8_t>* out_secondary_dex_hash) {
2198 out_secondary_dex_hash->clear();
2199
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002200 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002201
2202 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2203 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2204 << storage_flag;
2205 return false;
2206 }
2207
2208 // Pipe to get the hash result back from our child process.
2209 unique_fd pipe_read, pipe_write;
2210 if (!Pipe(&pipe_read, &pipe_write)) {
2211 PLOG(ERROR) << "Failed to create pipe";
2212 return false;
2213 }
2214
2215 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2216 // access data the app itself can access.
2217 pid_t pid = fork();
2218 if (pid == 0) {
2219 // child -- drop privileges before continuing
2220 drop_capabilities(uid);
2221 pipe_read.reset();
2222
2223 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002224 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2225 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002226 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002227 }
2228
2229 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2230 if (fd == -1) {
2231 if (errno == EACCES || errno == ENOENT) {
2232 // Not treated as an error.
2233 _exit(0);
2234 }
2235 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002236 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2237 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002238 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002239 }
2240
2241 SHA256_CTX ctx;
2242 SHA256_Init(&ctx);
2243
2244 std::vector<uint8_t> buffer(65536);
2245 while (true) {
2246 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2247 if (bytes_read == 0) {
2248 break;
2249 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002250 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2251 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002252 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002253 }
2254
2255 SHA256_Update(&ctx, buffer.data(), bytes_read);
2256 }
2257
2258 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2259 SHA256_Final(hash.data(), &ctx);
2260 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002261 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002262 }
2263
2264 _exit(0);
2265 }
2266
2267 // parent
2268 pipe_write.reset();
2269
2270 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2271 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2272 out_secondary_dex_hash->clear();
2273 }
2274 return wait_child(pid) == 0;
2275}
2276
Jeff Sharkey90aff262016-12-12 14:28:24 -07002277// Helper for move_ab, so that we can have common failure-case cleanup.
2278static bool unlink_and_rename(const char* from, const char* to) {
2279 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2280 // return a failure.
2281 struct stat s;
2282 if (stat(to, &s) == 0) {
2283 if (!S_ISREG(s.st_mode)) {
2284 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2285 return false;
2286 }
2287 if (unlink(to) != 0) {
2288 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2289 return false;
2290 }
2291 } else {
2292 // This may be a permission problem. We could investigate the error code, but we'll just
2293 // let the rename failure do the work for us.
2294 }
2295
2296 // Try to rename "to" to "from."
2297 if (rename(from, to) != 0) {
2298 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2299 return false;
2300 }
2301 return true;
2302}
2303
2304// Move/rename a B artifact (from) to an A artifact (to).
2305static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2306 // Check whether B exists.
2307 {
2308 struct stat s;
2309 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002310 // Ignore for now. The service calling this isn't smart enough to
2311 // understand lack of artifacts at the moment.
2312 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002313 return false;
2314 }
2315 if (!S_ISREG(s.st_mode)) {
2316 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2317 // Try to unlink, but swallow errors.
2318 unlink(b_path.c_str());
2319 return false;
2320 }
2321 }
2322
2323 // Rename B to A.
2324 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2325 // Delete the b_path so we don't try again (or fail earlier).
2326 if (unlink(b_path.c_str()) != 0) {
2327 PLOG(ERROR) << "Could not unlink " << b_path;
2328 }
2329
2330 return false;
2331 }
2332
2333 return true;
2334}
2335
2336bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2337 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002338 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2339 if (slot_suffix.empty()) {
2340 return false;
2341 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002342
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002343 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2344 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2345 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002346 }
2347
2348 // Validate other inputs.
2349 if (validate_apk_path(apk_path) != 0) {
2350 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2351 return false;
2352 }
2353 if (validate_apk_path(oat_dir) != 0) {
2354 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2355 return false;
2356 }
2357
2358 char a_path[PKG_PATH_MAX];
2359 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2360 return false;
2361 }
2362 const std::string a_vdex_path = create_vdex_filename(a_path);
2363 const std::string a_image_path = create_image_filename(a_path);
2364
2365 // B path = A path + slot suffix.
2366 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2367 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2368 const std::string b_image_path = StringPrintf("%s.%s",
2369 a_image_path.c_str(),
2370 slot_suffix.c_str());
2371
2372 bool success = true;
2373 if (move_ab_path(b_path, a_path)) {
2374 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2375 // Note: we can live without an app image. As such, ignore failure to move the image file.
2376 // If we decide to require the app image, or the app image being moved correctly,
2377 // then change accordingly.
2378 constexpr bool kIgnoreAppImageFailure = true;
2379
2380 if (!a_image_path.empty()) {
2381 if (!move_ab_path(b_image_path, a_image_path)) {
2382 unlink(a_image_path.c_str());
2383 if (!kIgnoreAppImageFailure) {
2384 success = false;
2385 }
2386 }
2387 }
2388 } else {
2389 // Cleanup: delete B image, ignore errors.
2390 unlink(b_image_path.c_str());
2391 success = false;
2392 }
2393 } else {
2394 // Cleanup: delete B image, ignore errors.
2395 unlink(b_vdex_path.c_str());
2396 unlink(b_image_path.c_str());
2397 success = false;
2398 }
2399 return success;
2400}
2401
Calin Juravle0f3beba2021-06-11 09:17:20 -07002402int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002403 // Delete the oat/odex file.
2404 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002405 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002406 /*is_secondary_dex*/false, out_path)) {
Calin Juravle0f3beba2021-06-11 09:17:20 -07002407 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2408 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002409 }
2410
2411 // In case of a permission failure report the issue. Otherwise just print a warning.
Calin Juravle0f3beba2021-06-11 09:17:20 -07002412 auto unlink_and_check = [](const char* path) -> int64_t {
2413 struct stat file_stat;
2414 if (stat(path, &file_stat) != 0) {
2415 if (errno != ENOENT) {
2416 PLOG(ERROR) << "Could not stat " << path;
2417 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002418 }
Calin Juravle0f3beba2021-06-11 09:17:20 -07002419 return 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002420 }
Calin Juravle0f3beba2021-06-11 09:17:20 -07002421
2422 if (unlink(path) != 0) {
2423 if (errno != ENOENT) {
2424 PLOG(ERROR) << "Could not unlink " << path;
2425 return -1;
2426 }
2427 }
2428 return static_cast<int64_t>(file_stat.st_size);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002429 };
2430
2431 // Delete the oat/odex file.
Calin Juravle0f3beba2021-06-11 09:17:20 -07002432 int64_t return_value_oat = unlink_and_check(out_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002433
2434 // Derive and delete the app image.
Calin Juravle0f3beba2021-06-11 09:17:20 -07002435 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07002436
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002437 // Derive and delete the vdex file.
Calin Juravle0f3beba2021-06-11 09:17:20 -07002438 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002439
Calin Juravle0f3beba2021-06-11 09:17:20 -07002440 // Report result
2441 if (return_value_oat == -1
2442 || return_value_art == -1
2443 || return_value_vdex == -1) {
2444 return -1;
2445 }
2446
2447 return return_value_oat + return_value_art + return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002448}
2449
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002450static bool is_absolute_path(const std::string& path) {
2451 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2452 LOG(ERROR) << "Invalid absolute path " << path;
2453 return false;
2454 } else {
2455 return true;
2456 }
2457}
2458
2459static bool is_valid_instruction_set(const std::string& instruction_set) {
2460 // TODO: add explicit whitelisting of instruction sets
2461 if (instruction_set.find('/') != std::string::npos) {
2462 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2463 return false;
2464 } else {
2465 return true;
2466 }
2467}
2468
2469bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2470 const char *apk_path, const char *instruction_set) {
2471 std::string oat_dir_ = oat_dir;
2472 std::string apk_path_ = apk_path;
2473 std::string instruction_set_ = instruction_set;
2474
2475 if (!is_absolute_path(oat_dir_)) return false;
2476 if (!is_absolute_path(apk_path_)) return false;
2477 if (!is_valid_instruction_set(instruction_set_)) return false;
2478
2479 std::string::size_type end = apk_path_.rfind('.');
2480 std::string::size_type start = apk_path_.rfind('/', end);
2481 if (end == std::string::npos || start == std::string::npos) {
2482 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2483 return false;
2484 }
2485
2486 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2487 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2488 const char* res = res_.c_str();
2489 if (strlen(res) >= PKG_PATH_MAX) {
2490 LOG(ERROR) << "Result too large";
2491 return false;
2492 } else {
2493 strlcpy(path, res, PKG_PATH_MAX);
2494 return true;
2495 }
2496}
2497
2498bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2499 const char *instruction_set) {
2500 std::string apk_path_ = apk_path;
2501 std::string instruction_set_ = instruction_set;
2502
2503 if (!is_absolute_path(apk_path_)) return false;
2504 if (!is_valid_instruction_set(instruction_set_)) return false;
2505
2506 std::string::size_type end = apk_path_.rfind('.');
2507 std::string::size_type start = apk_path_.rfind('/', end);
2508 if (end == std::string::npos || start == std::string::npos) {
2509 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2510 return false;
2511 }
2512
2513 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2514 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2515}
2516
2517bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2518 const char *instruction_set) {
2519 std::string src_ = src;
2520 std::string instruction_set_ = instruction_set;
2521
2522 if (!is_absolute_path(src_)) return false;
2523 if (!is_valid_instruction_set(instruction_set_)) return false;
2524
2525 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2526 if (*it == '/') {
2527 *it = '@';
2528 }
2529 }
2530
2531 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2532 + DALVIK_CACHE_POSTFIX;
2533 const char* res = res_.c_str();
2534 if (strlen(res) >= PKG_PATH_MAX) {
2535 LOG(ERROR) << "Result too large";
2536 return false;
2537 } else {
2538 strlcpy(path, res, PKG_PATH_MAX);
2539 return true;
2540 }
2541}
2542
Calin Juravle59f7ab82018-04-27 17:50:23 -07002543bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2544 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002545 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2546 for (const std::string& elem : classpaths_elems) {
2547 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2548 if (fd < 0) {
2549 PLOG(ERROR) << "Could not open classpath elem " << elem;
2550 return false;
2551 } else {
2552 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002553 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002554 }
2555 }
2556 return true;
2557}
2558
2559static bool create_app_profile_snapshot(int32_t app_id,
2560 const std::string& package_name,
2561 const std::string& profile_name,
2562 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002563 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2564
Calin Juravle824a64d2018-01-18 20:23:17 -08002565 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002566 if (snapshot_fd < 0) {
2567 return false;
2568 }
2569
2570 std::vector<unique_fd> profiles_fd;
2571 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002572 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2573 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002574 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2575 return false;
2576 }
2577
2578 profiles_fd.push_back(std::move(reference_profile_fd));
2579
Calin Juravle0d0a4922018-01-23 19:54:11 -08002580 // Open the class paths elements. These will be used to filter out profile data that does
2581 // not belong to the classpath during merge.
2582 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002583 std::vector<std::string> dex_locations;
2584 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002585 return false;
2586 }
2587
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002588 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002589 // This is specifically a snapshot for an app, so don't use boot image profiles.
2590 args.SetupMerge(profiles_fd,
2591 snapshot_fd,
2592 apk_fds,
2593 dex_locations,
2594 /* for_snapshot= */ true,
2595 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002596 pid_t pid = fork();
2597 if (pid == 0) {
2598 /* child -- drop privileges before continuing */
2599 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002600 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002601 }
2602
2603 /* parent */
2604 int return_code = wait_child(pid);
2605 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002606 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002607 return false;
2608 }
2609
Calin Juravle78728f32019-11-08 17:55:46 -08002610 // Verify that profman finished successfully.
2611 int profman_code = WEXITSTATUS(return_code);
2612 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2613 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2614 << ":" << profman_code;
2615 return false;
2616 }
Calin Juravle29591732017-11-20 17:46:19 -08002617 return true;
2618}
2619
Calin Juravle0d0a4922018-01-23 19:54:11 -08002620static bool create_boot_image_profile_snapshot(const std::string& package_name,
2621 const std::string& profile_name,
2622 const std::string& classpath) {
2623 // The reference profile directory for the android package might not be prepared. Do it now.
2624 const std::string ref_profile_dir =
2625 create_primary_reference_profile_package_dir_path(package_name);
2626 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2627 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2628 return false;
2629 }
2630
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002631 // Return false for empty class path since it may otherwise return true below if profiles is
2632 // empty.
2633 if (classpath.empty()) {
2634 PLOG(ERROR) << "Class path is empty";
2635 return false;
2636 }
2637
Calin Juravle0d0a4922018-01-23 19:54:11 -08002638 // Open and create the snapshot profile.
2639 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2640
2641 // Collect all non empty profiles.
2642 // The collection will traverse all applications profiles and find the non empty files.
2643 // This has the potential of inspecting a large number of files and directories (depending
2644 // on the number of applications and users). So there is a slight increase in the chance
2645 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2646 // fail the snapshot and aggregate whatever profile we could open.
2647 //
2648 // The profile snapshot is a best effort based on available data it's ok if some data
2649 // from some apps is missing. It will be counter productive for the snapshot to fail
2650 // because we could not open or read some of the files.
2651 std::vector<std::string> profiles;
2652 if (!collect_profiles(&profiles)) {
2653 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2654 }
2655
2656 // If we have no profiles return early.
2657 if (profiles.empty()) {
2658 return true;
2659 }
2660
2661 // Open the classpath elements. These will be used to filter out profile data that does
2662 // not belong to the classpath during merge.
2663 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002664 std::vector<std::string> dex_locations;
2665 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002666 return false;
2667 }
2668
2669 // If we could not open any files from the classpath return an error.
2670 if (apk_fds.empty()) {
2671 LOG(ERROR) << "Could not open any of the classpath elements.";
2672 return false;
2673 }
2674
2675 // Aggregate the profiles in batches of kAggregationBatchSize.
2676 // We do this to avoid opening a huge a amount of files.
2677 static constexpr size_t kAggregationBatchSize = 10;
2678
Calin Juravle0d0a4922018-01-23 19:54:11 -08002679 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002680 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002681 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
Calin Juravle31c68e72021-06-03 18:16:54 -07002682 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002683 if (fd.get() >= 0) {
2684 profiles_fd.push_back(std::move(fd));
2685 }
2686 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002687
2688 // We aggregate (read & write) into the same fd multiple times in a row.
2689 // We need to reset the cursor every time to ensure we read the whole file every time.
2690 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2691 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2692 return false;
2693 }
2694
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002695 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002696 args.SetupMerge(profiles_fd,
2697 snapshot_fd,
2698 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002699 dex_locations,
2700 /*for_snapshot=*/true,
2701 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002702 pid_t pid = fork();
2703 if (pid == 0) {
2704 /* child -- drop privileges before continuing */
2705 drop_capabilities(AID_SYSTEM);
2706
Calin Juravle59f7ab82018-04-27 17:50:23 -07002707 // The introduction of new access flags into boot jars causes them to
2708 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002709 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002710 }
2711
2712 /* parent */
2713 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002714
Calin Juravle0d0a4922018-01-23 19:54:11 -08002715 if (!WIFEXITED(return_code)) {
2716 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2717 return false;
2718 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002719
2720 // Verify that profman finished successfully.
2721 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002722 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2723 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2724 << ":" << profman_code;
2725 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002726 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002727 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002728
Calin Juravle0d0a4922018-01-23 19:54:11 -08002729 return true;
2730}
2731
2732bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2733 const std::string& profile_name, const std::string& classpath) {
2734 if (app_id == -1) {
2735 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2736 } else {
2737 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2738 }
2739}
2740
Calin Juravlec3b049e2018-01-18 22:32:58 -08002741bool prepare_app_profile(const std::string& package_name,
2742 userid_t user_id,
2743 appid_t app_id,
2744 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002745 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002746 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002747 // Prepare the current profile.
2748 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2749 /*is_secondary_dex*/ false);
2750 uid_t uid = multiuser_get_uid(user_id, app_id);
2751 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2752 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2753 return false;
2754 }
2755
2756 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002757 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002758 return true;
2759 }
2760
2761 // We have a dex metdata. Merge the profile into the reference profile.
2762 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2763 /*read_write*/ true, /*is_secondary_dex*/ false);
2764 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2765 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002766 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2767 if (apk_fd < 0) {
2768 PLOG(ERROR) << "Could not open code path " << code_path;
2769 return false;
2770 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002771
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002772 RunProfman args;
2773 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2774 std::move(ref_profile_fd),
2775 std::move(apk_fd),
2776 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002777 pid_t pid = fork();
2778 if (pid == 0) {
2779 /* child -- drop privileges before continuing */
2780 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2781 drop_capabilities(app_shared_gid);
2782
Calin Juravlef63d4792018-01-30 17:43:34 +00002783 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002784 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002785 }
2786
2787 /* parent */
2788 int return_code = wait_child(pid);
2789 if (!WIFEXITED(return_code)) {
2790 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2791 return false;
2792 }
2793 return true;
2794}
2795
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002796} // namespace installd
2797} // namespace android