blob: 894c7d34bde1d0b76876008ce9f54b5faa4b9ac9 [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);
Calin Juravlee01f8712021-06-03 18:16:54 -0700445 return open_profile(
446 uid,
447 profile,
448 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
449 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
Calin Juravle29591732017-11-20 17:46:19 -0800450}
451
Victor Hsiehcb35a062020-08-13 16:11:13 -0700452static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
453 const std::string& location, bool read_write, bool is_secondary_dex) {
454 std::string profile_path = create_reference_profile_path(package_name, location,
455 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700456 unique_fd ufd = open_profile(
457 uid,
458 profile_path,
459 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
460 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
461
Victor Hsiehcb35a062020-08-13 16:11:13 -0700462 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
463 clear_profile(path);
464 });
465}
466
Alex Buynytskyy79dcab52021-11-19 11:43:04 -0800467static unique_fd open_snapshot_profile(uid_t uid, const std::string& package_name,
468 const std::string& location) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800469 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravlee01f8712021-06-03 18:16:54 -0700470 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
Calin Juravle114f0812017-03-08 19:05:07 -0800471}
472
Calin Juravle824a64d2018-01-18 20:23:17 -0800473static void open_profile_files(uid_t uid, const std::string& package_name,
474 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800475 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700476 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800477 *reference_profile_fd = open_reference_profile(uid, package_name, location,
478 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700479
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000480 // 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 -0800481 // Note: the user owning the dex file should be the current user.
482 std::vector<userid_t> users;
483 if (is_secondary_dex){
484 users.push_back(multiuser_get_user_id(uid));
485 } else {
486 users = get_known_users(/*volume_uuid*/ nullptr);
487 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700488 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800489 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
490 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700491 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800492 if (profile_fd.get() >= 0) {
493 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700494 }
495 }
496}
497
Jiakai Zhang495142a2022-02-21 19:38:14 +0000498// Cleans up an output file specified by a file descriptor. This function should be called whenever
499// a subprocess that modifies a system-managed file crashes.
500// If the subprocess crashes while it's writing to the file, the file is likely corrupted, so we
501// should remove it.
502// If the subprocess times out and is killed while it's acquiring a flock on the file, there is
503// probably a deadlock, so it's also good to remove the file so that later operations won't
504// encounter the same problem. It's safe to do so because the process that is holding the flock will
505// still have access to the file until the file descriptor is closed.
506// Note that we can't do `clear_reference_profile` here even if the fd points to a reference profile
507// because that also requires a flock and is therefore likely to be stuck in the second case.
508static bool cleanup_output_fd(int fd) {
509 std::string path;
510 bool ret = remove_file_at_fd(fd, &path);
511 if (ret) {
512 LOG(INFO) << "Removed file at path " << path;
513 }
514 return ret;
515}
516
Calin Juravle76561322019-11-14 09:08:52 -0800517static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
518static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
Calin Juravle3b758282021-06-08 08:04:52 -0700519static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
Calin Juravle76561322019-11-14 09:08:52 -0800520static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
521static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
522static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
523static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Calin Juravle3b758282021-06-08 08:04:52 -0700524static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800526class RunProfman : public ExecVHelper {
527 public:
Jiakai Zhang495142a2022-02-21 19:38:14 +0000528 template <typename T, typename U>
529 void SetupArgs(const std::vector<T>& profile_fds,
530 const unique_fd& reference_profile_fd,
531 const std::vector<U>& apk_fds,
532 const std::vector<std::string>& dex_locations,
533 bool copy_and_update,
534 bool for_snapshot,
535 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800536
537 // TODO(calin): Assume for now we run in the bg compile job (which is in
538 // most of the invocation). With the current data flow, is not very easy or
539 // clean to discover this in RunProfman (it will require quite a messy refactoring).
540 const char* profman_bin = select_execution_binary(
541 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700542
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800543 if (copy_and_update) {
544 CHECK_EQ(1u, profile_fds.size());
545 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000546 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800547 if (reference_profile_fd != -1) {
548 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000549 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800550
Jiakai Zhang495142a2022-02-21 19:38:14 +0000551 for (const T& fd : profile_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800552 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
553 }
554
Jiakai Zhang495142a2022-02-21 19:38:14 +0000555 for (const U& fd : apk_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800556 AddArg("--apk-fd=" + std::to_string(fd.get()));
557 }
558
559 for (const std::string& dex_location : dex_locations) {
560 AddArg("--dex-location=" + dex_location);
561 }
562
563 if (copy_and_update) {
564 AddArg("--copy-and-update-profile-key");
565 }
566
Calin Juravle78728f32019-11-08 17:55:46 -0800567 if (for_snapshot) {
568 AddArg("--force-merge");
569 }
570
571 if (for_boot_image) {
572 AddArg("--boot-image-merge");
573 }
574
yawannga27559e2020-11-13 19:17:44 +0000575 // The percent won't exceed 100, otherwise, don't set it and use the
576 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000577 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000578 "dalvik.vm.bgdexopt.new-classes-percent",
579 /*default*/std::numeric_limits<uint32_t>::max());
580 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000581 AddArg("--min-new-classes-percent-change=" +
582 std::to_string(min_new_classes_percent_change));
583 }
584
yawannga27559e2020-11-13 19:17:44 +0000585 // The percent won't exceed 100, otherwise, don't set it and use the
586 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000587 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000588 "dalvik.vm.bgdexopt.new-methods-percent",
589 /*default*/std::numeric_limits<uint32_t>::max());
590 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000591 AddArg("--min-new-methods-percent-change=" +
592 std::to_string(min_new_methods_percent_change));
593 }
594
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800595 // Do not add after dex2oat_flags, they should override others for debugging.
596 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800597 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800599 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
600 const unique_fd& reference_profile_fd,
601 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800602 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
603 bool for_snapshot = false,
604 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800605 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800606 reference_profile_fd,
607 apk_fds,
608 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800609 /*copy_and_update=*/ false,
610 for_snapshot,
611 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800612 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700613
Jiakai Zhang495142a2022-02-21 19:38:14 +0000614 void SetupCopyAndUpdate(const unique_fd& profile_fd,
615 const unique_fd& reference_profile_fd,
616 const unique_fd& apk_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800617 const std::string& dex_location) {
Jiakai Zhang495142a2022-02-21 19:38:14 +0000618 SetupArgs(std::vector<borrowed_fd>{profile_fd},
619 reference_profile_fd,
620 std::vector<borrowed_fd>{apk_fd},
621 {dex_location},
Calin Juravle78728f32019-11-08 17:55:46 -0800622 /*copy_and_update=*/true,
623 /*for_snapshot*/false,
624 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800625 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000626
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800627 void SetupDump(const std::vector<unique_fd>& profiles_fd,
628 const unique_fd& reference_profile_fd,
629 const std::vector<std::string>& dex_locations,
630 const std::vector<unique_fd>& apk_fds,
631 const unique_fd& output_fd) {
632 AddArg("--dump-only");
633 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800634 SetupArgs(profiles_fd,
635 reference_profile_fd,
636 apk_fds,
637 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800638 /*copy_and_update=*/false,
639 /*for_snapshot*/false,
640 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800641 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000642
Victor Hsiehc9821f12020-08-07 11:32:29 -0700643 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800644 void Exec() {
645 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
646 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800647};
Mathieu Chartier31636522018-11-09 23:53:07 +0000648
Calin Juravle3b758282021-06-08 08:04:52 -0700649static int analyze_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800650 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800651 std::vector<unique_fd> profiles_fd;
652 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800653 open_profile_files(uid, package_name, location, is_secondary_dex,
654 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800655 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 // Skip profile guided compilation because no profiles were found.
657 // Or if the reference profile info couldn't be opened.
Calin Juravle3b758282021-06-08 08:04:52 -0700658 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700659 }
660
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800661 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700662 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
663 const std::vector<std::string>& dex_locations = std::vector<std::string>();
664 profman_merge.SetupMerge(
665 profiles_fd,
666 reference_profile_fd,
667 apk_fds,
668 dex_locations,
669 /* for_snapshot= */ false,
670 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 pid_t pid = fork();
672 if (pid == 0) {
673 /* child -- drop privileges before continuing */
674 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800675 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700676 }
677 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000678 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700679 bool need_to_compile = false;
Calin Juravle3b758282021-06-08 08:04:52 -0700680 bool empty_profiles = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700681 bool should_clear_current_profiles = false;
682 bool should_clear_reference_profile = false;
683 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800684 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jiakai Zhang495142a2022-02-21 19:38:14 +0000685 cleanup_output_fd(reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700686 } else {
687 return_code = WEXITSTATUS(return_code);
688 switch (return_code) {
689 case PROFMAN_BIN_RETURN_CODE_COMPILE:
690 need_to_compile = true;
691 should_clear_current_profiles = true;
692 should_clear_reference_profile = false;
693 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700694 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
Jeff Sharkey90aff262016-12-12 14:28:24 -0700695 need_to_compile = false;
696 should_clear_current_profiles = false;
697 should_clear_reference_profile = false;
698 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700699 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
700 need_to_compile = false;
701 empty_profiles = true;
702 should_clear_current_profiles = false;
703 should_clear_reference_profile = false;
704 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800706 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 need_to_compile = false;
708 should_clear_current_profiles = true;
709 should_clear_reference_profile = true;
710 break;
711 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
712 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
713 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800714 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700715 need_to_compile = false;
716 should_clear_current_profiles = false;
717 should_clear_reference_profile = false;
718 break;
Calin Juravle76561322019-11-14 09:08:52 -0800719 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
720 need_to_compile = false;
721 should_clear_current_profiles = true;
722 should_clear_reference_profile = true;
723 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700724 default:
725 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800726 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800727 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700728 need_to_compile = false;
729 should_clear_current_profiles = true;
730 should_clear_reference_profile = true;
731 break;
732 }
733 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800734
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800736 if (is_secondary_dex) {
737 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800738 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
739 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800740 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800741 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800742 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700743 }
744 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800745 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700746 }
Calin Juravle3b758282021-06-08 08:04:52 -0700747 int result = 0;
748 if (need_to_compile) {
749 result = PROFILES_ANALYSIS_OPTIMIZE;
750 } else if (empty_profiles) {
751 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
752 } else {
753 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
754 }
755 return result;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756}
757
Calin Juravle114f0812017-03-08 19:05:07 -0800758// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle3b758282021-06-08 08:04:52 -0700759// The analysis is done for a single profile name (which corresponds to a single code path).
760//
761// Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
762// that makes it worth to recompile the package.
763// If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
764// merged into the reference profiles accessible with open_reference_profile().
765//
766// Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
767// As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
768// empty.
769int analyze_primary_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800770 const std::string& profile_name) {
771 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800772}
773
Calin Juravle408cd4a2018-01-20 23:34:18 -0800774bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
775 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800776 std::vector<unique_fd> profile_fds;
777 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800778 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
779 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700780
Calin Juravle408cd4a2018-01-20 23:34:18 -0800781 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800782 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800784 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700785 const bool has_profiles = !profile_fds.empty();
786
787 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800788 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789 return false;
790 }
791
Calin Juravle114f0812017-03-08 19:05:07 -0800792 unique_fd output_fd(open(out_file_name.c_str(),
793 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700794 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800795 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700796 return false;
797 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800798
Jeff Sharkey90aff262016-12-12 14:28:24 -0700799 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800800 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800801 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
802 if (apk_fd == -1) {
803 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
804 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700805 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700806 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800807 apk_fds.push_back(std::move(apk_fd));
808
Jeff Sharkey90aff262016-12-12 14:28:24 -0700809
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800810 RunProfman profman_dump;
811 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700812 pid_t pid = fork();
813 if (pid == 0) {
814 /* child -- drop privileges before continuing */
815 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800816 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 }
818 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000819 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700820 if (!WIFEXITED(return_code)) {
Jiakai Zhang495142a2022-02-21 19:38:14 +0000821 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
822 cleanup_output_fd(output_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700823 return false;
824 }
825 return true;
826}
827
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700828bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800829 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700830 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
831 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800832 package_name,
833 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700834 /*read_write*/ true,
835 /*secondary*/ false));
836 if (in_fd.get() < 0) {
837 PLOG(WARNING) << "Could not open profile " << system_profile;
838 return false;
839 }
840 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800841 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700842 return false;
843 }
844
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700845 // As a security measure we want to write the profile information with the reduced capabilities
846 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700847 pid_t pid = fork();
848 if (pid == 0) {
849 /* child -- drop privileges before continuing */
850 drop_capabilities(packageUid);
851
852 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
853 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200854 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
855 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700856 }
857 // This implies that the app owning this profile is running
858 // (and has acquired the lock).
859 //
860 // The app never acquires the lock for the reference profiles of primary apks.
861 // Only dex2oat from installd will do that. Since installd is single threaded
862 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200863 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
864 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700865 return false;
866 }
867
868 bool truncated = ftruncate(out_fd.get(), 0) == 0;
869 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200870 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
871 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700872 }
873
874 // Copy over data.
875 static constexpr size_t kBufferSize = 4 * 1024;
876 char buffer[kBufferSize];
877 while (true) {
878 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
879 if (bytes == 0) {
880 break;
881 }
882 write(out_fd.get(), buffer, bytes);
883 }
884 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200885 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
886 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700887 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700888 // Use _exit since we don't want to run the global destructors in the child.
889 // b/62597429
890 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700891 }
892 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +0000893 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
894 if (!WIFEXITED(return_code)) {
895 cleanup_output_fd(out_fd.get());
896 return false;
897 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700898 return return_code == 0;
899}
900
Jeff Sharkey90aff262016-12-12 14:28:24 -0700901static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
902 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
903 if (EndsWith(oat_path, ".dex")) {
904 std::string new_path = oat_path;
905 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800906 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700907 return new_path;
908 }
909
910 // An odex entry. Not that this may not be an extension, e.g., in the OTA
911 // case (where the base name will have an extension for the B artifact).
912 size_t odex_pos = oat_path.rfind(".odex");
913 if (odex_pos != std::string::npos) {
914 std::string new_path = oat_path;
915 new_path.replace(odex_pos, strlen(".odex"), new_ext);
916 CHECK_NE(new_path.find(new_ext), std::string::npos);
917 return new_path;
918 }
919
920 // Don't know how to handle this.
921 return "";
922}
923
924// Translate the given oat path to an art (app image) path. An empty string
925// denotes an error.
926static std::string create_image_filename(const std::string& oat_path) {
927 return replace_file_extension(oat_path, ".art");
928}
929
930// Translate the given oat path to a vdex path. An empty string denotes an error.
931static std::string create_vdex_filename(const std::string& oat_path) {
932 return replace_file_extension(oat_path, ".vdex");
933}
934
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935static int open_output_file(const char* file_name, bool recreate, int permissions) {
936 int flags = O_RDWR | O_CREAT;
937 if (recreate) {
938 if (unlink(file_name) < 0) {
939 if (errno != ENOENT) {
940 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
941 }
942 }
943 flags |= O_EXCL;
944 }
945 return open(file_name, flags, permissions);
946}
947
Calin Juravle2289c0a2017-02-15 12:44:14 -0800948static bool set_permissions_and_ownership(
949 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
950 // Primary apks are owned by the system. Secondary dex files are owned by the app.
951 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700952 if (fchmod(fd,
953 S_IRUSR|S_IWUSR|S_IRGRP |
954 (is_public ? S_IROTH : 0)) < 0) {
955 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
956 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800957 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700958 ALOGE("installd cannot chown '%s' during dexopt\n", path);
959 return false;
960 }
961 return true;
962}
963
964static bool IsOutputDalvikCache(const char* oat_dir) {
965 // InstallerConnection.java (which invokes installd) transforms Java null arguments
966 // into '!'. Play it safe by handling it both.
967 // TODO: ensure we never get null.
968 // TODO: pass a flag instead of inferring if the output is dalvik cache.
969 return oat_dir == nullptr || oat_dir[0] == '!';
970}
971
Calin Juravled23dee72017-07-06 16:29:11 -0700972// Best-effort check whether we can fit the the path into our buffers.
973// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
974// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
975// extension to the cache path (5 bytes).
976// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
977static bool validate_dex_path_size(const std::string& dex_path) {
978 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
979 LOG(ERROR) << "dex_path too long: " << dex_path;
980 return false;
981 }
982 return true;
983}
984
Jeff Sharkey90aff262016-12-12 14:28:24 -0700985static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800986 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700987 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988 return false;
989 }
990
991 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800992 // Oat dirs for secondary dex files are already validated.
993 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700994 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
995 return false;
996 }
997 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
998 return false;
999 }
1000 } else {
1001 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1002 return false;
1003 }
1004 }
1005 return true;
1006}
1007
Calin Juravle7a570e82017-01-14 16:23:30 -08001008// (re)Creates the app image if needed.
Keun young Parkb7342262021-10-25 08:09:27 -07001009RestorableFile maybe_open_app_image(const std::string& out_oat_path, bool generate_app_image,
1010 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001011 const std::string image_path = create_image_filename(out_oat_path);
1012 if (image_path.empty()) {
1013 // Happens when the out_oat_path has an unknown extension.
Keun young Parkb7342262021-10-25 08:09:27 -07001014 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001015 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001016
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001017 // Not enabled, exit.
1018 if (!generate_app_image) {
Keun young Parkb7342262021-10-25 08:09:27 -07001019 RestorableFile::RemoveAllFiles(image_path);
1020 return RestorableFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001021 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001022 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1023 if (app_image_format.empty()) {
Keun young Parkb7342262021-10-25 08:09:27 -07001024 RestorableFile::RemoveAllFiles(image_path);
1025 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001026 }
Keun young Parkb7342262021-10-25 08:09:27 -07001027 // If the app is already running and we modify the image file, it can cause crashes
1028 // (b/27493510).
1029 RestorableFile image_file = RestorableFile::CreateWritableFile(image_path,
1030 /*permissions*/ 0600);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001031 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001032 // Could not create application image file. Go on since we can compile without it.
1033 LOG(ERROR) << "installd could not create '" << image_path
1034 << "' for image file during dexopt";
Keun young Parkb7342262021-10-25 08:09:27 -07001035 // If we have a valid image file path but cannot create tmp file, reset it.
1036 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001037 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001038 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001039 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001040 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001041 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001042
Victor Hsiehcb35a062020-08-13 16:11:13 -07001043 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -08001044}
1045
1046// Creates the dexopt swap file if necessary and return its fd.
1047// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001048unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001049 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001050 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001051 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001052 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001053 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001054 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001055 if (swap_fd.get() < 0) {
1056 // Could not create swap file. Optimistically go on and hope that we can compile
1057 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001058 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001059 } else {
1060 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001061 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001062 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1063 }
1064 }
1065 return swap_fd;
1066}
1067
1068// Opens the reference profiles if needed.
1069// 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 -07001070UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001071 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001072 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001073 // If we are not profile guided compilation, or we are compiling system server
1074 // do not bother to open the profiles; we won't be using them.
1075 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001076 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +00001077 }
1078
1079 // If this is a secondary dex path which is public do not open the profile.
1080 // We cannot compile public secondary dex paths with profiles. That's because
1081 // it will expose how the dex files are used by their owner.
1082 //
1083 // Note that the PackageManager is responsible to set the is_public flag for
1084 // primary apks and we do not check it here. In some cases, e.g. when
1085 // compiling with a public profile from the .dm file the PackageManager will
1086 // set is_public toghether with the profile guided compilation.
1087 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001088 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 }
Calin Juravle114f0812017-03-08 19:05:07 -08001090
1091 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001092 std::string location;
1093 if (is_secondary_dex) {
1094 location = dex_path;
1095 } else {
1096 if (profile_name == nullptr) {
1097 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001098 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001099 } else {
1100 location = profile_name;
1101 }
1102 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001103 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
1104 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001105}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001106
Victor Hsiehcb35a062020-08-13 16:11:13 -07001107// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1108// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001109bool 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 -07001110 const char* instruction_set, bool is_public, int uid,
1111 bool is_secondary_dex, bool profile_guided,
1112 UniqueFile* in_vdex_wrapper, RestorableFile* out_vdex_wrapper) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001113 CHECK(in_vdex_wrapper != nullptr);
1114 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001115 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1116 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001117 char in_odex_path[PKG_PATH_MAX];
1118 int dexopt_action = abs(dexopt_needed);
1119 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001120
1121 // Infer the name of the output VDEX.
1122 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1123 if (out_vdex_path_str.empty()) {
1124 return false;
1125 }
1126
Keun young Parkb7342262021-10-25 08:09:27 -07001127 // Create work file first. All files will be deleted when it fails.
1128 *out_vdex_wrapper = RestorableFile::CreateWritableFile(out_vdex_path_str,
1129 /*permissions*/ 0644);
1130 if (out_vdex_wrapper->fd() < 0) {
1131 ALOGE("installd cannot open vdex '%s' during dexopt\n", out_vdex_path_str.c_str());
1132 return false;
1133 }
1134
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001135 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001136 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001137 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1138 const char* path = nullptr;
1139 if (is_odex_location) {
1140 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1141 path = in_odex_path;
1142 } else {
1143 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001144 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001145 }
1146 } else {
1147 path = out_oat_path;
1148 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001149 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001150 if (in_vdex_path_str.empty()) {
1151 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001152 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001153 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001154 // We can update in place when all these conditions are met:
1155 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1156 // on /system typically cannot be updated in place).
1157 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1158 // cannot be currently used by a running process.
1159 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1160 // different vdex files to operate.
1161 update_vdex_in_place =
1162 (in_vdex_path_str == out_vdex_path_str) &&
1163 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1164 !profile_guided;
1165 if (update_vdex_in_place) {
Keun young Parkb7342262021-10-25 08:09:27 -07001166 // dex2oat marks it invalid anyway. So delete it and set work file fd.
1167 unlink(in_vdex_path_str.c_str());
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001168 // Open the file read-write to be able to update it.
Keun young Parkb7342262021-10-25 08:09:27 -07001169 in_vdex_wrapper->reset(out_vdex_wrapper->fd(), in_vdex_path_str);
1170 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1171 // wrapper).
1172 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001173 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001174 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1175 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001176 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177 }
1178
Victor Hsiehcb35a062020-08-13 16:11:13 -07001179 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001180 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001181 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1182 return false;
1183 }
1184
1185 // If we got here we successfully opened the vdex files.
1186 return true;
1187}
1188
1189// Opens the output oat file for the given apk.
Keun young Parkb7342262021-10-25 08:09:27 -07001190RestorableFile open_oat_out_file(const char* apk_path, const char* oat_dir, bool is_public, int uid,
1191 const char* instruction_set, bool is_secondary_dex) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001192 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001193 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 -07001194 return RestorableFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001195 }
Keun young Parkb7342262021-10-25 08:09:27 -07001196 RestorableFile oat = RestorableFile::CreateWritableFile(out_oat_path, /*permissions*/ 0644);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001197 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001198 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001199 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001200 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001202 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001203 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001204 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001205}
1206
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001207// Creates RDONLY fds for oat and vdex files, if exist.
1208// Returns false if it fails to create oat out path for the given apk path.
1209// Note that the method returns true even if the files could not be opened.
1210bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1211 const std::string& oat_dir,
1212 const std::string& instruction_set,
1213 bool is_secondary_dex,
1214 unique_fd* oat_file_fd,
1215 unique_fd* vdex_file_fd) {
1216 char oat_path[PKG_PATH_MAX];
1217 if (!create_oat_out_path(apk_path.c_str(),
1218 instruction_set.c_str(),
1219 oat_dir.c_str(),
1220 is_secondary_dex,
1221 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001222 LOG(ERROR) << "Could not create oat out path for "
1223 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001224 return false;
1225 }
1226 oat_file_fd->reset(open(oat_path, O_RDONLY));
1227 if (oat_file_fd->get() < 0) {
1228 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1229 }
1230
1231 std::string vdex_filename = create_vdex_filename(oat_path);
1232 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1233 if (vdex_file_fd->get() < 0) {
1234 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1235 }
1236
1237 return true;
1238}
1239
Calin Juravle80a21252017-01-17 14:43:25 -08001240// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001241// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1242// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1243// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001244class RunDexoptAnalyzer : public ExecVHelper {
1245 public:
1246 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001247 int vdex_fd,
1248 int oat_fd,
1249 int zip_fd,
1250 const std::string& instruction_set,
1251 const std::string& compiler_filter,
Calin Juravle3b758282021-06-08 08:04:52 -07001252 int profile_analysis_result,
David Brazdil4f6027a2019-03-19 11:44:21 +00001253 bool downgrade,
1254 const char* class_loader_context,
1255 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001256 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001257
1258 // We always run the analyzer in the background job.
1259 const char* dexoptanalyzer_bin = select_execution_binary(
1260 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001261
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001262 std::string dex_file_arg = "--dex-file=" + dex_file;
1263 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1264 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1265 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1266 std::string isa_arg = "--isa=" + instruction_set;
1267 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle3b758282021-06-08 08:04:52 -07001268 std::string profile_analysis_arg = "--profile-analysis-result="
1269 + std::to_string(profile_analysis_result);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001270 const char* downgrade_flag = "--downgrade";
1271 std::string class_loader_context_arg = "--class-loader-context=";
1272 if (class_loader_context != nullptr) {
1273 class_loader_context_arg += class_loader_context;
1274 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001275 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1276 if (!class_loader_context_fds.empty()) {
1277 class_loader_context_fds_arg += class_loader_context_fds;
1278 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001279
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001280 // program name, dex file, isa, filter
1281 AddArg(dex_file_arg);
1282 AddArg(isa_arg);
1283 AddArg(compiler_filter_arg);
1284 if (oat_fd >= 0) {
1285 AddArg(oat_fd_arg);
1286 }
1287 if (vdex_fd >= 0) {
1288 AddArg(vdex_fd_arg);
1289 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001290 AddArg(zip_fd_arg);
Calin Juravle3b758282021-06-08 08:04:52 -07001291 AddArg(profile_analysis_arg);
1292
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001293 if (downgrade) {
1294 AddArg(downgrade_flag);
1295 }
1296 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001297 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001298 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001299 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001300 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001301 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001302
Orion Hodson5f6b3ad2021-07-01 12:12:40 +01001303 // On-device signing related. odsign sets the system property odsign.verification.success if
1304 // AOT artifacts have the expected signatures.
1305 const bool trust_art_apex_data_files =
1306 ::android::base::GetBoolProperty("odsign.verification.success", false);
1307 if (!trust_art_apex_data_files) {
1308 AddRuntimeArg("-Xdeny-art-apex-data-files");
1309 }
1310
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001311 PrepareArgs(dexoptanalyzer_bin);
1312 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001313
1314 // Dexoptanalyzer mode which flattens the given class loader context and
1315 // prints a list of its dex files in that flattened order.
1316 RunDexoptAnalyzer(const char* class_loader_context) {
1317 CHECK(class_loader_context != nullptr);
1318
1319 // We always run the analyzer in the background job.
1320 const char* dexoptanalyzer_bin = select_execution_binary(
1321 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1322
1323 AddArg("--flatten-class-loader-context");
1324 AddArg(std::string("--class-loader-context=") + class_loader_context);
1325 PrepareArgs(dexoptanalyzer_bin);
1326 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001327};
Calin Juravle80a21252017-01-17 14:43:25 -08001328
1329// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001330static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001331 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001332 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001333 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001334 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001335 return false;
1336 }
Calin Juravle114f0812017-03-08 19:05:07 -08001337 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001338
Calin Juravle80a21252017-01-17 14:43:25 -08001339 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001340 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1341 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001342 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001343 return false;
1344 }
1345
1346 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001347 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001348
Calin Juravle7d765462017-09-04 15:57:10 -07001349 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001350 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001351 return false;
1352 }
1353
1354 return true;
1355}
1356
Calin Juravle7d765462017-09-04 15:57:10 -07001357// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1358// secondary dex files. This return codes are returned by the child process created for
1359// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001360
Andreas Gampe194fe422018-02-28 20:16:19 -08001361enum DexoptAnalyzerSkipCodes {
1362 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001363 // Specific errors are encoded in the name.
1364 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1365 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1366 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1367 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1368 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001369 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001370 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001371};
Calin Juravle7d765462017-09-04 15:57:10 -07001372
1373// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001374// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1375// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001376// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1377// of dexoptanalyzer.
1378static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001379 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001380 // The result values are defined in dexoptanalyzer.
1381 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001382 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001383 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001384 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001385 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001386 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001387 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001388 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001389 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001390 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1391 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001392 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1393 " Expected odex file status for secondary dex %s"
1394 " : dexoptanalyzer result=%d",
1395 dex_path.c_str(),
1396 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001397 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001398 }
1399
1400 // Use a second switch for enum switch-case analysis.
1401 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001402 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001403 // If the file does not exist there's no need for dexopt.
1404 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1405 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001406
1407 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1408 *error_msg = "Dexoptanalyzer path validation failed";
1409 return false;
1410 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1411 *error_msg = "Dexoptanalyzer open zip failed";
1412 return false;
1413 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1414 *error_msg = "Dexoptanalyzer dir preparation failed";
1415 return false;
1416 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1417 *error_msg = "Dexoptanalyzer open output failed";
1418 return false;
1419 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1420 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001421 return false;
1422 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001423
1424 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1425 dex_path.c_str(),
1426 result);
1427 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001428}
1429
Calin Juravle7d765462017-09-04 15:57:10 -07001430enum SecondaryDexAccess {
1431 kSecondaryDexAccessReadOk = 0,
1432 kSecondaryDexAccessDoesNotExist = 1,
1433 kSecondaryDexAccessPermissionError = 2,
1434 kSecondaryDexAccessIOError = 3
1435};
1436
1437static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1438 // Check if the path exists and can be read. If not, there's nothing to do.
1439 if (access(dex_path.c_str(), R_OK) == 0) {
1440 return kSecondaryDexAccessReadOk;
1441 } else {
1442 if (errno == ENOENT) {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001443 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1444 "Secondary dex does not exist: %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001445 return kSecondaryDexAccessDoesNotExist;
1446 } else {
Martijn Coenenc417edf2021-07-12 11:47:39 +02001447 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1448 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
Calin Juravle7d765462017-09-04 15:57:10 -07001449 return errno == EACCES
1450 ? kSecondaryDexAccessPermissionError
1451 : kSecondaryDexAccessIOError;
1452 }
1453 }
1454}
1455
1456static bool is_file_public(const std::string& filename) {
1457 struct stat file_stat;
1458 if (stat(filename.c_str(), &file_stat) == 0) {
1459 return (file_stat.st_mode & S_IROTH) != 0;
1460 }
1461 return false;
1462}
1463
1464// Create the oat file structure for the secondary dex 'dex_path' and assign
1465// the individual path component to the 'out_' parameters.
1466static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001467 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001468 size_t dirIndex = dex_path.rfind('/');
1469 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001470 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001471 return false;
1472 }
1473 // TODO(calin): we have similar computations in at lest 3 other places
1474 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1475 // using string append.
1476 std::string apk_dir = dex_path.substr(0, dirIndex);
1477 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1478 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1479
1480 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1481 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001482 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001483 return false;
1484 }
1485 return true;
1486}
1487
1488// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1489// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001490static bool validate_dexopt_storage_flags(int dexopt_flags,
1491 int* out_storage_flag,
1492 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001493 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1494 *out_storage_flag = FLAG_STORAGE_CE;
1495 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001496 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001497 return false;
1498 }
1499 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1500 *out_storage_flag = FLAG_STORAGE_DE;
1501 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001502 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001503 return false;
1504 }
1505 return true;
1506}
1507
David Brazdil4f6027a2019-03-19 11:44:21 +00001508static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1509 /* out */ std::vector<std::string>* context_dex_paths) {
1510 if (class_loader_context == nullptr) {
1511 return true;
1512 }
1513
1514 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1515
1516 // Pipe to get the hash result back from our child process.
1517 unique_fd pipe_read, pipe_write;
1518 if (!Pipe(&pipe_read, &pipe_write)) {
1519 PLOG(ERROR) << "Failed to create pipe";
1520 return false;
1521 }
1522
1523 pid_t pid = fork();
1524 if (pid == 0) {
1525 // child -- drop privileges before continuing.
1526 drop_capabilities(uid);
1527
1528 // Route stdout to `pipe_write`
1529 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1530 pipe_write.reset();
1531 pipe_read.reset();
1532
1533 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1534 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1535 }
1536
1537 /* parent */
1538 pipe_write.reset();
1539
1540 std::string str_dex_paths;
1541 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1542 PLOG(ERROR) << "Failed to read from pipe";
1543 return false;
1544 }
1545 pipe_read.reset();
1546
Jiakai Zhang495142a2022-02-21 19:38:14 +00001547 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
David Brazdil4f6027a2019-03-19 11:44:21 +00001548 if (!WIFEXITED(return_code)) {
1549 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1550 return false;
1551 }
1552
1553 constexpr int kFlattenClassLoaderContextSuccess = 50;
1554 return_code = WEXITSTATUS(return_code);
1555 if (return_code != kFlattenClassLoaderContextSuccess) {
1556 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1557 return false;
1558 }
1559
1560 if (!str_dex_paths.empty()) {
1561 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1562 }
1563 return true;
1564}
1565
1566static int open_dex_paths(const std::vector<std::string>& dex_paths,
1567 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1568 for (const std::string& dex_path : dex_paths) {
1569 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1570 if (zip_fds->back().get() < 0) {
1571 *error_msg = StringPrintf(
1572 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1573 if (errno == ENOENT) {
1574 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1575 } else {
1576 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1577 }
1578 }
1579 }
1580 return 0;
1581}
1582
1583static std::string join_fds(const std::vector<unique_fd>& fds) {
1584 std::stringstream ss;
1585 bool is_first = true;
1586 for (const unique_fd& fd : fds) {
1587 if (is_first) {
1588 is_first = false;
1589 } else {
1590 ss << ":";
1591 }
1592 ss << fd.get();
1593 }
1594 return ss.str();
1595}
1596
Keun young Park65578d62021-06-28 17:52:05 -07001597void control_dexopt_blocking(bool block) {
1598 dexopt_status_->control_dexopt_blocking(block);
1599}
1600
1601bool is_dexopt_blocked() {
1602 return dexopt_status_->is_dexopt_blocked();
1603}
1604
1605enum SecondaryDexOptProcessResult {
1606 kSecondaryDexOptProcessOk = 0,
1607 kSecondaryDexOptProcessCancelled = 1,
1608 kSecondaryDexOptProcessError = 2
1609};
1610
Calin Juravlec9eab382017-01-25 01:17:17 -08001611// 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 -07001612// be compiled.
1613// Returns: kSecondaryDexOptProcessError for errors (logged).
1614// kSecondaryDexOptProcessOk if the secondary dex path was process successfully.
1615// kSecondaryDexOptProcessCancelled if the processing was cancelled.
1616//
1617// When returning kSecondaryDexOptProcessOk, the output parameters will be:
Calin Juravleebc8a792017-04-04 20:21:05 -07001618// - is_public_out: whether or not the oat file should not be made public
1619// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1620// - oat_dir_out: the oat dir path where the oat file should be stored
Keun young Park65578d62021-06-28 17:52:05 -07001621static SecondaryDexOptProcessResult process_secondary_dex_dexopt(const std::string& dex_path,
1622 const char* pkgname, int dexopt_flags, const char* volume_uuid, int uid,
1623 const char* instruction_set, const char* compiler_filter, bool* is_public_out,
1624 int* dexopt_needed_out, std::string* oat_dir_out, bool downgrade,
1625 const char* class_loader_context, const std::vector<std::string>& context_dex_paths,
1626 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001627 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Keun young Park65578d62021-06-28 17:52:05 -07001628
1629 if (dexopt_status_->is_dexopt_blocked()) {
1630 return kSecondaryDexOptProcessCancelled;
1631 }
1632
Calin Juravle80a21252017-01-17 14:43:25 -08001633 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001634 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1635 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001636 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001637 }
Calin Juravle7d765462017-09-04 15:57:10 -07001638 // Compute the oat dir as it's not easy to extract it from the child computation.
1639 char oat_path[PKG_PATH_MAX];
1640 char oat_dir[PKG_PATH_MAX];
1641 char oat_isa_dir[PKG_PATH_MAX];
1642 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001643 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1644 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001645 return kSecondaryDexOptProcessError;
Calin Juravled23dee72017-07-06 16:29:11 -07001646 }
Calin Juravle7d765462017-09-04 15:57:10 -07001647 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001648
Keun young Park65578d62021-06-28 17:52:05 -07001649 bool cancelled = false;
1650 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1651 if (cancelled) {
1652 return kSecondaryDexOptProcessCancelled;
1653 }
Calin Juravle80a21252017-01-17 14:43:25 -08001654 if (pid == 0) {
1655 // child -- drop privileges before continuing.
1656 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001657
1658 // Validate the path structure.
1659 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001660 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1661 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001662 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001663 }
1664
1665 // Open the dex file.
1666 unique_fd zip_fd;
1667 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1668 if (zip_fd.get() < 0) {
1669 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001670 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001671 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001672 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001673 }
1674 }
1675
David Brazdil4f6027a2019-03-19 11:44:21 +00001676 // Open class loader context dex files.
1677 std::vector<unique_fd> context_zip_fds;
1678 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1679 if (open_dex_paths_rc != 0) {
1680 _exit(open_dex_paths_rc);
1681 }
1682
Calin Juravle7d765462017-09-04 15:57:10 -07001683 // Prepare the oat directories.
1684 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001685 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001686 }
1687
1688 // Open the vdex/oat files if any.
1689 unique_fd oat_file_fd;
1690 unique_fd vdex_file_fd;
1691 if (!maybe_open_oat_and_vdex_file(dex_path,
1692 *oat_dir_out,
1693 instruction_set,
1694 true /* is_secondary_dex */,
1695 &oat_file_fd,
1696 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001697 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001698 }
1699
1700 // Analyze profiles.
Calin Juravle3b758282021-06-08 08:04:52 -07001701 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
Calin Juravle824a64d2018-01-18 20:23:17 -08001702 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001703
1704 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001705 // Note that we do not do it before the fork since opening the files is required to happen
1706 // after forking.
1707 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1708 vdex_file_fd.get(),
1709 oat_file_fd.get(),
1710 zip_fd.get(),
1711 instruction_set,
Calin Juravle3b758282021-06-08 08:04:52 -07001712 compiler_filter,
1713 profile_analysis_result,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001714 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001715 class_loader_context,
1716 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001717 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001718 }
1719
1720 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00001721 int result = wait_child_with_timeout(pid, kShortTimeoutMs);
Keun young Park65578d62021-06-28 17:52:05 -07001722 cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Calin Juravle80a21252017-01-17 14:43:25 -08001723 if (!WIFEXITED(result)) {
Keun young Park65578d62021-06-28 17:52:05 -07001724 if ((WTERMSIG(result) == SIGKILL) && cancelled) {
1725 LOG(INFO) << "dexoptanalyzer cancelled for path:" << dex_path;
1726 return kSecondaryDexOptProcessCancelled;
1727 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001728 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1729 dex_path.c_str(),
1730 result);
1731 LOG(ERROR) << *error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07001732 return kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001733 }
1734 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001735 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001736 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1737 result,
1738 dexopt_needed_out,
1739 error_msg);
1740 if (!success) {
1741 LOG(ERROR) << *error_msg;
1742 }
Calin Juravle7d765462017-09-04 15:57:10 -07001743
1744 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1745
Calin Juravle80a21252017-01-17 14:43:25 -08001746 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001747 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1748 // makes the code simpler; force compilation is only needed during tests).
1749 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001750 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001751 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001752 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1753 }
1754
Calin Juravle7d765462017-09-04 15:57:10 -07001755 // Check if we should make the oat file public.
1756 // Note that if the dex file is not public the compiled code cannot be made public.
1757 // It is ok to check this flag outside in the parent process.
1758 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1759
Keun young Park65578d62021-06-28 17:52:05 -07001760 return success ? kSecondaryDexOptProcessOk : kSecondaryDexOptProcessError;
Calin Juravle80a21252017-01-17 14:43:25 -08001761}
1762
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001763static std::string format_dexopt_error(int status, const char* dex_path) {
1764 if (WIFEXITED(status)) {
1765 int int_code = WEXITSTATUS(status);
1766 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1767 if (code_name != nullptr) {
1768 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1769 }
1770 }
1771 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001772}
1773
Keun young Park65578d62021-06-28 17:52:05 -07001774
Calin Juravlec9eab382017-01-25 01:17:17 -08001775int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001776 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001777 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001778 bool downgrade, int target_sdk_version, const char* profile_name,
Keun young Park65578d62021-06-28 17:52:05 -07001779 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg,
1780 /* out */ bool* completed) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001781 CHECK(pkgname != nullptr);
1782 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001783 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001784 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1785 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001786
Keun young Park65578d62021-06-28 17:52:05 -07001787 bool local_completed; // local placeholder for nullptr case
1788 if (completed == nullptr) {
1789 completed = &local_completed;
1790 }
1791 *completed = true;
1792 if (dexopt_status_->is_dexopt_blocked()) {
1793 *completed = false;
1794 return 0;
1795 }
1796
Calin Juravled23dee72017-07-06 16:29:11 -07001797 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001798 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001799 return -1;
1800 }
1801
1802 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001803 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1804 class_loader_context);
1805 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001806 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001807 }
1808
Calin Juravleebc8a792017-04-04 20:21:05 -07001809 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001810 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1811 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1812 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001813 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001814 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001815 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001816 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001817 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001818 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001819
1820 // Check if we're dealing with a secondary dex file and if we need to compile it.
1821 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001822 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001823 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001824 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1825 *error_msg = "Failed acquiring context dex paths";
1826 return -1; // We had an error, logged in the process method.
1827 }
Keun young Park65578d62021-06-28 17:52:05 -07001828 SecondaryDexOptProcessResult sec_dex_result = process_secondary_dex_dexopt(dex_path,
1829 pkgname, dexopt_flags, volume_uuid, uid,instruction_set, compiler_filter,
1830 &is_public, &dexopt_needed, &oat_dir_str, downgrade, class_loader_context,
1831 context_dex_paths, error_msg);
1832 if (sec_dex_result == kSecondaryDexOptProcessOk) {
Calin Juravle80a21252017-01-17 14:43:25 -08001833 oat_dir = oat_dir_str.c_str();
1834 if (dexopt_needed == NO_DEXOPT_NEEDED) {
Keun young Parkb7342262021-10-25 08:09:27 -07001835 *completed = true;
Calin Juravle80a21252017-01-17 14:43:25 -08001836 return 0; // Nothing to do, report success.
1837 }
Keun young Park65578d62021-06-28 17:52:05 -07001838 } else if (sec_dex_result == kSecondaryDexOptProcessCancelled) {
1839 // cancelled, not an error.
1840 *completed = false;
1841 return 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001842 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001843 if (error_msg->empty()) { // TODO: Make this a CHECK.
1844 *error_msg = "Failed processing secondary.";
1845 }
Calin Juravle80a21252017-01-17 14:43:25 -08001846 return -1; // We had an error, logged in the process method.
1847 }
1848 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001849 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001850 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001851 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1852 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1853 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001854
1855 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001856 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1857 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001858 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1859 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001860 return -1;
1861 }
1862
David Brazdil4f6027a2019-03-19 11:44:21 +00001863 // Open class loader context dex files.
1864 std::vector<unique_fd> context_input_fds;
1865 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1866 LOG(ERROR) << *error_msg;
1867 return -1;
1868 }
1869
Calin Juravle7a570e82017-01-14 16:23:30 -08001870 // Create the output OAT file.
Keun young Parkb7342262021-10-25 08:09:27 -07001871 RestorableFile out_oat =
1872 open_oat_out_file(dex_path, oat_dir, is_public, uid, instruction_set, is_secondary_dex);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001873 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001874 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001875 return -1;
1876 }
1877
1878 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001879 UniqueFile in_vdex;
Keun young Parkb7342262021-10-25 08:09:27 -07001880 RestorableFile out_vdex;
Victor Hsiehcb35a062020-08-13 16:11:13 -07001881 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1882 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1883 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001884 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001885 return -1;
1886 }
1887
Calin Juravlecb556e32017-04-04 20:22:50 -07001888 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1889 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1890 // fully inherit their parent context).
1891 // Note that for primary apk the oat files are created before, in a separate installd
1892 // call which also does the restorecon. TODO(calin): unify the paths.
1893 if (is_secondary_dex) {
1894 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1895 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001896 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1897 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001898 return -1;
1899 }
1900 }
1901
Jeff Sharkey90aff262016-12-12 14:28:24 -07001902 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001903 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001904
Calin Juravle7a570e82017-01-14 16:23:30 -08001905 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001906 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001907 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001908
Victor Hsiehcb35a062020-08-13 16:11:13 -07001909 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001910 // We don't create an app image without reference profile since there is no speedup from
1911 // loading it in that case and instead will be a small overhead.
1912 generate_app_image = false;
1913 }
1914
1915 // Create the app image file if needed.
Keun young Parkb7342262021-10-25 08:09:27 -07001916 RestorableFile out_image = maybe_open_app_image(out_oat.path(), generate_app_image, is_public,
1917 uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001918
Victor Hsiehcb35a062020-08-13 16:11:13 -07001919 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001920 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001921 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1922 dex_metadata_path);
1923 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001924 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1925 }
1926 }
1927
Victor Hsieh8948a862020-08-07 11:30:55 -07001928 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1929 RUNTIME_NATIVE_BOOT_NAMESPACE,
1930 ENABLE_JITZYGOTE_IMAGE,
1931 /*default_value=*/ "");
1932 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1933
Victor Hsiehe98e6512020-08-10 15:39:22 -07001934 // Decide whether to use dex2oat64.
1935 bool use_dex2oat64 = false;
1936 // Check whether the device even supports 64-bit ABIs.
1937 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1938 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1939 }
1940 const char* dex2oat_bin = select_execution_binary(
1941 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1942 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1943 background_job_compile);
1944
Victor Hsiehc9821f12020-08-07 11:32:29 -07001945 auto execv_helper = std::make_unique<ExecVHelper>();
1946
Andreas Gampe023b2242018-02-28 16:03:25 -08001947 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001948
Victor Hsiehc9821f12020-08-07 11:32:29 -07001949 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Keun young Parkb7342262021-10-25 08:09:27 -07001950 runner.Initialize(out_oat.GetUniqueFile(), out_vdex.GetUniqueFile(), out_image.GetUniqueFile(),
1951 in_dex, in_vdex, dex_metadata, reference_profile, class_loader_context,
1952 join_fds(context_input_fds), swap_fd.get(), instruction_set, compiler_filter,
1953 debuggable, boot_complete, for_restore, target_sdk_version,
1954 enable_hidden_api_checks, generate_compact_dex, use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001955 compilation_reason);
1956
Keun young Park65578d62021-06-28 17:52:05 -07001957 bool cancelled = false;
1958 pid_t pid = dexopt_status_->check_cancellation_and_fork(&cancelled);
1959 if (cancelled) {
Keun young Parkb7342262021-10-25 08:09:27 -07001960 *completed = false;
1961 reference_profile.DisableCleanup();
Keun young Park65578d62021-06-28 17:52:05 -07001962 return 0;
1963 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001964 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001965 // Need to set schedpolicy before dropping privileges
1966 // for cgroup migration. See details at b/175178520.
1967 SetDex2OatScheduling(boot_complete);
1968
Jeff Sharkey90aff262016-12-12 14:28:24 -07001969 /* child -- drop privileges before continuing */
1970 drop_capabilities(uid);
1971
Victor Hsiehcb35a062020-08-13 16:11:13 -07001972 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001973 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1974 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001975 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001976 }
1977
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001978 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001979 } else {
Jiakai Zhang495142a2022-02-21 19:38:14 +00001980 int res = wait_child_with_timeout(pid, kLongTimeoutMs);
Keun young Park65578d62021-06-28 17:52:05 -07001981 bool cancelled = dexopt_status_->check_if_killed_and_remove_dexopt_pid(pid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001983 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001984 } else {
Keun young Park65578d62021-06-28 17:52:05 -07001985 if ((WTERMSIG(res) == SIGKILL) && cancelled) {
1986 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- cancelled";
1987 // cancelled, not an error
1988 *completed = false;
Keun young Parkb7342262021-10-25 08:09:27 -07001989 reference_profile.DisableCleanup();
Keun young Park65578d62021-06-28 17:52:05 -07001990 return 0;
1991 }
Andreas Gampe023b2242018-02-28 16:03:25 -08001992 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1993 << std::hex << std::setw(4) << res << ", process failed";
1994 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001995 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001996 }
1997 }
1998
Keun young Parkb7342262021-10-25 08:09:27 -07001999 // dex2oat ran successfully, so profile is safe to keep.
Victor Hsiehcb35a062020-08-13 16:11:13 -07002000 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07002001
Keun young Parkb7342262021-10-25 08:09:27 -07002002 // We've been successful, commit work files.
2003 // If committing (=renaming tmp to regular) fails, try to restore backup files.
2004 // If restoring fails as well, as a last resort, remove all files.
2005 if (!out_oat.CreateBackupFile() || !out_vdex.CreateBackupFile() ||
2006 !out_image.CreateBackupFile()) {
2007 // Renaming failure can mean that the original file may not be accessible from installd.
2008 LOG(ERROR) << "Cannot create backup file from existing file, file in wrong state?"
2009 << ", out_oat:" << out_oat.path() << " ,out_vdex:" << out_vdex.path()
2010 << " ,out_image:" << out_image.path();
2011 out_oat.ResetAndRemoveAllFiles();
2012 out_vdex.ResetAndRemoveAllFiles();
2013 out_image.ResetAndRemoveAllFiles();
2014 return -1;
2015 }
2016 if (!out_oat.CommitWorkFile() || !out_vdex.CommitWorkFile() || !out_image.CommitWorkFile()) {
2017 LOG(ERROR) << "Cannot commit, out_oat:" << out_oat.path()
2018 << " ,out_vdex:" << out_vdex.path() << " ,out_image:" << out_image.path();
2019 if (!out_oat.RestoreBackupFile() || !out_vdex.RestoreBackupFile() ||
2020 !out_image.RestoreBackupFile()) {
2021 LOG(ERROR) << "Cannot cancel commit, out_oat:" << out_oat.path()
2022 << " ,out_vdex:" << out_vdex.path() << " ,out_image:" << out_image.path();
2023 // Restoring failed.
2024 out_oat.ResetAndRemoveAllFiles();
2025 out_vdex.ResetAndRemoveAllFiles();
2026 out_image.ResetAndRemoveAllFiles();
2027 }
2028 return -1;
2029 }
2030 // Now remove remaining backup files.
2031 out_oat.RemoveBackupFile();
2032 out_vdex.RemoveBackupFile();
2033 out_image.RemoveBackupFile();
2034
Keun young Park65578d62021-06-28 17:52:05 -07002035 *completed = true;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002036 return 0;
2037}
2038
Calin Juravlec9eab382017-01-25 01:17:17 -08002039// Try to remove the given directory. Log an error if the directory exists
2040// and is empty but could not be removed.
2041static bool rmdir_if_empty(const char* dir) {
2042 if (rmdir(dir) == 0) {
2043 return true;
2044 }
2045 if (errno == ENOENT || errno == ENOTEMPTY) {
2046 return true;
2047 }
2048 PLOG(ERROR) << "Failed to remove dir: " << dir;
2049 return false;
2050}
2051
2052// Try to unlink the given file. Log an error if the file exists and could not
2053// be unlinked.
2054static bool unlink_if_exists(const std::string& file) {
2055 if (unlink(file.c_str()) == 0) {
2056 return true;
2057 }
2058 if (errno == ENOENT) {
2059 return true;
2060
2061 }
2062 PLOG(ERROR) << "Could not unlink: " << file;
2063 return false;
2064}
2065
Calin Juravle7d765462017-09-04 15:57:10 -07002066enum ReconcileSecondaryDexResult {
2067 kReconcileSecondaryDexExists = 0,
2068 kReconcileSecondaryDexCleanedUp = 1,
2069 kReconcileSecondaryDexValidationError = 2,
2070 kReconcileSecondaryDexCleanUpError = 3,
2071 kReconcileSecondaryDexAccessIOError = 4,
2072};
Calin Juravlec9eab382017-01-25 01:17:17 -08002073
2074// Reconcile the secondary dex 'dex_path' and its generated oat files.
2075// Return true if all the parameters are valid and the secondary dex file was
2076// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2077// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2078// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2079// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2080// Return false if there were errors during processing. In this case
2081// out_secondary_dex_exists will be set to false.
2082bool reconcile_secondary_dex_file(const std::string& dex_path,
2083 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002084 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002085 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002086 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002087 if (isas.size() == 0) {
2088 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2089 return false;
2090 }
2091
Calin Juravle7d765462017-09-04 15:57:10 -07002092 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2093 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2094 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002095 return false;
2096 }
2097
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002098 // As a security measure we want to unlink art artifacts with the reduced capabilities
2099 // of the package user id. So we fork and drop capabilities in the child.
2100 pid_t pid = fork();
2101 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002102 /* child -- drop privileges before continuing */
2103 drop_capabilities(uid);
2104
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002105 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002106 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002107 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002108 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2109 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002110 _exit(kReconcileSecondaryDexValidationError);
2111 }
2112
2113 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2114 switch (access_check) {
2115 case kSecondaryDexAccessDoesNotExist:
2116 // File does not exist. Proceed with cleaning.
2117 break;
2118 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2119 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2120 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2121 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02002122 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2123 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07002124 _exit(kReconcileSecondaryDexValidationError);
2125 }
2126
2127 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002128 char oat_path[PKG_PATH_MAX];
2129 char oat_dir[PKG_PATH_MAX];
2130 char oat_isa_dir[PKG_PATH_MAX];
2131 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002132 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002133 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002134 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002135 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002136 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002137 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002138 }
Calin Juravle51314092017-05-18 15:33:05 -07002139
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002140 // Delete oat/vdex/art files.
2141 result = unlink_if_exists(oat_path) && result;
2142 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2143 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002144
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002145 // Delete profiles.
2146 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002147 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002148 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002149 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002150 result = unlink_if_exists(current_profile) && result;
2151 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002152
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002153 // We upgraded once the location of current profile for secondary dex files.
2154 // Check for any previous left-overs and remove them as well.
2155 std::string old_current_profile = dex_path + ".prof";
2156 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002157
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002158 // Try removing the directories as well, they might be empty.
2159 result = rmdir_if_empty(oat_isa_dir) && result;
2160 result = rmdir_if_empty(oat_dir) && result;
2161 }
Calin Juravle7d765462017-09-04 15:57:10 -07002162 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002163 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2164 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002165 }
2166 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002167 }
2168
Jiakai Zhang495142a2022-02-21 19:38:14 +00002169 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravle7d765462017-09-04 15:57:10 -07002170 if (!WIFEXITED(return_code)) {
2171 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2172 } else {
2173 return_code = WEXITSTATUS(return_code);
2174 }
2175
2176 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2177
2178 switch (return_code) {
2179 case kReconcileSecondaryDexCleanedUp:
2180 case kReconcileSecondaryDexValidationError:
2181 // If we couldn't validate assume the dex file does not exist.
2182 // This will purge the entry from the PM records.
2183 *out_secondary_dex_exists = false;
2184 return true;
2185 case kReconcileSecondaryDexExists:
2186 *out_secondary_dex_exists = true;
2187 return true;
2188 case kReconcileSecondaryDexAccessIOError:
2189 // We had an access IO error.
2190 // Return false so that we can try again.
2191 // The value of out_secondary_dex_exists does not matter in this case and by convention
2192 // is set to false.
2193 *out_secondary_dex_exists = false;
2194 return false;
2195 default:
2196 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2197 *out_secondary_dex_exists = false;
2198 return false;
2199 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002200}
2201
Alan Stokesa25d90c2017-10-16 10:56:00 +01002202// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2203// Returns true if all parameters are valid and the hash successfully computed and stored in
2204// out_secondary_dex_hash.
2205// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2206// the app.
2207// For any other errors (e.g. if any of the parameters are invalid) returns false.
2208bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002209 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002210 std::vector<uint8_t>* out_secondary_dex_hash) {
2211 out_secondary_dex_hash->clear();
2212
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002213 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002214
2215 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2216 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2217 << storage_flag;
2218 return false;
2219 }
2220
2221 // Pipe to get the hash result back from our child process.
2222 unique_fd pipe_read, pipe_write;
2223 if (!Pipe(&pipe_read, &pipe_write)) {
2224 PLOG(ERROR) << "Failed to create pipe";
2225 return false;
2226 }
2227
2228 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2229 // access data the app itself can access.
2230 pid_t pid = fork();
2231 if (pid == 0) {
2232 // child -- drop privileges before continuing
2233 drop_capabilities(uid);
2234 pipe_read.reset();
2235
2236 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002237 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2238 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002239 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002240 }
2241
2242 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2243 if (fd == -1) {
2244 if (errno == EACCES || errno == ENOENT) {
2245 // Not treated as an error.
2246 _exit(0);
2247 }
2248 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002249 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2250 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002251 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002252 }
2253
2254 SHA256_CTX ctx;
2255 SHA256_Init(&ctx);
2256
2257 std::vector<uint8_t> buffer(65536);
2258 while (true) {
2259 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2260 if (bytes_read == 0) {
2261 break;
2262 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002263 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2264 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002265 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002266 }
2267
2268 SHA256_Update(&ctx, buffer.data(), bytes_read);
2269 }
2270
2271 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2272 SHA256_Final(hash.data(), &ctx);
2273 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002274 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002275 }
2276
2277 _exit(0);
2278 }
2279
2280 // parent
2281 pipe_write.reset();
2282
2283 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2284 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2285 out_secondary_dex_hash->clear();
2286 }
Jiakai Zhang495142a2022-02-21 19:38:14 +00002287 return wait_child_with_timeout(pid, kShortTimeoutMs) == 0;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002288}
2289
Jeff Sharkey90aff262016-12-12 14:28:24 -07002290// Helper for move_ab, so that we can have common failure-case cleanup.
2291static bool unlink_and_rename(const char* from, const char* to) {
2292 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2293 // return a failure.
2294 struct stat s;
2295 if (stat(to, &s) == 0) {
2296 if (!S_ISREG(s.st_mode)) {
2297 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2298 return false;
2299 }
2300 if (unlink(to) != 0) {
2301 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2302 return false;
2303 }
2304 } else {
2305 // This may be a permission problem. We could investigate the error code, but we'll just
2306 // let the rename failure do the work for us.
2307 }
2308
2309 // Try to rename "to" to "from."
2310 if (rename(from, to) != 0) {
2311 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2312 return false;
2313 }
2314 return true;
2315}
2316
2317// Move/rename a B artifact (from) to an A artifact (to).
2318static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2319 // Check whether B exists.
2320 {
2321 struct stat s;
2322 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002323 // Ignore for now. The service calling this isn't smart enough to
2324 // understand lack of artifacts at the moment.
2325 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002326 return false;
2327 }
2328 if (!S_ISREG(s.st_mode)) {
2329 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2330 // Try to unlink, but swallow errors.
2331 unlink(b_path.c_str());
2332 return false;
2333 }
2334 }
2335
2336 // Rename B to A.
2337 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2338 // Delete the b_path so we don't try again (or fail earlier).
2339 if (unlink(b_path.c_str()) != 0) {
2340 PLOG(ERROR) << "Could not unlink " << b_path;
2341 }
2342
2343 return false;
2344 }
2345
2346 return true;
2347}
2348
2349bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2350 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002351 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2352 if (slot_suffix.empty()) {
2353 return false;
2354 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002355
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002356 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2357 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2358 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002359 }
2360
2361 // Validate other inputs.
2362 if (validate_apk_path(apk_path) != 0) {
2363 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2364 return false;
2365 }
2366 if (validate_apk_path(oat_dir) != 0) {
2367 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2368 return false;
2369 }
2370
2371 char a_path[PKG_PATH_MAX];
2372 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2373 return false;
2374 }
2375 const std::string a_vdex_path = create_vdex_filename(a_path);
2376 const std::string a_image_path = create_image_filename(a_path);
2377
2378 // B path = A path + slot suffix.
2379 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2380 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2381 const std::string b_image_path = StringPrintf("%s.%s",
2382 a_image_path.c_str(),
2383 slot_suffix.c_str());
2384
2385 bool success = true;
2386 if (move_ab_path(b_path, a_path)) {
2387 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2388 // Note: we can live without an app image. As such, ignore failure to move the image file.
2389 // If we decide to require the app image, or the app image being moved correctly,
2390 // then change accordingly.
2391 constexpr bool kIgnoreAppImageFailure = true;
2392
2393 if (!a_image_path.empty()) {
2394 if (!move_ab_path(b_image_path, a_image_path)) {
2395 unlink(a_image_path.c_str());
2396 if (!kIgnoreAppImageFailure) {
2397 success = false;
2398 }
2399 }
2400 }
2401 } else {
2402 // Cleanup: delete B image, ignore errors.
2403 unlink(b_image_path.c_str());
2404 success = false;
2405 }
2406 } else {
2407 // Cleanup: delete B image, ignore errors.
2408 unlink(b_vdex_path.c_str());
2409 unlink(b_image_path.c_str());
2410 success = false;
2411 }
2412 return success;
2413}
2414
Calin Juravleea214ad2021-06-11 09:17:20 -07002415int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002416 // Delete the oat/odex file.
2417 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002418 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002419 /*is_secondary_dex*/false, out_path)) {
Calin Juravleea214ad2021-06-11 09:17:20 -07002420 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2421 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002422 }
2423
2424 // In case of a permission failure report the issue. Otherwise just print a warning.
Calin Juravleea214ad2021-06-11 09:17:20 -07002425 auto unlink_and_check = [](const char* path) -> int64_t {
2426 struct stat file_stat;
2427 if (stat(path, &file_stat) != 0) {
2428 if (errno != ENOENT) {
2429 PLOG(ERROR) << "Could not stat " << path;
2430 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002431 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002432 return 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002433 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002434
2435 if (unlink(path) != 0) {
2436 if (errno != ENOENT) {
2437 PLOG(ERROR) << "Could not unlink " << path;
2438 return -1;
2439 }
2440 }
2441 return static_cast<int64_t>(file_stat.st_size);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002442 };
2443
2444 // Delete the oat/odex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002445 int64_t return_value_oat = unlink_and_check(out_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002446
2447 // Derive and delete the app image.
Calin Juravleea214ad2021-06-11 09:17:20 -07002448 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07002449
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002450 // Derive and delete the vdex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002451 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002452
Calin Juravleea214ad2021-06-11 09:17:20 -07002453 // Report result
2454 if (return_value_oat == -1
2455 || return_value_art == -1
2456 || return_value_vdex == -1) {
2457 return -1;
2458 }
2459
2460 return return_value_oat + return_value_art + return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002461}
2462
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002463static bool is_absolute_path(const std::string& path) {
2464 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2465 LOG(ERROR) << "Invalid absolute path " << path;
2466 return false;
2467 } else {
2468 return true;
2469 }
2470}
2471
2472static bool is_valid_instruction_set(const std::string& instruction_set) {
2473 // TODO: add explicit whitelisting of instruction sets
2474 if (instruction_set.find('/') != std::string::npos) {
2475 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2476 return false;
2477 } else {
2478 return true;
2479 }
2480}
2481
2482bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2483 const char *apk_path, const char *instruction_set) {
2484 std::string oat_dir_ = oat_dir;
2485 std::string apk_path_ = apk_path;
2486 std::string instruction_set_ = instruction_set;
2487
2488 if (!is_absolute_path(oat_dir_)) return false;
2489 if (!is_absolute_path(apk_path_)) return false;
2490 if (!is_valid_instruction_set(instruction_set_)) return false;
2491
2492 std::string::size_type end = apk_path_.rfind('.');
2493 std::string::size_type start = apk_path_.rfind('/', end);
2494 if (end == std::string::npos || start == std::string::npos) {
2495 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2496 return false;
2497 }
2498
2499 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2500 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2501 const char* res = res_.c_str();
2502 if (strlen(res) >= PKG_PATH_MAX) {
2503 LOG(ERROR) << "Result too large";
2504 return false;
2505 } else {
2506 strlcpy(path, res, PKG_PATH_MAX);
2507 return true;
2508 }
2509}
2510
2511bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2512 const char *instruction_set) {
2513 std::string apk_path_ = apk_path;
2514 std::string instruction_set_ = instruction_set;
2515
2516 if (!is_absolute_path(apk_path_)) return false;
2517 if (!is_valid_instruction_set(instruction_set_)) return false;
2518
2519 std::string::size_type end = apk_path_.rfind('.');
2520 std::string::size_type start = apk_path_.rfind('/', end);
2521 if (end == std::string::npos || start == std::string::npos) {
2522 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2523 return false;
2524 }
2525
2526 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2527 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2528}
2529
2530bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2531 const char *instruction_set) {
2532 std::string src_ = src;
2533 std::string instruction_set_ = instruction_set;
2534
2535 if (!is_absolute_path(src_)) return false;
2536 if (!is_valid_instruction_set(instruction_set_)) return false;
2537
2538 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2539 if (*it == '/') {
2540 *it = '@';
2541 }
2542 }
2543
2544 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2545 + DALVIK_CACHE_POSTFIX;
2546 const char* res = res_.c_str();
2547 if (strlen(res) >= PKG_PATH_MAX) {
2548 LOG(ERROR) << "Result too large";
2549 return false;
2550 } else {
2551 strlcpy(path, res, PKG_PATH_MAX);
2552 return true;
2553 }
2554}
2555
Calin Juravle59f7ab82018-04-27 17:50:23 -07002556bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2557 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002558 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2559 for (const std::string& elem : classpaths_elems) {
2560 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2561 if (fd < 0) {
2562 PLOG(ERROR) << "Could not open classpath elem " << elem;
2563 return false;
2564 } else {
2565 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002566 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002567 }
2568 }
2569 return true;
2570}
2571
2572static bool create_app_profile_snapshot(int32_t app_id,
2573 const std::string& package_name,
2574 const std::string& profile_name,
2575 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002576 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2577
Alex Buynytskyy79dcab52021-11-19 11:43:04 -08002578 unique_fd snapshot_fd = open_snapshot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002579 if (snapshot_fd < 0) {
2580 return false;
2581 }
2582
2583 std::vector<unique_fd> profiles_fd;
2584 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002585 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2586 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002587 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2588 return false;
2589 }
2590
2591 profiles_fd.push_back(std::move(reference_profile_fd));
2592
Calin Juravle0d0a4922018-01-23 19:54:11 -08002593 // Open the class paths elements. These will be used to filter out profile data that does
2594 // not belong to the classpath during merge.
2595 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002596 std::vector<std::string> dex_locations;
2597 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002598 return false;
2599 }
2600
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002601 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002602 // This is specifically a snapshot for an app, so don't use boot image profiles.
2603 args.SetupMerge(profiles_fd,
2604 snapshot_fd,
2605 apk_fds,
2606 dex_locations,
2607 /* for_snapshot= */ true,
2608 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002609 pid_t pid = fork();
2610 if (pid == 0) {
2611 /* child -- drop privileges before continuing */
2612 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002613 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002614 }
2615
2616 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002617 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravle29591732017-11-20 17:46:19 -08002618 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002619 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002620 cleanup_output_fd(snapshot_fd.get());
Calin Juravle29591732017-11-20 17:46:19 -08002621 return false;
2622 }
2623
Calin Juravle78728f32019-11-08 17:55:46 -08002624 // Verify that profman finished successfully.
2625 int profman_code = WEXITSTATUS(return_code);
2626 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2627 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2628 << ":" << profman_code;
2629 return false;
2630 }
Calin Juravle29591732017-11-20 17:46:19 -08002631 return true;
2632}
2633
Calin Juravle0d0a4922018-01-23 19:54:11 -08002634static bool create_boot_image_profile_snapshot(const std::string& package_name,
2635 const std::string& profile_name,
2636 const std::string& classpath) {
2637 // The reference profile directory for the android package might not be prepared. Do it now.
2638 const std::string ref_profile_dir =
2639 create_primary_reference_profile_package_dir_path(package_name);
2640 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2641 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2642 return false;
2643 }
2644
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002645 // Return false for empty class path since it may otherwise return true below if profiles is
2646 // empty.
2647 if (classpath.empty()) {
2648 PLOG(ERROR) << "Class path is empty";
2649 return false;
2650 }
2651
Calin Juravle0d0a4922018-01-23 19:54:11 -08002652 // Open and create the snapshot profile.
Alex Buynytskyy79dcab52021-11-19 11:43:04 -08002653 unique_fd snapshot_fd = open_snapshot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002654
2655 // Collect all non empty profiles.
2656 // The collection will traverse all applications profiles and find the non empty files.
2657 // This has the potential of inspecting a large number of files and directories (depending
2658 // on the number of applications and users). So there is a slight increase in the chance
2659 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2660 // fail the snapshot and aggregate whatever profile we could open.
2661 //
2662 // The profile snapshot is a best effort based on available data it's ok if some data
2663 // from some apps is missing. It will be counter productive for the snapshot to fail
2664 // because we could not open or read some of the files.
2665 std::vector<std::string> profiles;
2666 if (!collect_profiles(&profiles)) {
2667 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2668 }
2669
2670 // If we have no profiles return early.
2671 if (profiles.empty()) {
2672 return true;
2673 }
2674
2675 // Open the classpath elements. These will be used to filter out profile data that does
2676 // not belong to the classpath during merge.
2677 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002678 std::vector<std::string> dex_locations;
2679 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002680 return false;
2681 }
2682
2683 // If we could not open any files from the classpath return an error.
2684 if (apk_fds.empty()) {
2685 LOG(ERROR) << "Could not open any of the classpath elements.";
2686 return false;
2687 }
2688
2689 // Aggregate the profiles in batches of kAggregationBatchSize.
2690 // We do this to avoid opening a huge a amount of files.
2691 static constexpr size_t kAggregationBatchSize = 10;
2692
Calin Juravle0d0a4922018-01-23 19:54:11 -08002693 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002694 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002695 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
Calin Juravlee01f8712021-06-03 18:16:54 -07002696 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002697 if (fd.get() >= 0) {
2698 profiles_fd.push_back(std::move(fd));
2699 }
2700 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002701
2702 // We aggregate (read & write) into the same fd multiple times in a row.
2703 // We need to reset the cursor every time to ensure we read the whole file every time.
2704 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2705 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2706 return false;
2707 }
2708
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002709 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002710 args.SetupMerge(profiles_fd,
2711 snapshot_fd,
2712 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002713 dex_locations,
2714 /*for_snapshot=*/true,
2715 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002716 pid_t pid = fork();
2717 if (pid == 0) {
2718 /* child -- drop privileges before continuing */
2719 drop_capabilities(AID_SYSTEM);
2720
Calin Juravle59f7ab82018-04-27 17:50:23 -07002721 // The introduction of new access flags into boot jars causes them to
2722 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002723 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002724 }
2725
2726 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002727 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravlea64fb512019-11-06 16:11:14 -08002728
Calin Juravle0d0a4922018-01-23 19:54:11 -08002729 if (!WIFEXITED(return_code)) {
2730 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002731 cleanup_output_fd(snapshot_fd.get());
Calin Juravle0d0a4922018-01-23 19:54:11 -08002732 return false;
2733 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002734
2735 // Verify that profman finished successfully.
2736 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002737 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2738 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2739 << ":" << profman_code;
2740 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002741 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002742 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002743
Calin Juravle0d0a4922018-01-23 19:54:11 -08002744 return true;
2745}
2746
2747bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2748 const std::string& profile_name, const std::string& classpath) {
2749 if (app_id == -1) {
2750 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2751 } else {
2752 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2753 }
2754}
2755
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002756static bool check_profile_exists_in_dexmetadata(const std::string& dex_metadata) {
2757 ZipArchiveHandle zip = nullptr;
2758 if (OpenArchive(dex_metadata.c_str(), &zip) != 0) {
2759 PLOG(ERROR) << "Failed to open dm '" << dex_metadata << "'";
2760 return false;
2761 }
2762
2763 ZipEntry64 entry;
2764 int result = FindEntry(zip, "primary.prof", &entry);
2765 CloseArchive(zip);
2766
2767 return result != 0 ? false : true;
2768}
2769
Calin Juravlec3b049e2018-01-18 22:32:58 -08002770bool prepare_app_profile(const std::string& package_name,
2771 userid_t user_id,
2772 appid_t app_id,
2773 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002774 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002775 const std::optional<std::string>& dex_metadata) {
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002776 if (user_id != USER_NULL) {
2777 if (user_id < 0) {
2778 LOG(ERROR) << "Unexpected user ID " << user_id;
2779 return false;
2780 }
2781
2782 // Prepare the current profile.
2783 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2784 /*is_secondary_dex*/ false);
2785 uid_t uid = multiuser_get_uid(user_id, app_id);
2786 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2787 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2788 return false;
2789 }
2790 } else {
2791 // Prepare the reference profile as the system user.
2792 user_id = USER_SYSTEM;
Calin Juravlec3b049e2018-01-18 22:32:58 -08002793 }
2794
2795 // Check if we need to install the profile from the dex metadata.
Yang Tianping8f2a40e2021-10-29 14:39:02 +08002796 if (!dex_metadata || !check_profile_exists_in_dexmetadata(dex_metadata->c_str())) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002797 return true;
2798 }
2799
2800 // We have a dex metdata. Merge the profile into the reference profile.
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002801 unique_fd ref_profile_fd =
2802 open_reference_profile(multiuser_get_uid(user_id, app_id), package_name, profile_name,
2803 /*read_write*/ true, /*is_secondary_dex*/ false);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002804 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2805 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002806 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2807 if (apk_fd < 0) {
2808 PLOG(ERROR) << "Could not open code path " << code_path;
2809 return false;
2810 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002811
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002812 RunProfman args;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002813 args.SetupCopyAndUpdate(dex_metadata_fd,
2814 ref_profile_fd,
2815 apk_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002816 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002817 pid_t pid = fork();
2818 if (pid == 0) {
2819 /* child -- drop privileges before continuing */
2820 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2821 drop_capabilities(app_shared_gid);
2822
Calin Juravlef63d4792018-01-30 17:43:34 +00002823 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002824 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002825 }
2826
2827 /* parent */
Jiakai Zhang495142a2022-02-21 19:38:14 +00002828 int return_code = wait_child_with_timeout(pid, kShortTimeoutMs);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002829 if (!WIFEXITED(return_code)) {
2830 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Jiakai Zhang495142a2022-02-21 19:38:14 +00002831 cleanup_output_fd(ref_profile_fd.get());
Calin Juravlec3b049e2018-01-18 22:32:58 -08002832 return false;
2833 }
2834 return true;
2835}
2836
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00002837int get_odex_visibility(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2838 char oat_path[PKG_PATH_MAX];
2839 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, /*is_secondary_dex=*/false,
2840 oat_path)) {
2841 return -1;
2842 }
2843 struct stat st;
2844 if (stat(oat_path, &st) == -1) {
2845 if (errno == ENOENT) {
2846 return ODEX_NOT_FOUND;
2847 }
2848 PLOG(ERROR) << "Could not stat " << oat_path;
2849 return -1;
2850 }
2851 return (st.st_mode & S_IROTH) ? ODEX_IS_PUBLIC : ODEX_IS_PRIVATE;
2852}
2853
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002854} // namespace installd
2855} // namespace android