blob: 794750ff813cd7d40acc72e3dada643ca975be9a [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Jeff Sharkey90aff262016-12-12 14:28:24 -070018#include <fcntl.h>
Keun young Park65578d62021-06-28 17:52:05 -070019#include <signal.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Keun young Park65578d62021-06-28 17:52:05 -070031#include <array>
Andreas Gampe023b2242018-02-28 16:03:25 -080032#include <iomanip>
Keun young Park65578d62021-06-28 17:52:05 -070033#include <mutex>
34#include <unordered_set>
Andreas Gampe023b2242018-02-28 16:03:25 -080035
Alan Stokesa25d90c2017-10-16 10:56:00 +010036#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070037#include <android-base/logging.h>
Keun young Park65578d62021-06-28 17:52:05 -070038#include <android-base/no_destructor.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070039#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070040#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
Martijn Coenen6de402a2021-04-26 16:23:40 +020043#include <async_safe/log.h>
Calin Juravle80a21252017-01-17 14:43:25 -080044#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <cutils/properties.h>
46#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070047#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010048#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <private/android_filesystem_config.h>
Wei Wang0efe8d52021-07-07 17:32:38 -070050#include <processgroup/processgroup.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070051#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000052#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070053#include <system/thread_defs.h>
Keun young Park65578d62021-06-28 17:52:05 -070054#include <utils/Mutex.h>
Yang Tianping8f2a40e2021-10-29 14:39:02 +080055#include <ziparchive/zip_archive.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070056
57#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080058#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070059#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060060#include "globals.h"
Calin Juravle3b758282021-06-08 08:04:52 -070061#include "installd_constants.h"
Keun young Parkb7342262021-10-25 08:09:27 -070062#include "installd_deps.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070063#include "otapreopt_utils.h"
Keun young Parkb7342262021-10-25 08:09:27 -070064#include "restorable_file.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070065#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070066#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067#include "utils.h"
68
Victor Hsieh76f19ba2020-08-10 14:37:26 -070069using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070070using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070071using android::base::GetBoolProperty;
72using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000073using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010074using android::base::ReadFully;
75using android::base::StringPrintf;
76using android::base::WriteFully;
Jiakai Zhang495142a2022-02-21 19:38:14 +000077using android::base::borrowed_fd;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080078using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070079
Keun young Park65578d62021-06-28 17:52:05 -070080namespace {
81
Jiakai Zhang495142a2022-02-21 19:38:14 +000082// Timeout for short operations, such as merging profiles.
83constexpr int kShortTimeoutMs = 60000; // 1 minute.
84
85// Timeout for long operations, such as compilation. This should be smaller than the Package Manager
86// watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that the operation will be
87// aborted before that watchdog would take down the system server.
88constexpr int kLongTimeoutMs = 570000; // 9.5 minutes.
89
Keun young Park65578d62021-06-28 17:52:05 -070090class DexOptStatus {
91 public:
92 // Check if dexopt is cancelled and fork if it is not cancelled.
93 // cancelled is set to true if cancelled. Otherwise it will be set to false.
94 // If it is not cancelled, it will return the return value of fork() call.
95 // If cancelled, fork will not happen and it will return -1.
96 pid_t check_cancellation_and_fork(/* out */ bool *cancelled) {
97 std::lock_guard<std::mutex> lock(dexopt_lock_);
98 if (dexopt_blocked_) {
99 *cancelled = true;
100 return -1;
101 }
102 pid_t pid = fork();
103 *cancelled = false;
104 if (pid > 0) { // parent
105 dexopt_pids_.insert(pid);
106 }
107 return pid;
108 }
109
110 // Returns true if pid was killed (is in killed list). It could have finished if killing
111 // happened after the process is finished.
112 bool check_if_killed_and_remove_dexopt_pid(pid_t pid) {
113 std::lock_guard<std::mutex> lock(dexopt_lock_);
114 dexopt_pids_.erase(pid);
115 if (dexopt_killed_pids_.erase(pid) == 1) {
116 return true;
117 }
118 return false;
119 }
120
121 // Tells whether dexopt is blocked or not.
122 bool is_dexopt_blocked() {
123 std::lock_guard<std::mutex> lock(dexopt_lock_);
124 return dexopt_blocked_;
125 }
126
127 // Enable or disable dexopt blocking.
128 void control_dexopt_blocking(bool block) {
129 std::lock_guard<std::mutex> lock(dexopt_lock_);
130 dexopt_blocked_ = block;
131 if (!block) {
132 return;
133 }
134 // Blocked, also kill currently running tasks
135 for (auto pid : dexopt_pids_) {
136 LOG(INFO) << "control_dexopt_blocking kill pid:" << pid;
137 kill(pid, SIGKILL);
138 dexopt_killed_pids_.insert(pid);
139 }
140 dexopt_pids_.clear();
141 }
142
143 private:
144 std::mutex dexopt_lock_;
145 // when true, dexopt is blocked and will not run.
146 bool dexopt_blocked_ GUARDED_BY(dexopt_lock_) = false;
147 // PIDs of child process while runinng dexopt.
148 // If the child process is finished, it should be removed.
149 std::unordered_set<pid_t> dexopt_pids_ GUARDED_BY(dexopt_lock_);
150 // PIDs of child processes killed by cancellation.
151 std::unordered_set<pid_t> dexopt_killed_pids_ GUARDED_BY(dexopt_lock_);
152};
153
154android::base::NoDestructor<DexOptStatus> dexopt_status_;
155
156} // namespace
157
Jeff Sharkey6c2c0562016-12-07 12:12:00 -0700158namespace android {
159namespace installd {
160
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800161
Calin Juravle114f0812017-03-08 19:05:07 -0800162// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
163struct FreeDelete {
164 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
165 void operator()(const void* ptr) const {
166 free(const_cast<void*>(ptr));
167 }
168};
169
170// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
171template <typename T>
172using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
173
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800174static unique_fd invalid_unique_fd() {
175 return unique_fd(-1);
176}
177
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700178static bool is_debug_runtime() {
179 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
180}
181
David Sehra3b5ab62017-10-25 14:27:29 -0700182static bool is_debuggable_build() {
183 return android::base::GetBoolProperty("ro.debuggable", false);
184}
185
Jeff Sharkey90aff262016-12-12 14:28:24 -0700186static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800187 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700188 if (ufd.get() < 0) {
189 if (errno != ENOENT) {
190 PLOG(WARNING) << "Could not open profile " << profile;
191 return false;
192 } else {
193 // Nothing to clear. That's ok.
194 return true;
195 }
196 }
197
198 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
199 if (errno != EWOULDBLOCK) {
200 PLOG(WARNING) << "Error locking profile " << profile;
201 }
202 // This implies that the app owning this profile is running
203 // (and has acquired the lock).
204 //
205 // If we can't acquire the lock bail out since clearing is useless anyway
206 // (the app will write again to the profile).
207 //
208 // Note:
209 // This does not impact the this is not an issue for the profiling correctness.
210 // In case this is needed because of an app upgrade, profiles will still be
211 // eventually cleared by the app itself due to checksum mismatch.
212 // If this is needed because profman advised, then keeping the data around
213 // until the next run is again not an issue.
214 //
215 // If the app attempts to acquire a lock while we've held one here,
216 // it will simply skip the current write cycle.
217 return false;
218 }
219
220 bool truncated = ftruncate(ufd.get(), 0) == 0;
221 if (!truncated) {
222 PLOG(WARNING) << "Could not truncate " << profile;
223 }
224 if (flock(ufd.get(), LOCK_UN) != 0) {
225 PLOG(WARNING) << "Error unlocking profile " << profile;
226 }
227 return truncated;
228}
229
Calin Juravle114f0812017-03-08 19:05:07 -0800230// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800231// The location is the profile name for primary apks or the dex path for secondary dex files.
232static bool clear_reference_profile(const std::string& package_name, const std::string& location,
233 bool is_secondary_dex) {
234 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700235}
236
Calin Juravle114f0812017-03-08 19:05:07 -0800237// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800238// The location is the profile name for primary apks or the dex path for secondary dex files.
239static bool clear_current_profile(const std::string& package_name, const std::string& location,
240 userid_t user, bool is_secondary_dex) {
241 return clear_profile(create_current_profile_path(user, package_name, location,
242 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700243}
244
Calin Juravle114f0812017-03-08 19:05:07 -0800245// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800246// The location is the profile name for primary apks or the dex path for secondary dex files.
247bool clear_primary_reference_profile(const std::string& package_name,
248 const std::string& location) {
249 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800250}
251
252// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800253// The location is the profile name for primary apks or the dex path for secondary dex files.
254bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700255 bool success = true;
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000256 // For secondary dex files, we don't really need the user but we use it for validity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700257 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
258 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800259 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700260 }
261 return success;
262}
263
Calin Juravle114f0812017-03-08 19:05:07 -0800264// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800265bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
266 userid_t user) {
267 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800268}
269
Calin Juravlef74a7372019-02-28 20:29:41 -0800270// Determines which binary we should use for execution (the debug or non-debug version).
271// e.g. dex2oatd vs dex2oat
272static const char* select_execution_binary(const char* binary, const char* debug_binary,
273 bool background_job_compile) {
274 return select_execution_binary(
275 binary,
276 debug_binary,
277 background_job_compile,
278 is_debug_runtime(),
279 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
280 is_debuggable_build());
281}
282
283// Determines which binary we should use for execution (the debug or non-debug version).
284// e.g. dex2oatd vs dex2oat
285// This is convenient method which is much easier to test because it doesn't read
286// system properties.
287const char* select_execution_binary(
288 const char* binary,
289 const char* debug_binary,
290 bool background_job_compile,
291 bool is_debug_runtime,
292 bool is_release,
293 bool is_debuggable_build) {
294 // Do not use debug binaries for release candidates (to give more soak time).
295 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
296
297 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
298 // the file is present (it may not be on images with very little space available).
299 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
300
301 return useDebug ? debug_binary : binary;
302}
303
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000304// Namespace for Android Runtime flags applied during boot time.
305static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
306// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000307static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000308
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700309// Phenotype property name for enabling profiling the boot class path.
310static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
311
Calin Juravlef85ddb92020-05-01 14:05:40 -0700312static bool IsBootClassPathProfilingEnable() {
313 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
314 profile_boot_class_path =
315 server_configurable_flags::GetServerConfigurableFlag(
316 RUNTIME_NATIVE_BOOT_NAMESPACE,
317 PROFILE_BOOT_CLASS_PATH,
318 /*default_value=*/ profile_boot_class_path);
319 return profile_boot_class_path == "true";
320}
321
Jeff Sharkey90aff262016-12-12 14:28:24 -0700322/*
323 * Whether dexopt should use a swap file when compiling an APK.
324 *
325 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
326 * itself, anyways).
327 *
328 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
329 *
330 * Otherwise, return true if this is a low-mem device.
331 *
332 * Otherwise, return default value.
333 */
334static bool kAlwaysProvideSwapFile = false;
335static bool kDefaultProvideSwapFile = true;
336
337static bool ShouldUseSwapFileForDexopt() {
338 if (kAlwaysProvideSwapFile) {
339 return true;
340 }
341
342 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700343 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
344 if (!dex2oat_prop_buf.empty()) {
345 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700346 }
347
348 // Shortcut for default value. This is an implementation optimization for the process sketched
349 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
350 // as low-mem is never returning false. The compiler will optimize this away if it can.
351 if (kDefaultProvideSwapFile) {
352 return true;
353 }
354
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700355 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700356 return true;
357 }
358
359 // Default value must be false here.
360 return kDefaultProvideSwapFile;
361}
362
Richard Uhler76cc0272016-12-08 10:46:35 +0000363static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700364 if (set_to_bg) {
Wei Wang0efe8d52021-07-07 17:32:38 -0700365 if (!SetTaskProfiles(0, {"Dex2OatBootComplete"})) {
366 LOG(ERROR) << "Failed to set dex2oat task profile";
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800367 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700368 }
369 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800370 PLOG(ERROR) << "setpriority failed";
371 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700372 }
373 }
374}
375
Calin Juravlee01f8712021-06-03 18:16:54 -0700376static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
377 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, mode)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800378 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800379 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800380 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800381 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800382 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700383 }
Calin Juravle114f0812017-03-08 19:05:07 -0800384 // Profiles should belong to the app; make sure of that by giving ownership to
385 // the app uid. If we cannot do that, there's no point in returning the fd
386 // since dex2oat/profman will fail with SElinux denials.
387 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000388 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800389 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800390 }
Calin Juravle29591732017-11-20 17:46:19 -0800391 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800392}
393
Calin Juravlee01f8712021-06-03 18:16:54 -0700394static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
Calin Juravle114f0812017-03-08 19:05:07 -0800395 // Do not follow symlinks when opening a profile:
396 // - primary profiles should not contain symlinks in their paths
397 // - secondary dex paths should have been already resolved and validated
398 flags |= O_NOFOLLOW;
399
Calin Juravle29591732017-11-20 17:46:19 -0800400 // Check if we need to create the profile
401 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
402 unique_fd fd;
403 if ((flags & O_CREAT) != 0) {
Calin Juravlee01f8712021-06-03 18:16:54 -0700404 fd = create_profile(uid, profile, flags, mode);
Calin Juravle29591732017-11-20 17:46:19 -0800405 } else {
406 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
407 }
408
Calin Juravle114f0812017-03-08 19:05:07 -0800409 if (fd.get() < 0) {
410 if (errno != ENOENT) {
411 // Profiles might be missing for various reasons. For example, in a
412 // multi-user environment, the profile directory for one user can be created
413 // after we start a merge. In this case the current profile for that user
414 // will not be found.
415 // Also, the secondary dex profiles might be deleted by the app at any time,
416 // so we can't we need to prepare if they are missing.
417 PLOG(ERROR) << "Failed to open profile " << profile;
418 }
419 return invalid_unique_fd();
Calin Juravlee01f8712021-06-03 18:16:54 -0700420 } else {
421 // If we just create the file we need to set its mode because on Android
422 // open has a mask that only allows owner access.
423 if ((flags & O_CREAT) != 0) {
424 if (fchmod(fd.get(), mode) != 0) {
425 PLOG(ERROR) << "Could not set mode " << std::hex << mode << std::dec
426 << " on profile" << profile;
427 // Not a terminal failure.
428 }
429 }
Calin Juravle114f0812017-03-08 19:05:07 -0800430 }
431
Jeff Sharkey90aff262016-12-12 14:28:24 -0700432 return fd;
433}
434
Calin Juravle824a64d2018-01-18 20:23:17 -0800435static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
436 const std::string& location, bool is_secondary_dex) {
437 std::string profile = create_current_profile_path(user, package_name, location,
438 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700439 return open_profile(uid, profile, O_RDONLY, /*mode=*/ 0);
Calin Juravle114f0812017-03-08 19:05:07 -0800440}
441
Calin Juravle824a64d2018-01-18 20:23:17 -0800442static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
443 const std::string& location, bool read_write, bool is_secondary_dex) {
444 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Martin Stjernholme1dadb52023-03-01 13:56:29 +0000445 if (read_write && GetBoolProperty("dalvik.vm.useartservice", false)) {
446 // ART Service doesn't use flock and instead assumes profile files are
447 // immutable, so ensure we don't open a file for writing when it's
448 // active.
449 // TODO(b/251921228): Normally installd isn't called at all in that
450 // case, but OTA is still an exception that uses the legacy code.
451 LOG(ERROR) << "Opening ref profile " << profile
452 << " for writing is unsafe when ART Service is enabled.";
453 return invalid_unique_fd();
454 }
Calin Juravlee01f8712021-06-03 18:16:54 -0700455 return open_profile(
456 uid,
457 profile,
458 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
459 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
Calin Juravle29591732017-11-20 17:46:19 -0800460}
461
Victor Hsiehcb35a062020-08-13 16:11:13 -0700462static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
Martin Stjernholme1dadb52023-03-01 13:56:29 +0000463 const std::string& location,
464 bool is_secondary_dex) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700465 std::string profile_path = create_reference_profile_path(package_name, location,
466 is_secondary_dex);
Martin Stjernholme1dadb52023-03-01 13:56:29 +0000467 unique_fd ufd = open_profile(uid, profile_path, O_RDONLY,
468 S_IRUSR | S_IWUSR |
469 S_IRGRP); // so that ART can also read it when apps run.
Calin Juravlee01f8712021-06-03 18:16:54 -0700470
Victor Hsiehcb35a062020-08-13 16:11:13 -0700471 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
472 clear_profile(path);
473 });
474}
475
Alex Buynytskyy79dcab52021-11-19 11:43:04 -0800476static unique_fd open_snapshot_profile(uid_t uid, const std::string& package_name,
477 const std::string& location) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800478 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravlee01f8712021-06-03 18:16:54 -0700479 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
Calin Juravle114f0812017-03-08 19:05:07 -0800480}
481
Calin Juravle824a64d2018-01-18 20:23:17 -0800482static void open_profile_files(uid_t uid, const std::string& package_name,
483 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800484 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700485 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800486 *reference_profile_fd = open_reference_profile(uid, package_name, location,
487 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700488
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000489 // For secondary dex files, we don't really need the user but we use it for validity checks.
Calin Juravle114f0812017-03-08 19:05:07 -0800490 // Note: the user owning the dex file should be the current user.
491 std::vector<userid_t> users;
492 if (is_secondary_dex){
493 users.push_back(multiuser_get_user_id(uid));
494 } else {
495 users = get_known_users(/*volume_uuid*/ nullptr);
496 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700497 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800498 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
499 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700500 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800501 if (profile_fd.get() >= 0) {
502 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700503 }
504 }
505}
506
Jiakai Zhang495142a2022-02-21 19:38:14 +0000507// Cleans up an output file specified by a file descriptor. This function should be called whenever
508// a subprocess that modifies a system-managed file crashes.
509// If the subprocess crashes while it's writing to the file, the file is likely corrupted, so we
510// should remove it.
511// If the subprocess times out and is killed while it's acquiring a flock on the file, there is
512// probably a deadlock, so it's also good to remove the file so that later operations won't
513// encounter the same problem. It's safe to do so because the process that is holding the flock will
514// still have access to the file until the file descriptor is closed.
515// Note that we can't do `clear_reference_profile` here even if the fd points to a reference profile
516// because that also requires a flock and is therefore likely to be stuck in the second case.
517static bool cleanup_output_fd(int fd) {
518 std::string path;
519 bool ret = remove_file_at_fd(fd, &path);
520 if (ret) {
521 LOG(INFO) << "Removed file at path " << path;
522 }
523 return ret;
524}
525
Calin Juravle76561322019-11-14 09:08:52 -0800526static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
527static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
Calin Juravle3b758282021-06-08 08:04:52 -0700528static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
Calin Juravle76561322019-11-14 09:08:52 -0800529static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
530static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
531static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
532static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Calin Juravle3b758282021-06-08 08:04:52 -0700533static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700534
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800535class RunProfman : public ExecVHelper {
536 public:
Jiakai Zhang495142a2022-02-21 19:38:14 +0000537 template <typename T, typename U>
538 void SetupArgs(const std::vector<T>& profile_fds,
539 const unique_fd& reference_profile_fd,
540 const std::vector<U>& apk_fds,
541 const std::vector<std::string>& dex_locations,
542 bool copy_and_update,
543 bool for_snapshot,
544 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800545
546 // TODO(calin): Assume for now we run in the bg compile job (which is in
547 // most of the invocation). With the current data flow, is not very easy or
548 // clean to discover this in RunProfman (it will require quite a messy refactoring).
549 const char* profman_bin = select_execution_binary(
550 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700551
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800552 if (copy_and_update) {
553 CHECK_EQ(1u, profile_fds.size());
554 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000555 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800556 if (reference_profile_fd != -1) {
557 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000558 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800559
Jiakai Zhang495142a2022-02-21 19:38:14 +0000560 for (const T& fd : profile_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800561 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
562 }
563
Jiakai Zhang495142a2022-02-21 19:38:14 +0000564 for (const U& fd : apk_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800565 AddArg("--apk-fd=" + std::to_string(fd.get()));
566 }
567
568 for (const std::string& dex_location : dex_locations) {
569 AddArg("--dex-location=" + dex_location);
570 }
571
572 if (copy_and_update) {
573 AddArg("--copy-and-update-profile-key");
574 }
575
Calin Juravle78728f32019-11-08 17:55:46 -0800576 if (for_snapshot) {
577 AddArg("--force-merge");
578 }
579
580 if (for_boot_image) {
581 AddArg("--boot-image-merge");
582 }
583
yawannga27559e2020-11-13 19:17:44 +0000584 // The percent won't exceed 100, otherwise, don't set it and use the
585 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000586 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000587 "dalvik.vm.bgdexopt.new-classes-percent",
588 /*default*/std::numeric_limits<uint32_t>::max());
589 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000590 AddArg("--min-new-classes-percent-change=" +
591 std::to_string(min_new_classes_percent_change));
592 }
593
yawannga27559e2020-11-13 19:17:44 +0000594 // The percent won't exceed 100, otherwise, don't set it and use the
595 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000596 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000597 "dalvik.vm.bgdexopt.new-methods-percent",
598 /*default*/std::numeric_limits<uint32_t>::max());
599 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000600 AddArg("--min-new-methods-percent-change=" +
601 std::to_string(min_new_methods_percent_change));
602 }
603
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800604 // Do not add after dex2oat_flags, they should override others for debugging.
605 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800606 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700607
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800608 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
609 const unique_fd& reference_profile_fd,
610 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800611 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
612 bool for_snapshot = false,
613 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800614 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800615 reference_profile_fd,
616 apk_fds,
617 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800618 /*copy_and_update=*/ false,
619 for_snapshot,
620 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800621 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700622
Jiakai Zhang495142a2022-02-21 19:38:14 +0000623 void SetupCopyAndUpdate(const unique_fd& profile_fd,
624 const unique_fd& reference_profile_fd,
625 const unique_fd& apk_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800626 const std::string& dex_location) {
Jiakai Zhang495142a2022-02-21 19:38:14 +0000627 SetupArgs(std::vector<borrowed_fd>{profile_fd},
628 reference_profile_fd,
629 std::vector<borrowed_fd>{apk_fd},
630 {dex_location},
Calin Juravle78728f32019-11-08 17:55:46 -0800631 /*copy_and_update=*/true,
632 /*for_snapshot*/false,
633 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800634 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000635
Martin Stjernholmfd000402022-04-11 18:04:59 +0100636 void SetupDump(const std::vector<unique_fd>& profiles_fd, const unique_fd& reference_profile_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800637 const std::vector<std::string>& dex_locations,
Martin Stjernholmfd000402022-04-11 18:04:59 +0100638 const std::vector<unique_fd>& apk_fds, bool dump_classes_and_methods,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800639 const unique_fd& output_fd) {
Martin Stjernholmfd000402022-04-11 18:04:59 +0100640 if (dump_classes_and_methods) {
641 AddArg("--dump-classes-and-methods");
642 } else {
643 AddArg("--dump-only");
644 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800645 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800646 SetupArgs(profiles_fd,
647 reference_profile_fd,
648 apk_fds,
649 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800650 /*copy_and_update=*/false,
651 /*for_snapshot*/false,
652 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800653 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000654
Victor Hsiehc9821f12020-08-07 11:32:29 -0700655 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800656 void Exec() {
657 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
658 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800659};
Mathieu Chartier31636522018-11-09 23:53:07 +0000660
Calin Juravle3b758282021-06-08 08:04:52 -0700661static int analyze_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800662 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800663 std::vector<unique_fd> profiles_fd;
664 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800665 open_profile_files(uid, package_name, location, is_secondary_dex,
666 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800667 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700668 // Skip profile guided compilation because no profiles were found.
669 // Or if the reference profile info couldn't be opened.
Calin Juravle3b758282021-06-08 08:04:52 -0700670 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 }
672
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800673 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700674 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
675 const std::vector<std::string>& dex_locations = std::vector<std::string>();
676 profman_merge.SetupMerge(
677 profiles_fd,
678 reference_profile_fd,
679 apk_fds,
680 dex_locations,
681 /* for_snapshot= */ false,
682 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700683 pid_t pid = fork();
684 if (pid == 0) {
685 /* child -- drop privileges before continuing */
686 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800687 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700688 }
689 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000690 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700691 bool need_to_compile = false;
Calin Juravle3b758282021-06-08 08:04:52 -0700692 bool empty_profiles = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700693 bool should_clear_current_profiles = false;
694 bool should_clear_reference_profile = false;
695 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800696 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jiakai Zhang495142a2022-02-21 19:38:14 +0000697 cleanup_output_fd(reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700698 } else {
699 return_code = WEXITSTATUS(return_code);
700 switch (return_code) {
701 case PROFMAN_BIN_RETURN_CODE_COMPILE:
702 need_to_compile = true;
703 should_clear_current_profiles = true;
704 should_clear_reference_profile = false;
705 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700706 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 need_to_compile = false;
708 should_clear_current_profiles = false;
709 should_clear_reference_profile = false;
710 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700711 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
712 need_to_compile = false;
713 empty_profiles = true;
714 should_clear_current_profiles = false;
715 should_clear_reference_profile = false;
716 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700717 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800718 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700719 need_to_compile = false;
720 should_clear_current_profiles = true;
721 should_clear_reference_profile = true;
722 break;
723 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
724 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
725 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800726 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727 need_to_compile = false;
728 should_clear_current_profiles = false;
729 should_clear_reference_profile = false;
730 break;
Calin Juravle76561322019-11-14 09:08:52 -0800731 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
732 need_to_compile = false;
733 should_clear_current_profiles = true;
734 should_clear_reference_profile = true;
735 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700736 default:
737 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800738 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800739 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700740 need_to_compile = false;
741 should_clear_current_profiles = true;
742 should_clear_reference_profile = true;
743 break;
744 }
745 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800746
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800748 if (is_secondary_dex) {
749 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800750 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
751 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800752 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800753 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800754 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700755 }
756 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800757 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700758 }
Calin Juravle3b758282021-06-08 08:04:52 -0700759 int result = 0;
760 if (need_to_compile) {
761 result = PROFILES_ANALYSIS_OPTIMIZE;
762 } else if (empty_profiles) {
763 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
764 } else {
765 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
766 }
767 return result;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700768}
769
Calin Juravle114f0812017-03-08 19:05:07 -0800770// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle3b758282021-06-08 08:04:52 -0700771// The analysis is done for a single profile name (which corresponds to a single code path).
772//
773// Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
774// that makes it worth to recompile the package.
775// If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
776// merged into the reference profiles accessible with open_reference_profile().
777//
778// Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
779// As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
780// empty.
781int analyze_primary_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800782 const std::string& profile_name) {
783 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800784}
785
Calin Juravle408cd4a2018-01-20 23:34:18 -0800786bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
Martin Stjernholmfd000402022-04-11 18:04:59 +0100787 const std::string& code_path, bool dump_classes_and_methods) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800788 std::vector<unique_fd> profile_fds;
789 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800790 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
791 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792
Calin Juravle408cd4a2018-01-20 23:34:18 -0800793 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800794 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700795
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800796 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700797 const bool has_profiles = !profile_fds.empty();
798
799 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800800 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700801 return false;
802 }
803
Calin Juravle114f0812017-03-08 19:05:07 -0800804 unique_fd output_fd(open(out_file_name.c_str(),
805 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800807 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808 return false;
809 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800810
Jeff Sharkey90aff262016-12-12 14:28:24 -0700811 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800812 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800813 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
814 if (apk_fd == -1) {
815 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
816 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700818 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800819 apk_fds.push_back(std::move(apk_fd));
820
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800822 RunProfman profman_dump;
Martin Stjernholmfd000402022-04-11 18:04:59 +0100823 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds,
824 dump_classes_and_methods, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825 pid_t pid = fork();
826 if (pid == 0) {
827 /* child -- drop privileges before continuing */
828 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800829 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700830 }
831 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000832 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 if (!WIFEXITED(return_code)) {
Jiakai Zhang495142a2022-02-21 19:38:14 +0000834 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
835 cleanup_output_fd(output_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836 return false;
837 }
838 return true;
839}
840
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700841bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800842 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700843 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
844 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800845 package_name,
846 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700847 /*read_write*/ true,
848 /*secondary*/ false));
849 if (in_fd.get() < 0) {
850 PLOG(WARNING) << "Could not open profile " << system_profile;
851 return false;
852 }
853 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800854 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700855 return false;
856 }
857
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700858 // As a security measure we want to write the profile information with the reduced capabilities
859 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700860 pid_t pid = fork();
861 if (pid == 0) {
862 /* child -- drop privileges before continuing */
863 drop_capabilities(packageUid);
864
865 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
866 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200867 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
868 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700869 }
870 // This implies that the app owning this profile is running
871 // (and has acquired the lock).
872 //
873 // The app never acquires the lock for the reference profiles of primary apks.
874 // Only dex2oat from installd will do that. Since installd is single threaded
875 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200876 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
877 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700878 return false;
879 }
880
881 bool truncated = ftruncate(out_fd.get(), 0) == 0;
882 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200883 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
884 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700885 }
886
887 // Copy over data.
888 static constexpr size_t kBufferSize = 4 * 1024;
889 char buffer[kBufferSize];
890 while (true) {
891 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
892 if (bytes == 0) {
893 break;
894 }
895 write(out_fd.get(), buffer, bytes);
896 }
897 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200898 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
899 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700900 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700901 // Use _exit since we don't want to run the global destructors in the child.
902 // b/62597429
903 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700904 }
905 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000906 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
907 if (!WIFEXITED(return_code)) {
908 cleanup_output_fd(out_fd.get());
909 return false;
910 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700911 return return_code == 0;
912}
913
Jeff Sharkey90aff262016-12-12 14:28:24 -0700914static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
915 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
916 if (EndsWith(oat_path, ".dex")) {
917 std::string new_path = oat_path;
918 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800919 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700920 return new_path;
921 }
922
923 // An odex entry. Not that this may not be an extension, e.g., in the OTA
924 // case (where the base name will have an extension for the B artifact).
925 size_t odex_pos = oat_path.rfind(".odex");
926 if (odex_pos != std::string::npos) {
927 std::string new_path = oat_path;
928 new_path.replace(odex_pos, strlen(".odex"), new_ext);
929 CHECK_NE(new_path.find(new_ext), std::string::npos);
930 return new_path;
931 }
932
933 // Don't know how to handle this.
934 return "";
935}
936
937// Translate the given oat path to an art (app image) path. An empty string
938// denotes an error.
939static std::string create_image_filename(const std::string& oat_path) {
940 return replace_file_extension(oat_path, ".art");
941}
942
943// Translate the given oat path to a vdex path. An empty string denotes an error.
944static std::string create_vdex_filename(const std::string& oat_path) {
945 return replace_file_extension(oat_path, ".vdex");
946}
947
Jeff Sharkey90aff262016-12-12 14:28:24 -0700948static int open_output_file(const char* file_name, bool recreate, int permissions) {
949 int flags = O_RDWR | O_CREAT;
950 if (recreate) {
951 if (unlink(file_name) < 0) {
952 if (errno != ENOENT) {
953 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
954 }
955 }
956 flags |= O_EXCL;
957 }
958 return open(file_name, flags, permissions);
959}
960
Calin Juravle2289c0a2017-02-15 12:44:14 -0800961static bool set_permissions_and_ownership(
962 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
963 // Primary apks are owned by the system. Secondary dex files are owned by the app.
964 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700965 if (fchmod(fd,
966 S_IRUSR|S_IWUSR|S_IRGRP |
967 (is_public ? S_IROTH : 0)) < 0) {
968 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
969 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800970 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700971 ALOGE("installd cannot chown '%s' during dexopt\n", path);
972 return false;
973 }
974 return true;
975}
976
977static bool IsOutputDalvikCache(const char* oat_dir) {
978 // InstallerConnection.java (which invokes installd) transforms Java null arguments
979 // into '!'. Play it safe by handling it both.
980 // TODO: ensure we never get null.
981 // TODO: pass a flag instead of inferring if the output is dalvik cache.
982 return oat_dir == nullptr || oat_dir[0] == '!';
983}
984
Calin Juravled23dee72017-07-06 16:29:11 -0700985// Best-effort check whether we can fit the the path into our buffers.
986// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
987// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
988// extension to the cache path (5 bytes).
989// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
990static bool validate_dex_path_size(const std::string& dex_path) {
991 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
992 LOG(ERROR) << "dex_path too long: " << dex_path;
993 return false;
994 }
995 return true;
996}
997
Jeff Sharkey90aff262016-12-12 14:28:24 -0700998static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800999 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001000 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001001 return false;
1002 }
1003
1004 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001005 // Oat dirs for secondary dex files are already validated.
1006 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1008 return false;
1009 }
1010 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1011 return false;
1012 }
1013 } else {
1014 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1015 return false;
1016 }
1017 }
1018 return true;
1019}
1020
Calin Juravle7a570e82017-01-14 16:23:30 -08001021// (re)Creates the app image if needed.
Keun young Parkb7342262021-10-25 08:09:27 -07001022RestorableFile maybe_open_app_image(const std::string& out_oat_path, bool generate_app_image,
1023 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001024 const std::string image_path = create_image_filename(out_oat_path);
1025 if (image_path.empty()) {
1026 // Happens when the out_oat_path has an unknown extension.
Keun young Parkb7342262021-10-25 08:09:27 -07001027 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001028 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001029
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001030 // Not enabled, exit.
1031 if (!generate_app_image) {
Keun young Parkb7342262021-10-25 08:09:27 -07001032 RestorableFile::RemoveAllFiles(image_path);
1033 return RestorableFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001034 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001035 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1036 if (app_image_format.empty()) {
Keun young Parkb7342262021-10-25 08:09:27 -07001037 RestorableFile::RemoveAllFiles(image_path);
1038 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001039 }
Keun young Parkb7342262021-10-25 08:09:27 -07001040 // If the app is already running and we modify the image file, it can cause crashes
1041 // (b/27493510).
1042 RestorableFile image_file = RestorableFile::CreateWritableFile(image_path,
1043 /*permissions*/ 0600);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001044 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001045 // Could not create application image file. Go on since we can compile without it.
1046 LOG(ERROR) << "installd could not create '" << image_path
1047 << "' for image file during dexopt";
Keun young Parkb7342262021-10-25 08:09:27 -07001048 // If we have a valid image file path but cannot create tmp file, reset it.
1049 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001050 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001051 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001052 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001053 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001054 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001055
Victor Hsiehcb35a062020-08-13 16:11:13 -07001056 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -08001057}
1058
1059// Creates the dexopt swap file if necessary and return its fd.
1060// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001061unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001062 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001063 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001064 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001065 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001066 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001067 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001068 if (swap_fd.get() < 0) {
1069 // Could not create swap file. Optimistically go on and hope that we can compile
1070 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001071 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001072 } else {
1073 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001074 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001075 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1076 }
1077 }
1078 return swap_fd;
1079}
1080
1081// Opens the reference profiles if needed.
1082// 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 -07001083UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001084 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001085 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001086 // If we are not profile guided compilation, or we are compiling system server
1087 // do not bother to open the profiles; we won't be using them.
1088 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001089 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +00001090 }
1091
1092 // If this is a secondary dex path which is public do not open the profile.
1093 // We cannot compile public secondary dex paths with profiles. That's because
1094 // it will expose how the dex files are used by their owner.
1095 //
1096 // Note that the PackageManager is responsible to set the is_public flag for
1097 // primary apks and we do not check it here. In some cases, e.g. when
1098 // compiling with a public profile from the .dm file the PackageManager will
1099 // set is_public toghether with the profile guided compilation.
1100 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001101 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001102 }
Calin Juravle114f0812017-03-08 19:05:07 -08001103
1104 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001105 std::string location;
1106 if (is_secondary_dex) {
1107 location = dex_path;
1108 } else {
1109 if (profile_name == nullptr) {
1110 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001111 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001112 } else {
1113 location = profile_name;
1114 }
1115 }
Martin Stjernholme1dadb52023-03-01 13:56:29 +00001116 return open_reference_profile_as_unique_file(uid, pkgname, location, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001117}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118
Victor Hsiehcb35a062020-08-13 16:11:13 -07001119// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1120// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001121bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Keun young Parkb7342262021-10-25 08:09:27 -07001122 const char* instruction_set, bool is_public, int uid,
1123 bool is_secondary_dex, bool profile_guided,
1124 UniqueFile* in_vdex_wrapper, RestorableFile* out_vdex_wrapper) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001125 CHECK(in_vdex_wrapper != nullptr);
1126 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1128 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001129 char in_odex_path[PKG_PATH_MAX];
1130 int dexopt_action = abs(dexopt_needed);
1131 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001132
1133 // Infer the name of the output VDEX.
1134 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1135 if (out_vdex_path_str.empty()) {
1136 return false;
1137 }
1138
Keun young Parkb7342262021-10-25 08:09:27 -07001139 // Create work file first. All files will be deleted when it fails.
1140 *out_vdex_wrapper = RestorableFile::CreateWritableFile(out_vdex_path_str,
1141 /*permissions*/ 0644);
1142 if (out_vdex_wrapper->fd() < 0) {
1143 ALOGE("installd cannot open vdex '%s' during dexopt\n", out_vdex_path_str.c_str());
1144 return false;
1145 }
1146
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001147 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001148 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001149 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1150 const char* path = nullptr;
1151 if (is_odex_location) {
1152 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1153 path = in_odex_path;
1154 } else {
1155 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 }
1158 } else {
1159 path = out_oat_path;
1160 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001161 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001162 if (in_vdex_path_str.empty()) {
1163 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001166 // We can update in place when all these conditions are met:
1167 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1168 // on /system typically cannot be updated in place).
1169 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1170 // cannot be currently used by a running process.
1171 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1172 // different vdex files to operate.
1173 update_vdex_in_place =
1174 (in_vdex_path_str == out_vdex_path_str) &&
1175 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1176 !profile_guided;
1177 if (update_vdex_in_place) {
Keun young Parkb7342262021-10-25 08:09:27 -07001178 // dex2oat marks it invalid anyway. So delete it and set work file fd.
1179 unlink(in_vdex_path_str.c_str());
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001180 // Open the file read-write to be able to update it.
Keun young Parkb7342262021-10-25 08:09:27 -07001181 in_vdex_wrapper->reset(out_vdex_wrapper->fd(), in_vdex_path_str);
1182 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1183 // wrapper).
1184 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001185 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001186 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1187 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001188 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001189 }
1190
Victor Hsiehcb35a062020-08-13 16:11:13 -07001191 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001192 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001193 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1194 return false;
1195 }
1196
1197 // If we got here we successfully opened the vdex files.
1198 return true;
1199}
1200
1201// Opens the output oat file for the given apk.
Keun young Parkb7342262021-10-25 08:09:27 -07001202RestorableFile open_oat_out_file(const char* apk_path, const char* oat_dir, bool is_public, int uid,
1203 const char* instruction_set, bool is_secondary_dex) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001204 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001205 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Keun young Parkb7342262021-10-25 08:09:27 -07001206 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 }
Keun young Parkb7342262021-10-25 08:09:27 -07001208 RestorableFile oat = RestorableFile::CreateWritableFile(out_oat_path, /*permissions*/ 0644);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001209 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001210 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001211 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001212 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001214 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001215 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001216 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001217}
1218
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001219// Creates RDONLY fds for oat and vdex files, if exist.
1220// Returns false if it fails to create oat out path for the given apk path.
1221// Note that the method returns true even if the files could not be opened.
1222bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1223 const std::string& oat_dir,
1224 const std::string& instruction_set,
1225 bool is_secondary_dex,
1226 unique_fd* oat_file_fd,
1227 unique_fd* vdex_file_fd) {
1228 char oat_path[PKG_PATH_MAX];
1229 if (!create_oat_out_path(apk_path.c_str(),
1230 instruction_set.c_str(),
1231 oat_dir.c_str(),
1232 is_secondary_dex,
1233 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001234 LOG(ERROR) << "Could not create oat out path for "
1235 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001236 return false;
1237 }
1238 oat_file_fd->reset(open(oat_path, O_RDONLY));
1239 if (oat_file_fd->get() < 0) {
1240 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1241 }
1242
1243 std::string vdex_filename = create_vdex_filename(oat_path);
1244 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1245 if (vdex_file_fd->get() < 0) {
1246 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1247 }
1248
1249 return true;
1250}
1251
Calin Juravle80a21252017-01-17 14:43:25 -08001252// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001253// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1254// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1255// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001256class RunDexoptAnalyzer : public ExecVHelper {
1257 public:
1258 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001259 int vdex_fd,
1260 int oat_fd,
1261 int zip_fd,
1262 const std::string& instruction_set,
1263 const std::string& compiler_filter,
Calin Juravle3b758282021-06-08 08:04:52 -07001264 int profile_analysis_result,
David Brazdil4f6027a2019-03-19 11:44:21 +00001265 bool downgrade,
1266 const char* class_loader_context,
1267 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001268 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001269
1270 // We always run the analyzer in the background job.
1271 const char* dexoptanalyzer_bin = select_execution_binary(
1272 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001273
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001274 std::string dex_file_arg = "--dex-file=" + dex_file;
1275 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1276 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1277 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1278 std::string isa_arg = "--isa=" + instruction_set;
1279 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle3b758282021-06-08 08:04:52 -07001280 std::string profile_analysis_arg = "--profile-analysis-result="
1281 + std::to_string(profile_analysis_result);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001282 const char* downgrade_flag = "--downgrade";
1283 std::string class_loader_context_arg = "--class-loader-context=";
1284 if (class_loader_context != nullptr) {
1285 class_loader_context_arg += class_loader_context;
1286 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001287 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1288 if (!class_loader_context_fds.empty()) {
1289 class_loader_context_fds_arg += class_loader_context_fds;
1290 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001291
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001292 // program name, dex file, isa, filter
1293 AddArg(dex_file_arg);
1294 AddArg(isa_arg);
1295 AddArg(compiler_filter_arg);
1296 if (oat_fd >= 0) {
1297 AddArg(oat_fd_arg);
1298 }
1299 if (vdex_fd >= 0) {
1300 AddArg(vdex_fd_arg);
1301 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001302 AddArg(zip_fd_arg);
Calin Juravle3b758282021-06-08 08:04:52 -07001303 AddArg(profile_analysis_arg);
1304
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001305 if (downgrade) {
1306 AddArg(downgrade_flag);
1307 }
1308 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001309 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001310 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001311 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001312 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001313 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001314
Orion Hodson5f6b3ad2021-07-01 12:12:40 +01001315 // On-device signing related. odsign sets the system property odsign.verification.success if
1316 // AOT artifacts have the expected signatures.
1317 const bool trust_art_apex_data_files =
1318 ::android::base::GetBoolProperty("odsign.verification.success", false);
1319 if (!trust_art_apex_data_files) {
1320 AddRuntimeArg("-Xdeny-art-apex-data-files");
1321 }
1322
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001323 PrepareArgs(dexoptanalyzer_bin);
1324 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001325
1326 // Dexoptanalyzer mode which flattens the given class loader context and
1327 // prints a list of its dex files in that flattened order.
1328 RunDexoptAnalyzer(const char* class_loader_context) {
1329 CHECK(class_loader_context != nullptr);
1330
1331 // We always run the analyzer in the background job.
1332 const char* dexoptanalyzer_bin = select_execution_binary(
1333 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1334
1335 AddArg("--flatten-class-loader-context");
1336 AddArg(std::string("--class-loader-context=") + class_loader_context);
1337 PrepareArgs(dexoptanalyzer_bin);
1338 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001339};
Calin Juravle80a21252017-01-17 14:43:25 -08001340
1341// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001342static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001343 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001344 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001345 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001346 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001347 return false;
1348 }
Calin Juravle114f0812017-03-08 19:05:07 -08001349 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001350
Calin Juravle80a21252017-01-17 14:43:25 -08001351 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001352 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1353 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001354 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001355 return false;
1356 }
1357
1358 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001359 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001360
Calin Juravle7d765462017-09-04 15:57:10 -07001361 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001362 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001363 return false;
1364 }
1365
1366 return true;
1367}
1368
Calin Juravle7d765462017-09-04 15:57:10 -07001369// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1370// secondary dex files. This return codes are returned by the child process created for
1371// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001372
Andreas Gampe194fe422018-02-28 20:16:19 -08001373enum DexoptAnalyzerSkipCodes {
1374 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001375 // Specific errors are encoded in the name.
1376 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1377 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1378 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1379 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1380 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001381 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001382 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001383};
Calin Juravle7d765462017-09-04 15:57:10 -07001384
1385// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001386// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1387// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001388// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1389// of dexoptanalyzer.
1390static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001391 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001392 // The result values are defined in dexoptanalyzer.
1393 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001394 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001395 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001396 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001397 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001398 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001399 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001400 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001401 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001402 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1403 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001404 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1405 " Expected odex file status for secondary dex %s"
1406 " : dexoptanalyzer result=%d",
1407 dex_path.c_str(),
1408 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001409 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001410 }
1411
1412 // Use a second switch for enum switch-case analysis.
1413 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001414 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001415 // If the file does not exist there's no need for dexopt.
1416 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1417 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001418
1419 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1420 *error_msg = "Dexoptanalyzer path validation failed";
1421 return false;
1422 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1423 *error_msg = "Dexoptanalyzer open zip failed";
1424 return false;
1425 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1426 *error_msg = "Dexoptanalyzer dir preparation failed";
1427 return false;
1428 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1429 *error_msg = "Dexoptanalyzer open output failed";
1430 return false;
1431 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1432 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001433 return false;
1434 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001435
1436 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1437 dex_path.c_str(),
1438 result);
1439 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001440}
1441
Calin Juravle7d765462017-09-04 15:57:10 -07001442enum SecondaryDexAccess {
1443 kSecondaryDexAccessReadOk = 0,
1444 kSecondaryDexAccessDoesNotExist = 1,
1445 kSecondaryDexAccessPermissionError = 2,
1446 kSecondaryDexAccessIOError = 3
1447};
1448
1449static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1450 // Check if the path exists and can be read. If not, there's nothing to do.
1451 if (access(dex_path.c_str(), R_OK) == 0) {
1452 return kSecondaryDexAccessReadOk;
1453 } else {
1454 if (errno == ENOENT) {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001455 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1456 "Secondary dex does not exist: %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001457 return kSecondaryDexAccessDoesNotExist;
1458 } else {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001459 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1460 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
Calin Juravle7d765462017-09-04 15:57:10 -07001461 return errno == EACCES
1462 ? kSecondaryDexAccessPermissionError
1463 : kSecondaryDexAccessIOError;
1464 }
1465 }
1466}
1467
1468static bool is_file_public(const std::string& filename) {
1469 struct stat file_stat;
1470 if (stat(filename.c_str(), &file_stat) == 0) {
1471 return (file_stat.st_mode & S_IROTH) != 0;
1472 }
1473 return false;
1474}
1475
1476// Create the oat file structure for the secondary dex 'dex_path' and assign
1477// the individual path component to the 'out_' parameters.
1478static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001479 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001480 size_t dirIndex = dex_path.rfind('/');
1481 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001482 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001483 return false;
1484 }
1485 // TODO(calin): we have similar computations in at lest 3 other places
1486 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1487 // using string append.
1488 std::string apk_dir = dex_path.substr(0, dirIndex);
1489 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1490 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1491
1492 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1493 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001494 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001495 return false;
1496 }
1497 return true;
1498}
1499
1500// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1501// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001502static bool validate_dexopt_storage_flags(int dexopt_flags,
1503 int* out_storage_flag,
1504 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001505 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1506 *out_storage_flag = FLAG_STORAGE_CE;
1507 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001508 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001509 return false;
1510 }
1511 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1512 *out_storage_flag = FLAG_STORAGE_DE;
1513 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001514 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001515 return false;
1516 }
1517 return true;
1518}
1519
David Brazdil4f6027a2019-03-19 11:44:21 +00001520static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1521 /* out */ std::vector<std::string>* context_dex_paths) {
1522 if (class_loader_context == nullptr) {
1523 return true;
1524 }
1525
1526 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1527
1528 // Pipe to get the hash result back from our child process.
1529 unique_fd pipe_read, pipe_write;
1530 if (!Pipe(&pipe_read, &pipe_write)) {
1531 PLOG(ERROR) << "Failed to create pipe";
1532 return false;
1533 }
1534
1535 pid_t pid = fork();
1536 if (pid == 0) {
1537 // child -- drop privileges before continuing.
1538 drop_capabilities(uid);
1539
1540 // Route stdout to `pipe_write`
1541 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1542 pipe_write.reset();
1543 pipe_read.reset();
1544
1545 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1546 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1547 }
1548
1549 /* parent */
1550 pipe_write.reset();
1551
1552 std::string str_dex_paths;
1553 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1554 PLOG(ERROR) << "Failed to read from pipe";
1555 return false;
1556 }
1557 pipe_read.reset();
1558
Jiakai Zhang495142a2022-02-21 19:38:14 +00001559 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
David Brazdil4f6027a2019-03-19 11:44:21 +00001560 if (!WIFEXITED(return_code)) {
1561 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1562 return false;
1563 }
1564
1565 constexpr int kFlattenClassLoaderContextSuccess = 50;
1566 return_code = WEXITSTATUS(return_code);
1567 if (return_code != kFlattenClassLoaderContextSuccess) {
1568 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1569 return false;
1570 }
1571
1572 if (!str_dex_paths.empty()) {
1573 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1574 }
1575 return true;
1576}
1577
1578static int open_dex_paths(const std::vector<std::string>& dex_paths,
1579 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1580 for (const std::string& dex_path : dex_paths) {
1581 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1582 if (zip_fds->back().get() < 0) {
1583 *error_msg = StringPrintf(
1584 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1585 if (errno == ENOENT) {
1586 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1587 } else {
1588 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1589 }
1590 }
1591 }
1592 return 0;
1593}
1594
1595static std::string join_fds(const std::vector<unique_fd>& fds) {
1596 std::stringstream ss;
1597 bool is_first = true;
1598 for (const unique_fd& fd : fds) {
1599 if (is_first) {
1600 is_first = false;
1601 } else {
1602 ss << ":";
1603 }
1604 ss << fd.get();
1605 }
1606 return ss.str();
1607}
1608
Keun young Park65578d62021-06-28 17:52:05 -07001609void control_dexopt_blocking(bool block) {
1610 dexopt_status_->control_dexopt_blocking(block);
1611}
1612
1613bool is_dexopt_blocked() {
1614 return dexopt_status_->is_dexopt_blocked();
1615}
1616
1617enum SecondaryDexOptProcessResult {
1618 kSecondaryDexOptProcessOk = 0,
1619 kSecondaryDexOptProcessCancelled = 1,
1620 kSecondaryDexOptProcessError = 2
1621};
1622
Calin Juravlec9eab382017-01-25 01:17:17 -08001623// 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 -07001624// be compiled.
1625// Returns: kSecondaryDexOptProcessError for errors (logged).
1626// kSecondaryDexOptProcessOk if the secondary dex path was process successfully.
1627// kSecondaryDexOptProcessCancelled if the processing was cancelled.
1628//
1629// When returning kSecondaryDexOptProcessOk, the output parameters will be:
Calin Juravleebc8a792017-04-04 20:21:05 -07001630// - is_public_out: whether or not the oat file should not be made public
1631// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1632// - oat_dir_out: the oat dir path where the oat file should be stored
Keun young Park65578d62021-06-28 17:52:05 -07001633static SecondaryDexOptProcessResult process_secondary_dex_dexopt(const std::string& dex_path,
1634 const char* pkgname, int dexopt_flags, const char* volume_uuid, int uid,
1635 const char* instruction_set, const char* compiler_filter, bool* is_public_out,
1636 int* dexopt_needed_out, std::string* oat_dir_out, bool downgrade,
1637 const char* class_loader_context, const std::vector<std::string>& context_dex_paths,
1638 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001639 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Keun young Park65578d62021-06-28 17:52:05 -07001640
1641 if (dexopt_status_->is_dexopt_blocked()) {
1642 return kSecondaryDexOptProcessCancelled;
1643 }
1644
Calin Juravle80a21252017-01-17 14:43:25 -08001645 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001646 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1647 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001648 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001649 }
Calin Juravle7d765462017-09-04 15:57:10 -07001650 // Compute the oat dir as it's not easy to extract it from the child computation.
1651 char oat_path[PKG_PATH_MAX];
1652 char oat_dir[PKG_PATH_MAX];
1653 char oat_isa_dir[PKG_PATH_MAX];
1654 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001655 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1656 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001657 return kSecondaryDexOptProcessError;
Calin Juravled23dee72017-07-06 16:29:11 -07001658 }
Calin Juravle7d765462017-09-04 15:57:10 -07001659 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001660
Keun young Park65578d62021-06-28 17:52:05 -07001661 bool cancelled = false;
1662 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1663 if (cancelled) {
1664 return kSecondaryDexOptProcessCancelled;
1665 }
Calin Juravle80a21252017-01-17 14:43:25 -08001666 if (pid == 0) {
1667 // child -- drop privileges before continuing.
1668 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001669
1670 // Validate the path structure.
1671 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001672 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1673 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001674 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001675 }
1676
1677 // Open the dex file.
1678 unique_fd zip_fd;
1679 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1680 if (zip_fd.get() < 0) {
1681 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001682 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001683 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001684 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001685 }
1686 }
1687
David Brazdil4f6027a2019-03-19 11:44:21 +00001688 // Open class loader context dex files.
1689 std::vector<unique_fd> context_zip_fds;
1690 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1691 if (open_dex_paths_rc != 0) {
1692 _exit(open_dex_paths_rc);
1693 }
1694
Calin Juravle7d765462017-09-04 15:57:10 -07001695 // Prepare the oat directories.
1696 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001697 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001698 }
1699
1700 // Open the vdex/oat files if any.
1701 unique_fd oat_file_fd;
1702 unique_fd vdex_file_fd;
1703 if (!maybe_open_oat_and_vdex_file(dex_path,
1704 *oat_dir_out,
1705 instruction_set,
1706 true /* is_secondary_dex */,
1707 &oat_file_fd,
1708 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001709 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001710 }
1711
1712 // Analyze profiles.
Calin Juravle3b758282021-06-08 08:04:52 -07001713 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
Calin Juravle824a64d2018-01-18 20:23:17 -08001714 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001715
1716 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001717 // Note that we do not do it before the fork since opening the files is required to happen
1718 // after forking.
1719 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1720 vdex_file_fd.get(),
1721 oat_file_fd.get(),
1722 zip_fd.get(),
1723 instruction_set,
Calin Juravle3b758282021-06-08 08:04:52 -07001724 compiler_filter,
1725 profile_analysis_result,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001726 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001727 class_loader_context,
1728 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001729 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001730 }
1731
1732 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00001733 int result = wait_child_with_timeout(pid, kShortTimeoutMs);
Keun young Park65578d62021-06-28 17:52:05 -07001734 cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Calin Juravle80a21252017-01-17 14:43:25 -08001735 if (!WIFEXITED(result)) {
Keun young Park65578d62021-06-28 17:52:05 -07001736 if ((WTERMSIG(result) == SIGKILL) && cancelled) {
1737 LOG(INFO) << "dexoptanalyzer cancelled for path:" << dex_path;
1738 return kSecondaryDexOptProcessCancelled;
1739 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001740 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1741 dex_path.c_str(),
1742 result);
1743 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001744 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001745 }
1746 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001747 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001748 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1749 result,
1750 dexopt_needed_out,
1751 error_msg);
1752 if (!success) {
1753 LOG(ERROR) << *error_msg;
1754 }
Calin Juravle7d765462017-09-04 15:57:10 -07001755
1756 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1757
Calin Juravle80a21252017-01-17 14:43:25 -08001758 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001759 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1760 // makes the code simpler; force compilation is only needed during tests).
1761 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001762 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001763 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001764 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1765 }
1766
Calin Juravle7d765462017-09-04 15:57:10 -07001767 // Check if we should make the oat file public.
1768 // Note that if the dex file is not public the compiled code cannot be made public.
1769 // It is ok to check this flag outside in the parent process.
1770 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1771
Keun young Park65578d62021-06-28 17:52:05 -07001772 return success ? kSecondaryDexOptProcessOk : kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001773}
1774
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001775static std::string format_dexopt_error(int status, const char* dex_path) {
1776 if (WIFEXITED(status)) {
1777 int int_code = WEXITSTATUS(status);
1778 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1779 if (code_name != nullptr) {
1780 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1781 }
1782 }
1783 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001784}
1785
Keun young Park65578d62021-06-28 17:52:05 -07001786
Calin Juravlec9eab382017-01-25 01:17:17 -08001787int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001788 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001789 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001790 bool downgrade, int target_sdk_version, const char* profile_name,
Keun young Park65578d62021-06-28 17:52:05 -07001791 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg,
1792 /* out */ bool* completed) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001793 CHECK(pkgname != nullptr);
1794 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001795 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001796 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1797 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001798
Keun young Park65578d62021-06-28 17:52:05 -07001799 bool local_completed; // local placeholder for nullptr case
1800 if (completed == nullptr) {
1801 completed = &local_completed;
1802 }
1803 *completed = true;
1804 if (dexopt_status_->is_dexopt_blocked()) {
1805 *completed = false;
1806 return 0;
1807 }
1808
Calin Juravled23dee72017-07-06 16:29:11 -07001809 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001810 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001811 return -1;
1812 }
1813
1814 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001815 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1816 class_loader_context);
1817 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001818 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001819 }
1820
Calin Juravleebc8a792017-04-04 20:21:05 -07001821 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001822 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1823 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1824 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001825 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001826 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001827 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001828 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001829 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001830 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001831
1832 // Check if we're dealing with a secondary dex file and if we need to compile it.
1833 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001834 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001835 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001836 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1837 *error_msg = "Failed acquiring context dex paths";
1838 return -1; // We had an error, logged in the process method.
1839 }
Keun young Park65578d62021-06-28 17:52:05 -07001840 SecondaryDexOptProcessResult sec_dex_result = process_secondary_dex_dexopt(dex_path,
1841 pkgname, dexopt_flags, volume_uuid, uid,instruction_set, compiler_filter,
1842 &is_public, &dexopt_needed, &oat_dir_str, downgrade, class_loader_context,
1843 context_dex_paths, error_msg);
1844 if (sec_dex_result == kSecondaryDexOptProcessOk) {
Calin Juravle80a21252017-01-17 14:43:25 -08001845 oat_dir = oat_dir_str.c_str();
1846 if (dexopt_needed == NO_DEXOPT_NEEDED) {
Keun young Parkb7342262021-10-25 08:09:27 -07001847 *completed = true;
Calin Juravle80a21252017-01-17 14:43:25 -08001848 return 0; // Nothing to do, report success.
1849 }
Keun young Park65578d62021-06-28 17:52:05 -07001850 } else if (sec_dex_result == kSecondaryDexOptProcessCancelled) {
1851 // cancelled, not an error.
1852 *completed = false;
1853 return 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001854 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001855 if (error_msg->empty()) { // TODO: Make this a CHECK.
1856 *error_msg = "Failed processing secondary.";
1857 }
Calin Juravle80a21252017-01-17 14:43:25 -08001858 return -1; // We had an error, logged in the process method.
1859 }
1860 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001861 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001862 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001863 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1864 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1865 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001866
1867 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001868 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1869 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001870 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1871 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001872 return -1;
1873 }
1874
David Brazdil4f6027a2019-03-19 11:44:21 +00001875 // Open class loader context dex files.
1876 std::vector<unique_fd> context_input_fds;
1877 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1878 LOG(ERROR) << *error_msg;
1879 return -1;
1880 }
1881
Calin Juravle7a570e82017-01-14 16:23:30 -08001882 // Create the output OAT file.
Keun young Parkb7342262021-10-25 08:09:27 -07001883 RestorableFile out_oat =
1884 open_oat_out_file(dex_path, oat_dir, is_public, uid, instruction_set, is_secondary_dex);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001885 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001886 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001887 return -1;
1888 }
1889
1890 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001891 UniqueFile in_vdex;
Keun young Parkb7342262021-10-25 08:09:27 -07001892 RestorableFile out_vdex;
Victor Hsiehcb35a062020-08-13 16:11:13 -07001893 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1894 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1895 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001896 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001897 return -1;
1898 }
1899
Calin Juravlecb556e32017-04-04 20:22:50 -07001900 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1901 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1902 // fully inherit their parent context).
1903 // Note that for primary apk the oat files are created before, in a separate installd
1904 // call which also does the restorecon. TODO(calin): unify the paths.
1905 if (is_secondary_dex) {
1906 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1907 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001908 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1909 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001910 return -1;
1911 }
1912 }
1913
Jeff Sharkey90aff262016-12-12 14:28:24 -07001914 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001915 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001916
Calin Juravle7a570e82017-01-14 16:23:30 -08001917 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001918 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001919 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
yanmin5400138e2023-02-24 19:10:19 +08001920 struct stat sbuf;
1921 if (reference_profile.fd() == -1 ||
1922 (fstat(reference_profile.fd(), &sbuf) != -1 && sbuf.st_size == 0)) {
1923 // We don't create an app image with empty or non existing reference profile since there
1924 // is no speedup from loading it in that case and instead will be a small overhead.
liulvping61907742018-08-21 09:36:52 +08001925 generate_app_image = false;
1926 }
1927
1928 // Create the app image file if needed.
Keun young Parkb7342262021-10-25 08:09:27 -07001929 RestorableFile out_image = maybe_open_app_image(out_oat.path(), generate_app_image, is_public,
1930 uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001931
Victor Hsiehcb35a062020-08-13 16:11:13 -07001932 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001933 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001934 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1935 dex_metadata_path);
1936 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001937 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1938 }
1939 }
1940
Victor Hsieh8948a862020-08-07 11:30:55 -07001941 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1942 RUNTIME_NATIVE_BOOT_NAMESPACE,
1943 ENABLE_JITZYGOTE_IMAGE,
1944 /*default_value=*/ "");
1945 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1946
Victor Hsiehe98e6512020-08-10 15:39:22 -07001947 // Decide whether to use dex2oat64.
1948 bool use_dex2oat64 = false;
1949 // Check whether the device even supports 64-bit ABIs.
1950 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1951 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1952 }
1953 const char* dex2oat_bin = select_execution_binary(
1954 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1955 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1956 background_job_compile);
1957
Victor Hsiehc9821f12020-08-07 11:32:29 -07001958 auto execv_helper = std::make_unique<ExecVHelper>();
1959
Andreas Gampe023b2242018-02-28 16:03:25 -08001960 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001961
Victor Hsiehc9821f12020-08-07 11:32:29 -07001962 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Keun young Parkb7342262021-10-25 08:09:27 -07001963 runner.Initialize(out_oat.GetUniqueFile(), out_vdex.GetUniqueFile(), out_image.GetUniqueFile(),
1964 in_dex, in_vdex, dex_metadata, reference_profile, class_loader_context,
1965 join_fds(context_input_fds), swap_fd.get(), instruction_set, compiler_filter,
1966 debuggable, boot_complete, for_restore, target_sdk_version,
1967 enable_hidden_api_checks, generate_compact_dex, use_jitzygote_image,
Martin Stjernholm02570a72022-11-01 13:56:46 +00001968 background_job_compile, compilation_reason);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001969
Keun young Park65578d62021-06-28 17:52:05 -07001970 bool cancelled = false;
1971 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1972 if (cancelled) {
Keun young Parkb7342262021-10-25 08:09:27 -07001973 *completed = false;
1974 reference_profile.DisableCleanup();
Keun young Park65578d62021-06-28 17:52:05 -07001975 return 0;
1976 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001977 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001978 // Need to set schedpolicy before dropping privileges
1979 // for cgroup migration. See details at b/175178520.
1980 SetDex2OatScheduling(boot_complete);
1981
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982 /* child -- drop privileges before continuing */
1983 drop_capabilities(uid);
1984
Victor Hsiehcb35a062020-08-13 16:11:13 -07001985 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001986 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1987 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001988 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001989 }
1990
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001991 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001992 } else {
Jiakai Zhang495142a2022-02-21 19:38:14 +00001993 int res = wait_child_with_timeout(pid, kLongTimeoutMs);
Keun young Park65578d62021-06-28 17:52:05 -07001994 bool cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001995 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001996 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001997 } else {
Keun young Park65578d62021-06-28 17:52:05 -07001998 if ((WTERMSIG(res) == SIGKILL) && cancelled) {
1999 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- cancelled";
2000 // cancelled, not an error
2001 *completed = false;
Keun young Parkb7342262021-10-25 08:09:27 -07002002 reference_profile.DisableCleanup();
Keun young Park65578d62021-06-28 17:52:05 -07002003 return 0;
2004 }
Andreas Gampe023b2242018-02-28 16:03:25 -08002005 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2006 << std::hex << std::setw(4) << res << ", process failed";
2007 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002008 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002009 }
2010 }
2011
Keun young Parkb7342262021-10-25 08:09:27 -07002012 // dex2oat ran successfully, so profile is safe to keep.
Victor Hsiehcb35a062020-08-13 16:11:13 -07002013 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07002014
Keun young Parkb7342262021-10-25 08:09:27 -07002015 // We've been successful, commit work files.
2016 // If committing (=renaming tmp to regular) fails, try to restore backup files.
2017 // If restoring fails as well, as a last resort, remove all files.
2018 if (!out_oat.CreateBackupFile() || !out_vdex.CreateBackupFile() ||
2019 !out_image.CreateBackupFile()) {
2020 // Renaming failure can mean that the original file may not be accessible from installd.
2021 LOG(ERROR) << "Cannot create backup file from existing file, file in wrong state?"
2022 << ", out_oat:" << out_oat.path() << " ,out_vdex:" << out_vdex.path()
2023 << " ,out_image:" << out_image.path();
2024 out_oat.ResetAndRemoveAllFiles();
2025 out_vdex.ResetAndRemoveAllFiles();
2026 out_image.ResetAndRemoveAllFiles();
2027 return -1;
2028 }
2029 if (!out_oat.CommitWorkFile() || !out_vdex.CommitWorkFile() || !out_image.CommitWorkFile()) {
2030 LOG(ERROR) << "Cannot commit, out_oat:" << out_oat.path()
2031 << " ,out_vdex:" << out_vdex.path() << " ,out_image:" << out_image.path();
2032 if (!out_oat.RestoreBackupFile() || !out_vdex.RestoreBackupFile() ||
2033 !out_image.RestoreBackupFile()) {
2034 LOG(ERROR) << "Cannot cancel commit, out_oat:" << out_oat.path()
2035 << " ,out_vdex:" << out_vdex.path() << " ,out_image:" << out_image.path();
2036 // Restoring failed.
2037 out_oat.ResetAndRemoveAllFiles();
2038 out_vdex.ResetAndRemoveAllFiles();
2039 out_image.ResetAndRemoveAllFiles();
2040 }
2041 return -1;
2042 }
2043 // Now remove remaining backup files.
2044 out_oat.RemoveBackupFile();
2045 out_vdex.RemoveBackupFile();
2046 out_image.RemoveBackupFile();
2047
Keun young Park65578d62021-06-28 17:52:05 -07002048 *completed = true;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002049 return 0;
2050}
2051
Calin Juravlec9eab382017-01-25 01:17:17 -08002052// Try to remove the given directory. Log an error if the directory exists
2053// and is empty but could not be removed.
2054static bool rmdir_if_empty(const char* dir) {
2055 if (rmdir(dir) == 0) {
2056 return true;
2057 }
2058 if (errno == ENOENT || errno == ENOTEMPTY) {
2059 return true;
2060 }
2061 PLOG(ERROR) << "Failed to remove dir: " << dir;
2062 return false;
2063}
2064
2065// Try to unlink the given file. Log an error if the file exists and could not
2066// be unlinked.
2067static bool unlink_if_exists(const std::string& file) {
2068 if (unlink(file.c_str()) == 0) {
2069 return true;
2070 }
2071 if (errno == ENOENT) {
2072 return true;
2073
2074 }
2075 PLOG(ERROR) << "Could not unlink: " << file;
2076 return false;
2077}
2078
Calin Juravle7d765462017-09-04 15:57:10 -07002079enum ReconcileSecondaryDexResult {
2080 kReconcileSecondaryDexExists = 0,
2081 kReconcileSecondaryDexCleanedUp = 1,
2082 kReconcileSecondaryDexValidationError = 2,
2083 kReconcileSecondaryDexCleanUpError = 3,
2084 kReconcileSecondaryDexAccessIOError = 4,
2085};
Calin Juravlec9eab382017-01-25 01:17:17 -08002086
2087// Reconcile the secondary dex 'dex_path' and its generated oat files.
2088// Return true if all the parameters are valid and the secondary dex file was
2089// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2090// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2091// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2092// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2093// Return false if there were errors during processing. In this case
2094// out_secondary_dex_exists will be set to false.
2095bool reconcile_secondary_dex_file(const std::string& dex_path,
2096 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002097 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002098 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002099 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002100 if (isas.size() == 0) {
2101 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2102 return false;
2103 }
2104
Calin Juravle7d765462017-09-04 15:57:10 -07002105 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2106 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2107 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002108 return false;
2109 }
2110
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002111 // As a security measure we want to unlink art artifacts with the reduced capabilities
2112 // of the package user id. So we fork and drop capabilities in the child.
2113 pid_t pid = fork();
2114 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002115 /* child -- drop privileges before continuing */
2116 drop_capabilities(uid);
2117
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002118 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002119 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002120 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002121 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2122 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002123 _exit(kReconcileSecondaryDexValidationError);
2124 }
2125
2126 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2127 switch (access_check) {
2128 case kSecondaryDexAccessDoesNotExist:
2129 // File does not exist. Proceed with cleaning.
2130 break;
2131 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2132 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2133 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2134 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02002135 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2136 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07002137 _exit(kReconcileSecondaryDexValidationError);
2138 }
2139
2140 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002141 char oat_path[PKG_PATH_MAX];
2142 char oat_dir[PKG_PATH_MAX];
2143 char oat_isa_dir[PKG_PATH_MAX];
2144 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002145 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002146 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002147 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002148 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002149 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002150 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002151 }
Calin Juravle51314092017-05-18 15:33:05 -07002152
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002153 // Delete oat/vdex/art files.
2154 result = unlink_if_exists(oat_path) && result;
2155 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2156 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002157
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002158 // Delete profiles.
2159 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002160 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002161 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002162 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002163 result = unlink_if_exists(current_profile) && result;
2164 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002165
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002166 // We upgraded once the location of current profile for secondary dex files.
2167 // Check for any previous left-overs and remove them as well.
2168 std::string old_current_profile = dex_path + ".prof";
2169 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002170
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002171 // Try removing the directories as well, they might be empty.
2172 result = rmdir_if_empty(oat_isa_dir) && result;
2173 result = rmdir_if_empty(oat_dir) && result;
2174 }
Calin Juravle7d765462017-09-04 15:57:10 -07002175 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002176 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2177 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002178 }
2179 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002180 }
2181
Jiakai Zhang495142a2022-02-21 19:38:14 +00002182 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravle7d765462017-09-04 15:57:10 -07002183 if (!WIFEXITED(return_code)) {
2184 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2185 } else {
2186 return_code = WEXITSTATUS(return_code);
2187 }
2188
2189 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2190
2191 switch (return_code) {
2192 case kReconcileSecondaryDexCleanedUp:
2193 case kReconcileSecondaryDexValidationError:
2194 // If we couldn't validate assume the dex file does not exist.
2195 // This will purge the entry from the PM records.
2196 *out_secondary_dex_exists = false;
2197 return true;
2198 case kReconcileSecondaryDexExists:
2199 *out_secondary_dex_exists = true;
2200 return true;
2201 case kReconcileSecondaryDexAccessIOError:
2202 // We had an access IO error.
2203 // Return false so that we can try again.
2204 // The value of out_secondary_dex_exists does not matter in this case and by convention
2205 // is set to false.
2206 *out_secondary_dex_exists = false;
2207 return false;
2208 default:
2209 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2210 *out_secondary_dex_exists = false;
2211 return false;
2212 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002213}
2214
Alan Stokesa25d90c2017-10-16 10:56:00 +01002215// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2216// Returns true if all parameters are valid and the hash successfully computed and stored in
2217// out_secondary_dex_hash.
2218// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2219// the app.
2220// For any other errors (e.g. if any of the parameters are invalid) returns false.
2221bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002222 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002223 std::vector<uint8_t>* out_secondary_dex_hash) {
2224 out_secondary_dex_hash->clear();
2225
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002226 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002227
2228 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2229 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2230 << storage_flag;
2231 return false;
2232 }
2233
2234 // Pipe to get the hash result back from our child process.
2235 unique_fd pipe_read, pipe_write;
2236 if (!Pipe(&pipe_read, &pipe_write)) {
2237 PLOG(ERROR) << "Failed to create pipe";
2238 return false;
2239 }
2240
2241 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2242 // access data the app itself can access.
2243 pid_t pid = fork();
2244 if (pid == 0) {
2245 // child -- drop privileges before continuing
2246 drop_capabilities(uid);
2247 pipe_read.reset();
2248
2249 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002250 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2251 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002252 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002253 }
2254
2255 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2256 if (fd == -1) {
2257 if (errno == EACCES || errno == ENOENT) {
2258 // Not treated as an error.
2259 _exit(0);
2260 }
2261 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002262 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2263 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002264 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002265 }
2266
2267 SHA256_CTX ctx;
2268 SHA256_Init(&ctx);
2269
2270 std::vector<uint8_t> buffer(65536);
2271 while (true) {
2272 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2273 if (bytes_read == 0) {
2274 break;
2275 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002276 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2277 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002278 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002279 }
2280
2281 SHA256_Update(&ctx, buffer.data(), bytes_read);
2282 }
2283
2284 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2285 SHA256_Final(hash.data(), &ctx);
2286 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002287 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002288 }
2289
2290 _exit(0);
2291 }
2292
2293 // parent
2294 pipe_write.reset();
2295
2296 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2297 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2298 out_secondary_dex_hash->clear();
2299 }
Jiakai Zhang495142a2022-02-21 19:38:14 +00002300 return wait_child_with_timeout(pid, kShortTimeoutMs) == 0;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002301}
2302
Jeff Sharkey90aff262016-12-12 14:28:24 -07002303// Helper for move_ab, so that we can have common failure-case cleanup.
2304static bool unlink_and_rename(const char* from, const char* to) {
2305 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2306 // return a failure.
2307 struct stat s;
2308 if (stat(to, &s) == 0) {
2309 if (!S_ISREG(s.st_mode)) {
2310 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2311 return false;
2312 }
2313 if (unlink(to) != 0) {
2314 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2315 return false;
2316 }
2317 } else {
2318 // This may be a permission problem. We could investigate the error code, but we'll just
2319 // let the rename failure do the work for us.
2320 }
2321
2322 // Try to rename "to" to "from."
2323 if (rename(from, to) != 0) {
2324 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2325 return false;
2326 }
2327 return true;
2328}
2329
2330// Move/rename a B artifact (from) to an A artifact (to).
2331static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2332 // Check whether B exists.
2333 {
2334 struct stat s;
2335 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002336 // Ignore for now. The service calling this isn't smart enough to
2337 // understand lack of artifacts at the moment.
2338 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002339 return false;
2340 }
2341 if (!S_ISREG(s.st_mode)) {
2342 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2343 // Try to unlink, but swallow errors.
2344 unlink(b_path.c_str());
2345 return false;
2346 }
2347 }
2348
2349 // Rename B to A.
2350 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2351 // Delete the b_path so we don't try again (or fail earlier).
2352 if (unlink(b_path.c_str()) != 0) {
2353 PLOG(ERROR) << "Could not unlink " << b_path;
2354 }
2355
2356 return false;
2357 }
2358
2359 return true;
2360}
2361
2362bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2363 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002364 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2365 if (slot_suffix.empty()) {
2366 return false;
2367 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002368
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002369 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2370 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2371 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002372 }
2373
2374 // Validate other inputs.
2375 if (validate_apk_path(apk_path) != 0) {
2376 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2377 return false;
2378 }
2379 if (validate_apk_path(oat_dir) != 0) {
2380 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2381 return false;
2382 }
2383
2384 char a_path[PKG_PATH_MAX];
2385 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2386 return false;
2387 }
2388 const std::string a_vdex_path = create_vdex_filename(a_path);
2389 const std::string a_image_path = create_image_filename(a_path);
2390
2391 // B path = A path + slot suffix.
2392 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2393 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2394 const std::string b_image_path = StringPrintf("%s.%s",
2395 a_image_path.c_str(),
2396 slot_suffix.c_str());
2397
2398 bool success = true;
2399 if (move_ab_path(b_path, a_path)) {
2400 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2401 // Note: we can live without an app image. As such, ignore failure to move the image file.
2402 // If we decide to require the app image, or the app image being moved correctly,
2403 // then change accordingly.
2404 constexpr bool kIgnoreAppImageFailure = true;
2405
2406 if (!a_image_path.empty()) {
2407 if (!move_ab_path(b_image_path, a_image_path)) {
2408 unlink(a_image_path.c_str());
2409 if (!kIgnoreAppImageFailure) {
2410 success = false;
2411 }
2412 }
2413 }
2414 } else {
2415 // Cleanup: delete B image, ignore errors.
2416 unlink(b_image_path.c_str());
2417 success = false;
2418 }
2419 } else {
2420 // Cleanup: delete B image, ignore errors.
2421 unlink(b_vdex_path.c_str());
2422 unlink(b_image_path.c_str());
2423 success = false;
2424 }
2425 return success;
2426}
2427
Calin Juravleea214ad2021-06-11 09:17:20 -07002428int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002429 // Delete the oat/odex file.
2430 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002431 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002432 /*is_secondary_dex*/false, out_path)) {
Calin Juravleea214ad2021-06-11 09:17:20 -07002433 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2434 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002435 }
2436
2437 // In case of a permission failure report the issue. Otherwise just print a warning.
Calin Juravleea214ad2021-06-11 09:17:20 -07002438 auto unlink_and_check = [](const char* path) -> int64_t {
2439 struct stat file_stat;
2440 if (stat(path, &file_stat) != 0) {
2441 if (errno != ENOENT) {
2442 PLOG(ERROR) << "Could not stat " << path;
2443 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002444 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002445 return 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002446 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002447
2448 if (unlink(path) != 0) {
2449 if (errno != ENOENT) {
2450 PLOG(ERROR) << "Could not unlink " << path;
2451 return -1;
2452 }
2453 }
2454 return static_cast<int64_t>(file_stat.st_size);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002455 };
2456
2457 // Delete the oat/odex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002458 int64_t return_value_oat = unlink_and_check(out_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002459
2460 // Derive and delete the app image.
Calin Juravleea214ad2021-06-11 09:17:20 -07002461 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07002462
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002463 // Derive and delete the vdex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002464 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002465
Calin Juravleea214ad2021-06-11 09:17:20 -07002466 // Report result
2467 if (return_value_oat == -1
2468 || return_value_art == -1
2469 || return_value_vdex == -1) {
2470 return -1;
2471 }
2472
2473 return return_value_oat + return_value_art + return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002474}
2475
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002476static bool is_absolute_path(const std::string& path) {
2477 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2478 LOG(ERROR) << "Invalid absolute path " << path;
2479 return false;
2480 } else {
2481 return true;
2482 }
2483}
2484
2485static bool is_valid_instruction_set(const std::string& instruction_set) {
2486 // TODO: add explicit whitelisting of instruction sets
2487 if (instruction_set.find('/') != std::string::npos) {
2488 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2489 return false;
2490 } else {
2491 return true;
2492 }
2493}
2494
2495bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2496 const char *apk_path, const char *instruction_set) {
2497 std::string oat_dir_ = oat_dir;
2498 std::string apk_path_ = apk_path;
2499 std::string instruction_set_ = instruction_set;
2500
2501 if (!is_absolute_path(oat_dir_)) return false;
2502 if (!is_absolute_path(apk_path_)) return false;
2503 if (!is_valid_instruction_set(instruction_set_)) return false;
2504
2505 std::string::size_type end = apk_path_.rfind('.');
2506 std::string::size_type start = apk_path_.rfind('/', end);
2507 if (end == std::string::npos || start == std::string::npos) {
2508 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2509 return false;
2510 }
2511
2512 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2513 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2514 const char* res = res_.c_str();
2515 if (strlen(res) >= PKG_PATH_MAX) {
2516 LOG(ERROR) << "Result too large";
2517 return false;
2518 } else {
2519 strlcpy(path, res, PKG_PATH_MAX);
2520 return true;
2521 }
2522}
2523
2524bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2525 const char *instruction_set) {
2526 std::string apk_path_ = apk_path;
2527 std::string instruction_set_ = instruction_set;
2528
2529 if (!is_absolute_path(apk_path_)) return false;
2530 if (!is_valid_instruction_set(instruction_set_)) return false;
2531
2532 std::string::size_type end = apk_path_.rfind('.');
2533 std::string::size_type start = apk_path_.rfind('/', end);
2534 if (end == std::string::npos || start == std::string::npos) {
2535 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2536 return false;
2537 }
2538
2539 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2540 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2541}
2542
2543bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2544 const char *instruction_set) {
2545 std::string src_ = src;
2546 std::string instruction_set_ = instruction_set;
2547
2548 if (!is_absolute_path(src_)) return false;
2549 if (!is_valid_instruction_set(instruction_set_)) return false;
2550
2551 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2552 if (*it == '/') {
2553 *it = '@';
2554 }
2555 }
2556
2557 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2558 + DALVIK_CACHE_POSTFIX;
2559 const char* res = res_.c_str();
2560 if (strlen(res) >= PKG_PATH_MAX) {
2561 LOG(ERROR) << "Result too large";
2562 return false;
2563 } else {
2564 strlcpy(path, res, PKG_PATH_MAX);
2565 return true;
2566 }
2567}
2568
Calin Juravle59f7ab82018-04-27 17:50:23 -07002569bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2570 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002571 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2572 for (const std::string& elem : classpaths_elems) {
2573 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2574 if (fd < 0) {
2575 PLOG(ERROR) << "Could not open classpath elem " << elem;
2576 return false;
2577 } else {
2578 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002579 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002580 }
2581 }
2582 return true;
2583}
2584
2585static bool create_app_profile_snapshot(int32_t app_id,
2586 const std::string& package_name,
2587 const std::string& profile_name,
2588 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002589 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2590
Alex Buynytskyy79dcab52021-11-19 11:43:04 -08002591 unique_fd snapshot_fd = open_snapshot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002592 if (snapshot_fd < 0) {
2593 return false;
2594 }
2595
2596 std::vector<unique_fd> profiles_fd;
2597 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002598 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2599 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002600 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2601 return false;
2602 }
2603
2604 profiles_fd.push_back(std::move(reference_profile_fd));
2605
Calin Juravle0d0a4922018-01-23 19:54:11 -08002606 // Open the class paths elements. These will be used to filter out profile data that does
2607 // not belong to the classpath during merge.
2608 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002609 std::vector<std::string> dex_locations;
2610 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002611 return false;
2612 }
2613
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002614 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002615 // This is specifically a snapshot for an app, so don't use boot image profiles.
2616 args.SetupMerge(profiles_fd,
2617 snapshot_fd,
2618 apk_fds,
2619 dex_locations,
2620 /* for_snapshot= */ true,
2621 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002622 pid_t pid = fork();
2623 if (pid == 0) {
2624 /* child -- drop privileges before continuing */
2625 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002626 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002627 }
2628
2629 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002630 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravle29591732017-11-20 17:46:19 -08002631 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002632 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002633 cleanup_output_fd(snapshot_fd.get());
Calin Juravle29591732017-11-20 17:46:19 -08002634 return false;
2635 }
2636
Calin Juravle78728f32019-11-08 17:55:46 -08002637 // Verify that profman finished successfully.
2638 int profman_code = WEXITSTATUS(return_code);
2639 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2640 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2641 << ":" << profman_code;
2642 return false;
2643 }
Calin Juravle29591732017-11-20 17:46:19 -08002644 return true;
2645}
2646
Calin Juravle0d0a4922018-01-23 19:54:11 -08002647static bool create_boot_image_profile_snapshot(const std::string& package_name,
2648 const std::string& profile_name,
2649 const std::string& classpath) {
2650 // The reference profile directory for the android package might not be prepared. Do it now.
2651 const std::string ref_profile_dir =
2652 create_primary_reference_profile_package_dir_path(package_name);
2653 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2654 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2655 return false;
2656 }
2657
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002658 // Return false for empty class path since it may otherwise return true below if profiles is
2659 // empty.
2660 if (classpath.empty()) {
2661 PLOG(ERROR) << "Class path is empty";
2662 return false;
2663 }
2664
Calin Juravle0d0a4922018-01-23 19:54:11 -08002665 // Open and create the snapshot profile.
Alex Buynytskyy79dcab52021-11-19 11:43:04 -08002666 unique_fd snapshot_fd = open_snapshot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002667
2668 // Collect all non empty profiles.
2669 // The collection will traverse all applications profiles and find the non empty files.
2670 // This has the potential of inspecting a large number of files and directories (depending
2671 // on the number of applications and users). So there is a slight increase in the chance
2672 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2673 // fail the snapshot and aggregate whatever profile we could open.
2674 //
2675 // The profile snapshot is a best effort based on available data it's ok if some data
2676 // from some apps is missing. It will be counter productive for the snapshot to fail
2677 // because we could not open or read some of the files.
2678 std::vector<std::string> profiles;
2679 if (!collect_profiles(&profiles)) {
2680 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2681 }
2682
2683 // If we have no profiles return early.
2684 if (profiles.empty()) {
2685 return true;
2686 }
2687
2688 // Open the classpath elements. These will be used to filter out profile data that does
2689 // not belong to the classpath during merge.
2690 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002691 std::vector<std::string> dex_locations;
2692 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002693 return false;
2694 }
2695
2696 // If we could not open any files from the classpath return an error.
2697 if (apk_fds.empty()) {
2698 LOG(ERROR) << "Could not open any of the classpath elements.";
2699 return false;
2700 }
2701
2702 // Aggregate the profiles in batches of kAggregationBatchSize.
2703 // We do this to avoid opening a huge a amount of files.
2704 static constexpr size_t kAggregationBatchSize = 10;
2705
Calin Juravle0d0a4922018-01-23 19:54:11 -08002706 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002707 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002708 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
Calin Juravlee01f8712021-06-03 18:16:54 -07002709 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002710 if (fd.get() >= 0) {
2711 profiles_fd.push_back(std::move(fd));
2712 }
2713 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002714
2715 // We aggregate (read & write) into the same fd multiple times in a row.
2716 // We need to reset the cursor every time to ensure we read the whole file every time.
2717 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2718 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2719 return false;
2720 }
2721
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002722 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002723 args.SetupMerge(profiles_fd,
2724 snapshot_fd,
2725 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002726 dex_locations,
2727 /*for_snapshot=*/true,
2728 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002729 pid_t pid = fork();
2730 if (pid == 0) {
2731 /* child -- drop privileges before continuing */
2732 drop_capabilities(AID_SYSTEM);
2733
Calin Juravle59f7ab82018-04-27 17:50:23 -07002734 // The introduction of new access flags into boot jars causes them to
2735 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002736 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002737 }
2738
2739 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002740 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravlea64fb512019-11-06 16:11:14 -08002741
Calin Juravle0d0a4922018-01-23 19:54:11 -08002742 if (!WIFEXITED(return_code)) {
2743 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002744 cleanup_output_fd(snapshot_fd.get());
Calin Juravle0d0a4922018-01-23 19:54:11 -08002745 return false;
2746 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002747
2748 // Verify that profman finished successfully.
2749 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002750 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2751 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2752 << ":" << profman_code;
2753 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002754 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002755 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002756
Calin Juravle0d0a4922018-01-23 19:54:11 -08002757 return true;
2758}
2759
2760bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2761 const std::string& profile_name, const std::string& classpath) {
2762 if (app_id == -1) {
2763 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2764 } else {
2765 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2766 }
2767}
2768
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002769static bool check_profile_exists_in_dexmetadata(const std::string& dex_metadata) {
2770 ZipArchiveHandle zip = nullptr;
2771 if (OpenArchive(dex_metadata.c_str(), &zip) != 0) {
2772 PLOG(ERROR) << "Failed to open dm '" << dex_metadata << "'";
2773 return false;
2774 }
2775
2776 ZipEntry64 entry;
2777 int result = FindEntry(zip, "primary.prof", &entry);
2778 CloseArchive(zip);
2779
2780 return result != 0 ? false : true;
2781}
2782
Calin Juravlec3b049e2018-01-18 22:32:58 -08002783bool prepare_app_profile(const std::string& package_name,
2784 userid_t user_id,
2785 appid_t app_id,
2786 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002787 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002788 const std::optional<std::string>& dex_metadata) {
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002789 if (user_id != USER_NULL) {
2790 if (user_id < 0) {
2791 LOG(ERROR) << "Unexpected user ID " << user_id;
2792 return false;
2793 }
2794
2795 // Prepare the current profile.
2796 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2797 /*is_secondary_dex*/ false);
2798 uid_t uid = multiuser_get_uid(user_id, app_id);
2799 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2800 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2801 return false;
2802 }
2803 } else {
2804 // Prepare the reference profile as the system user.
2805 user_id = USER_SYSTEM;
Calin Juravlec3b049e2018-01-18 22:32:58 -08002806 }
2807
2808 // Check if we need to install the profile from the dex metadata.
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002809 if (!dex_metadata || !check_profile_exists_in_dexmetadata(dex_metadata->c_str())) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002810 return true;
2811 }
2812
2813 // We have a dex metdata. Merge the profile into the reference profile.
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002814 unique_fd ref_profile_fd =
2815 open_reference_profile(multiuser_get_uid(user_id, app_id), package_name, profile_name,
2816 /*read_write*/ true, /*is_secondary_dex*/ false);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002817 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2818 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002819 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2820 if (apk_fd < 0) {
2821 PLOG(ERROR) << "Could not open code path " << code_path;
2822 return false;
2823 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002824
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002825 RunProfman args;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002826 args.SetupCopyAndUpdate(dex_metadata_fd,
2827 ref_profile_fd,
2828 apk_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002829 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002830 pid_t pid = fork();
2831 if (pid == 0) {
2832 /* child -- drop privileges before continuing */
2833 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2834 drop_capabilities(app_shared_gid);
2835
Calin Juravlef63d4792018-01-30 17:43:34 +00002836 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002837 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002838 }
2839
2840 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002841 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002842 if (!WIFEXITED(return_code)) {
2843 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002844 cleanup_output_fd(ref_profile_fd.get());
Calin Juravlec3b049e2018-01-18 22:32:58 -08002845 return false;
2846 }
2847 return true;
2848}
2849
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002850int get_odex_visibility(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2851 char oat_path[PKG_PATH_MAX];
2852 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, /*is_secondary_dex=*/false,
2853 oat_path)) {
2854 return -1;
2855 }
2856 struct stat st;
2857 if (stat(oat_path, &st) == -1) {
2858 if (errno == ENOENT) {
2859 return ODEX_NOT_FOUND;
2860 }
2861 PLOG(ERROR) << "Could not stat " << oat_path;
2862 return -1;
2863 }
2864 return (st.st_mode & S_IROTH) ? ODEX_IS_PUBLIC : ODEX_IS_PRIVATE;
2865}
2866
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002867} // namespace installd
2868} // namespace android