blob: 5f2e3f91b57a95d42903ec52dfcf1f50d2e2962e [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
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.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
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Martijn Coenen6de402a2021-04-26 16:23:40 +020039#include <async_safe/log.h>
Calin Juravle80a21252017-01-17 14:43:25 -080040#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include <cutils/properties.h>
42#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000048#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080052#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070053#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060054#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070055#include "installd_deps.h"
Calin Juravle3b758282021-06-08 08:04:52 -070056#include "installd_constants.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070057#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070058#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070059#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070060#include "utils.h"
61
Victor Hsieh76f19ba2020-08-10 14:37:26 -070062using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070063using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070064using android::base::GetBoolProperty;
65using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000066using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010067using android::base::ReadFully;
68using android::base::StringPrintf;
69using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080070using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070071
72namespace android {
73namespace installd {
74
Andreas Gampefa2dadd2018-02-28 19:52:47 -080075
Calin Juravle114f0812017-03-08 19:05:07 -080076// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
77struct FreeDelete {
78 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
79 void operator()(const void* ptr) const {
80 free(const_cast<void*>(ptr));
81 }
82};
83
84// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
85template <typename T>
86using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
87
Calin Juravle1a0af3b2017-03-09 14:33:33 -080088static unique_fd invalid_unique_fd() {
89 return unique_fd(-1);
90}
91
Andreas Gampe6a9cf722017-07-24 16:49:10 -070092static bool is_debug_runtime() {
93 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
94}
95
David Sehra3b5ab62017-10-25 14:27:29 -070096static bool is_debuggable_build() {
97 return android::base::GetBoolProperty("ro.debuggable", false);
98}
99
Jeff Sharkey90aff262016-12-12 14:28:24 -0700100static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800101 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700102 if (ufd.get() < 0) {
103 if (errno != ENOENT) {
104 PLOG(WARNING) << "Could not open profile " << profile;
105 return false;
106 } else {
107 // Nothing to clear. That's ok.
108 return true;
109 }
110 }
111
112 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
113 if (errno != EWOULDBLOCK) {
114 PLOG(WARNING) << "Error locking profile " << profile;
115 }
116 // This implies that the app owning this profile is running
117 // (and has acquired the lock).
118 //
119 // If we can't acquire the lock bail out since clearing is useless anyway
120 // (the app will write again to the profile).
121 //
122 // Note:
123 // This does not impact the this is not an issue for the profiling correctness.
124 // In case this is needed because of an app upgrade, profiles will still be
125 // eventually cleared by the app itself due to checksum mismatch.
126 // If this is needed because profman advised, then keeping the data around
127 // until the next run is again not an issue.
128 //
129 // If the app attempts to acquire a lock while we've held one here,
130 // it will simply skip the current write cycle.
131 return false;
132 }
133
134 bool truncated = ftruncate(ufd.get(), 0) == 0;
135 if (!truncated) {
136 PLOG(WARNING) << "Could not truncate " << profile;
137 }
138 if (flock(ufd.get(), LOCK_UN) != 0) {
139 PLOG(WARNING) << "Error unlocking profile " << profile;
140 }
141 return truncated;
142}
143
Calin Juravle114f0812017-03-08 19:05:07 -0800144// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800145// The location is the profile name for primary apks or the dex path for secondary dex files.
146static bool clear_reference_profile(const std::string& package_name, const std::string& location,
147 bool is_secondary_dex) {
148 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700149}
150
Calin Juravle114f0812017-03-08 19:05:07 -0800151// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800152// The location is the profile name for primary apks or the dex path for secondary dex files.
153static bool clear_current_profile(const std::string& package_name, const std::string& location,
154 userid_t user, bool is_secondary_dex) {
155 return clear_profile(create_current_profile_path(user, package_name, location,
156 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700157}
158
Calin Juravle114f0812017-03-08 19:05:07 -0800159// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800160// The location is the profile name for primary apks or the dex path for secondary dex files.
161bool clear_primary_reference_profile(const std::string& package_name,
162 const std::string& location) {
163 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800164}
165
166// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800167// The location is the profile name for primary apks or the dex path for secondary dex files.
168bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700169 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800170 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700171 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
172 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800173 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 }
175 return success;
176}
177
Calin Juravle114f0812017-03-08 19:05:07 -0800178// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800179bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
180 userid_t user) {
181 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800182}
183
Calin Juravlef74a7372019-02-28 20:29:41 -0800184// Determines which binary we should use for execution (the debug or non-debug version).
185// e.g. dex2oatd vs dex2oat
186static const char* select_execution_binary(const char* binary, const char* debug_binary,
187 bool background_job_compile) {
188 return select_execution_binary(
189 binary,
190 debug_binary,
191 background_job_compile,
192 is_debug_runtime(),
193 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
194 is_debuggable_build());
195}
196
197// Determines which binary we should use for execution (the debug or non-debug version).
198// e.g. dex2oatd vs dex2oat
199// This is convenient method which is much easier to test because it doesn't read
200// system properties.
201const char* select_execution_binary(
202 const char* binary,
203 const char* debug_binary,
204 bool background_job_compile,
205 bool is_debug_runtime,
206 bool is_release,
207 bool is_debuggable_build) {
208 // Do not use debug binaries for release candidates (to give more soak time).
209 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
210
211 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
212 // the file is present (it may not be on images with very little space available).
213 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
214
215 return useDebug ? debug_binary : binary;
216}
217
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000218// Namespace for Android Runtime flags applied during boot time.
219static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
220// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000221static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000222
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700223// Phenotype property name for enabling profiling the boot class path.
224static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
225
Calin Juravlef85ddb92020-05-01 14:05:40 -0700226static bool IsBootClassPathProfilingEnable() {
227 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
228 profile_boot_class_path =
229 server_configurable_flags::GetServerConfigurableFlag(
230 RUNTIME_NATIVE_BOOT_NAMESPACE,
231 PROFILE_BOOT_CLASS_PATH,
232 /*default_value=*/ profile_boot_class_path);
233 return profile_boot_class_path == "true";
234}
235
Victor Hsiehcb35a062020-08-13 16:11:13 -0700236static void UnlinkIgnoreResult(const std::string& path) {
237 if (unlink(path.c_str()) < 0) {
238 PLOG(ERROR) << "Failed to unlink " << path;
239 }
240}
241
Jeff Sharkey90aff262016-12-12 14:28:24 -0700242/*
243 * Whether dexopt should use a swap file when compiling an APK.
244 *
245 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
246 * itself, anyways).
247 *
248 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
249 *
250 * Otherwise, return true if this is a low-mem device.
251 *
252 * Otherwise, return default value.
253 */
254static bool kAlwaysProvideSwapFile = false;
255static bool kDefaultProvideSwapFile = true;
256
257static bool ShouldUseSwapFileForDexopt() {
258 if (kAlwaysProvideSwapFile) {
259 return true;
260 }
261
262 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700263 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
264 if (!dex2oat_prop_buf.empty()) {
265 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700266 }
267
268 // Shortcut for default value. This is an implementation optimization for the process sketched
269 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
270 // as low-mem is never returning false. The compiler will optimize this away if it can.
271 if (kDefaultProvideSwapFile) {
272 return true;
273 }
274
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700275 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700276 return true;
277 }
278
279 // Default value must be false here.
280 return kDefaultProvideSwapFile;
281}
282
Richard Uhler76cc0272016-12-08 10:46:35 +0000283static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700284 if (set_to_bg) {
285 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800286 PLOG(ERROR) << "set_sched_policy failed";
287 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700288 }
289 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800290 PLOG(ERROR) << "setpriority failed";
291 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700292 }
293 }
294}
295
Calin Juravlee01f8712021-06-03 18:16:54 -0700296static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
297 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, mode)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800298 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800299 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800300 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800301 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800302 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700303 }
Calin Juravle114f0812017-03-08 19:05:07 -0800304 // Profiles should belong to the app; make sure of that by giving ownership to
305 // the app uid. If we cannot do that, there's no point in returning the fd
306 // since dex2oat/profman will fail with SElinux denials.
307 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000308 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800309 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800310 }
Calin Juravle29591732017-11-20 17:46:19 -0800311 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800312}
313
Calin Juravlee01f8712021-06-03 18:16:54 -0700314static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
Calin Juravle114f0812017-03-08 19:05:07 -0800315 // Do not follow symlinks when opening a profile:
316 // - primary profiles should not contain symlinks in their paths
317 // - secondary dex paths should have been already resolved and validated
318 flags |= O_NOFOLLOW;
319
Calin Juravle29591732017-11-20 17:46:19 -0800320 // Check if we need to create the profile
321 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
322 unique_fd fd;
323 if ((flags & O_CREAT) != 0) {
Calin Juravlee01f8712021-06-03 18:16:54 -0700324 fd = create_profile(uid, profile, flags, mode);
Calin Juravle29591732017-11-20 17:46:19 -0800325 } else {
326 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
327 }
328
Calin Juravle114f0812017-03-08 19:05:07 -0800329 if (fd.get() < 0) {
330 if (errno != ENOENT) {
331 // Profiles might be missing for various reasons. For example, in a
332 // multi-user environment, the profile directory for one user can be created
333 // after we start a merge. In this case the current profile for that user
334 // will not be found.
335 // Also, the secondary dex profiles might be deleted by the app at any time,
336 // so we can't we need to prepare if they are missing.
337 PLOG(ERROR) << "Failed to open profile " << profile;
338 }
339 return invalid_unique_fd();
Calin Juravlee01f8712021-06-03 18:16:54 -0700340 } else {
341 // If we just create the file we need to set its mode because on Android
342 // open has a mask that only allows owner access.
343 if ((flags & O_CREAT) != 0) {
344 if (fchmod(fd.get(), mode) != 0) {
345 PLOG(ERROR) << "Could not set mode " << std::hex << mode << std::dec
346 << " on profile" << profile;
347 // Not a terminal failure.
348 }
349 }
Calin Juravle114f0812017-03-08 19:05:07 -0800350 }
351
Jeff Sharkey90aff262016-12-12 14:28:24 -0700352 return fd;
353}
354
Calin Juravle824a64d2018-01-18 20:23:17 -0800355static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
356 const std::string& location, bool is_secondary_dex) {
357 std::string profile = create_current_profile_path(user, package_name, location,
358 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700359 return open_profile(uid, profile, O_RDONLY, /*mode=*/ 0);
Calin Juravle114f0812017-03-08 19:05:07 -0800360}
361
Calin Juravle824a64d2018-01-18 20:23:17 -0800362static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
363 const std::string& location, bool read_write, bool is_secondary_dex) {
364 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700365 return open_profile(
366 uid,
367 profile,
368 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
369 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
Calin Juravle29591732017-11-20 17:46:19 -0800370}
371
Victor Hsiehcb35a062020-08-13 16:11:13 -0700372static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
373 const std::string& location, bool read_write, bool is_secondary_dex) {
374 std::string profile_path = create_reference_profile_path(package_name, location,
375 is_secondary_dex);
Calin Juravlee01f8712021-06-03 18:16:54 -0700376 unique_fd ufd = open_profile(
377 uid,
378 profile_path,
379 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
380 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
381
Victor Hsiehcb35a062020-08-13 16:11:13 -0700382 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
383 clear_profile(path);
384 });
385}
386
Calin Juravle29591732017-11-20 17:46:19 -0800387static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800388 const std::string& location) {
389 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravlee01f8712021-06-03 18:16:54 -0700390 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
Calin Juravle114f0812017-03-08 19:05:07 -0800391}
392
Calin Juravle824a64d2018-01-18 20:23:17 -0800393static void open_profile_files(uid_t uid, const std::string& package_name,
394 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800395 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700396 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800397 *reference_profile_fd = open_reference_profile(uid, package_name, location,
398 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700399
Calin Juravle114f0812017-03-08 19:05:07 -0800400 // For secondary dex files, we don't really need the user but we use it for sanity checks.
401 // Note: the user owning the dex file should be the current user.
402 std::vector<userid_t> users;
403 if (is_secondary_dex){
404 users.push_back(multiuser_get_user_id(uid));
405 } else {
406 users = get_known_users(/*volume_uuid*/ nullptr);
407 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700408 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800409 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
410 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700411 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800412 if (profile_fd.get() >= 0) {
413 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700414 }
415 }
416}
417
Calin Juravle76561322019-11-14 09:08:52 -0800418static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
419static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
Calin Juravle3b758282021-06-08 08:04:52 -0700420static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
Calin Juravle76561322019-11-14 09:08:52 -0800421static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
422static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
423static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
424static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Calin Juravle3b758282021-06-08 08:04:52 -0700425static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700426
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800427class RunProfman : public ExecVHelper {
428 public:
429 void SetupArgs(const std::vector<unique_fd>& profile_fds,
430 const unique_fd& reference_profile_fd,
431 const std::vector<unique_fd>& apk_fds,
432 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800433 bool copy_and_update,
434 bool for_snapshot,
435 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800436
437 // TODO(calin): Assume for now we run in the bg compile job (which is in
438 // most of the invocation). With the current data flow, is not very easy or
439 // clean to discover this in RunProfman (it will require quite a messy refactoring).
440 const char* profman_bin = select_execution_binary(
441 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700442
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800443 if (copy_and_update) {
444 CHECK_EQ(1u, profile_fds.size());
445 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000446 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800447 if (reference_profile_fd != -1) {
448 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000449 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800450
451 for (const unique_fd& fd : profile_fds) {
452 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
453 }
454
455 for (const unique_fd& fd : apk_fds) {
456 AddArg("--apk-fd=" + std::to_string(fd.get()));
457 }
458
459 for (const std::string& dex_location : dex_locations) {
460 AddArg("--dex-location=" + dex_location);
461 }
462
463 if (copy_and_update) {
464 AddArg("--copy-and-update-profile-key");
465 }
466
Calin Juravle78728f32019-11-08 17:55:46 -0800467 if (for_snapshot) {
468 AddArg("--force-merge");
469 }
470
471 if (for_boot_image) {
472 AddArg("--boot-image-merge");
473 }
474
yawannga27559e2020-11-13 19:17:44 +0000475 // The percent won't exceed 100, otherwise, don't set it and use the
476 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000477 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000478 "dalvik.vm.bgdexopt.new-classes-percent",
479 /*default*/std::numeric_limits<uint32_t>::max());
480 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000481 AddArg("--min-new-classes-percent-change=" +
482 std::to_string(min_new_classes_percent_change));
483 }
484
yawannga27559e2020-11-13 19:17:44 +0000485 // The percent won't exceed 100, otherwise, don't set it and use the
486 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000487 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000488 "dalvik.vm.bgdexopt.new-methods-percent",
489 /*default*/std::numeric_limits<uint32_t>::max());
490 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000491 AddArg("--min-new-methods-percent-change=" +
492 std::to_string(min_new_methods_percent_change));
493 }
494
Orion Hodson5f6b3ad2021-07-01 12:12:40 +0100495 // On-device signing related. odsign sets the system property odsign.verification.success if
496 // AOT artifacts have the expected signatures.
497 const bool trust_art_apex_data_files =
498 ::android::base::GetBoolProperty("odsign.verification.success", false);
499 if (!trust_art_apex_data_files) {
500 AddRuntimeArg("-Xdeny-art-apex-data-files");
501 }
502
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800503 // Do not add after dex2oat_flags, they should override others for debugging.
504 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800505 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700506
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800507 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
508 const unique_fd& reference_profile_fd,
509 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800510 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
511 bool for_snapshot = false,
512 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800513 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800514 reference_profile_fd,
515 apk_fds,
516 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800517 /*copy_and_update=*/ false,
518 for_snapshot,
519 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800520 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700521
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800522 void SetupCopyAndUpdate(unique_fd&& profile_fd,
523 unique_fd&& reference_profile_fd,
524 unique_fd&& apk_fd,
525 const std::string& dex_location) {
526 // The fds need to stay open longer than the scope of the function, so put them into a local
527 // variable vector.
528 profiles_fd_.push_back(std::move(profile_fd));
529 apk_fds_.push_back(std::move(apk_fd));
530 reference_profile_fd_ = std::move(reference_profile_fd);
531 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800532 SetupArgs(profiles_fd_,
533 reference_profile_fd_,
534 apk_fds_,
535 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800536 /*copy_and_update=*/true,
537 /*for_snapshot*/false,
538 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800539 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000540
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800541 void SetupDump(const std::vector<unique_fd>& profiles_fd,
542 const unique_fd& reference_profile_fd,
543 const std::vector<std::string>& dex_locations,
544 const std::vector<unique_fd>& apk_fds,
545 const unique_fd& output_fd) {
546 AddArg("--dump-only");
547 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800548 SetupArgs(profiles_fd,
549 reference_profile_fd,
550 apk_fds,
551 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800552 /*copy_and_update=*/false,
553 /*for_snapshot*/false,
554 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800555 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000556
Victor Hsiehc9821f12020-08-07 11:32:29 -0700557 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800558 void Exec() {
559 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
560 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000561
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800562 private:
563 unique_fd reference_profile_fd_;
564 std::vector<unique_fd> profiles_fd_;
565 std::vector<unique_fd> apk_fds_;
566};
Mathieu Chartier31636522018-11-09 23:53:07 +0000567
Calin Juravle3b758282021-06-08 08:04:52 -0700568static int analyze_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800569 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800570 std::vector<unique_fd> profiles_fd;
571 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800572 open_profile_files(uid, package_name, location, is_secondary_dex,
573 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800574 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700575 // Skip profile guided compilation because no profiles were found.
576 // Or if the reference profile info couldn't be opened.
Calin Juravle3b758282021-06-08 08:04:52 -0700577 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700578 }
579
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800580 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700581 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
582 const std::vector<std::string>& dex_locations = std::vector<std::string>();
583 profman_merge.SetupMerge(
584 profiles_fd,
585 reference_profile_fd,
586 apk_fds,
587 dex_locations,
588 /* for_snapshot= */ false,
589 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700590 pid_t pid = fork();
591 if (pid == 0) {
592 /* child -- drop privileges before continuing */
593 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800594 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700595 }
596 /* parent */
597 int return_code = wait_child(pid);
598 bool need_to_compile = false;
Calin Juravle3b758282021-06-08 08:04:52 -0700599 bool empty_profiles = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700600 bool should_clear_current_profiles = false;
601 bool should_clear_reference_profile = false;
602 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800603 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700604 } else {
605 return_code = WEXITSTATUS(return_code);
606 switch (return_code) {
607 case PROFMAN_BIN_RETURN_CODE_COMPILE:
608 need_to_compile = true;
609 should_clear_current_profiles = true;
610 should_clear_reference_profile = false;
611 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700612 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
Jeff Sharkey90aff262016-12-12 14:28:24 -0700613 need_to_compile = false;
614 should_clear_current_profiles = false;
615 should_clear_reference_profile = false;
616 break;
Calin Juravle3b758282021-06-08 08:04:52 -0700617 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
618 need_to_compile = false;
619 empty_profiles = true;
620 should_clear_current_profiles = false;
621 should_clear_reference_profile = false;
622 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700623 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800624 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700625 need_to_compile = false;
626 should_clear_current_profiles = true;
627 should_clear_reference_profile = true;
628 break;
629 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
630 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
631 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800632 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 need_to_compile = false;
634 should_clear_current_profiles = false;
635 should_clear_reference_profile = false;
636 break;
Calin Juravle76561322019-11-14 09:08:52 -0800637 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
638 need_to_compile = false;
639 should_clear_current_profiles = true;
640 should_clear_reference_profile = true;
641 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700642 default:
643 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800644 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800645 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646 need_to_compile = false;
647 should_clear_current_profiles = true;
648 should_clear_reference_profile = true;
649 break;
650 }
651 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800652
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800654 if (is_secondary_dex) {
655 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800656 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
657 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800658 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800659 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800660 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 }
662 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800663 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664 }
Calin Juravle3b758282021-06-08 08:04:52 -0700665 int result = 0;
666 if (need_to_compile) {
667 result = PROFILES_ANALYSIS_OPTIMIZE;
668 } else if (empty_profiles) {
669 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
670 } else {
671 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
672 }
673 return result;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700674}
675
Calin Juravle114f0812017-03-08 19:05:07 -0800676// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle3b758282021-06-08 08:04:52 -0700677// The analysis is done for a single profile name (which corresponds to a single code path).
678//
679// Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
680// that makes it worth to recompile the package.
681// If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
682// merged into the reference profiles accessible with open_reference_profile().
683//
684// Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
685// As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
686// empty.
687int analyze_primary_profiles(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800688 const std::string& profile_name) {
689 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800690}
691
Calin Juravle408cd4a2018-01-20 23:34:18 -0800692bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
693 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800694 std::vector<unique_fd> profile_fds;
695 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800696 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
697 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700698
Calin Juravle408cd4a2018-01-20 23:34:18 -0800699 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800700 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800702 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700703 const bool has_profiles = !profile_fds.empty();
704
705 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800706 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 return false;
708 }
709
Calin Juravle114f0812017-03-08 19:05:07 -0800710 unique_fd output_fd(open(out_file_name.c_str(),
711 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800713 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700714 return false;
715 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800716
Jeff Sharkey90aff262016-12-12 14:28:24 -0700717 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800718 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800719 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
720 if (apk_fd == -1) {
721 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
722 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700723 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700724 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800725 apk_fds.push_back(std::move(apk_fd));
726
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800728 RunProfman profman_dump;
729 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700730 pid_t pid = fork();
731 if (pid == 0) {
732 /* child -- drop privileges before continuing */
733 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800734 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735 }
736 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700737 int return_code = wait_child(pid);
738 if (!WIFEXITED(return_code)) {
739 LOG(WARNING) << "profman failed for package " << pkgname << ": "
740 << return_code;
741 return false;
742 }
743 return true;
744}
745
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700746bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800747 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700748 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
749 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800750 package_name,
751 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700752 /*read_write*/ true,
753 /*secondary*/ false));
754 if (in_fd.get() < 0) {
755 PLOG(WARNING) << "Could not open profile " << system_profile;
756 return false;
757 }
758 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800759 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700760 return false;
761 }
762
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700763 // As a security measure we want to write the profile information with the reduced capabilities
764 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700765 pid_t pid = fork();
766 if (pid == 0) {
767 /* child -- drop privileges before continuing */
768 drop_capabilities(packageUid);
769
770 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
771 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200772 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
773 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700774 }
775 // This implies that the app owning this profile is running
776 // (and has acquired the lock).
777 //
778 // The app never acquires the lock for the reference profiles of primary apks.
779 // Only dex2oat from installd will do that. Since installd is single threaded
780 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200781 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
782 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700783 return false;
784 }
785
786 bool truncated = ftruncate(out_fd.get(), 0) == 0;
787 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200788 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
789 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700790 }
791
792 // Copy over data.
793 static constexpr size_t kBufferSize = 4 * 1024;
794 char buffer[kBufferSize];
795 while (true) {
796 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
797 if (bytes == 0) {
798 break;
799 }
800 write(out_fd.get(), buffer, bytes);
801 }
802 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200803 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
804 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700805 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700806 // Use _exit since we don't want to run the global destructors in the child.
807 // b/62597429
808 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700809 }
810 /* parent */
811 int return_code = wait_child(pid);
812 return return_code == 0;
813}
814
Jeff Sharkey90aff262016-12-12 14:28:24 -0700815static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
816 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
817 if (EndsWith(oat_path, ".dex")) {
818 std::string new_path = oat_path;
819 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800820 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821 return new_path;
822 }
823
824 // An odex entry. Not that this may not be an extension, e.g., in the OTA
825 // case (where the base name will have an extension for the B artifact).
826 size_t odex_pos = oat_path.rfind(".odex");
827 if (odex_pos != std::string::npos) {
828 std::string new_path = oat_path;
829 new_path.replace(odex_pos, strlen(".odex"), new_ext);
830 CHECK_NE(new_path.find(new_ext), std::string::npos);
831 return new_path;
832 }
833
834 // Don't know how to handle this.
835 return "";
836}
837
838// Translate the given oat path to an art (app image) path. An empty string
839// denotes an error.
840static std::string create_image_filename(const std::string& oat_path) {
841 return replace_file_extension(oat_path, ".art");
842}
843
844// Translate the given oat path to a vdex path. An empty string denotes an error.
845static std::string create_vdex_filename(const std::string& oat_path) {
846 return replace_file_extension(oat_path, ".vdex");
847}
848
Jeff Sharkey90aff262016-12-12 14:28:24 -0700849static int open_output_file(const char* file_name, bool recreate, int permissions) {
850 int flags = O_RDWR | O_CREAT;
851 if (recreate) {
852 if (unlink(file_name) < 0) {
853 if (errno != ENOENT) {
854 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
855 }
856 }
857 flags |= O_EXCL;
858 }
859 return open(file_name, flags, permissions);
860}
861
Calin Juravle2289c0a2017-02-15 12:44:14 -0800862static bool set_permissions_and_ownership(
863 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
864 // Primary apks are owned by the system. Secondary dex files are owned by the app.
865 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700866 if (fchmod(fd,
867 S_IRUSR|S_IWUSR|S_IRGRP |
868 (is_public ? S_IROTH : 0)) < 0) {
869 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
870 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800871 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700872 ALOGE("installd cannot chown '%s' during dexopt\n", path);
873 return false;
874 }
875 return true;
876}
877
878static bool IsOutputDalvikCache(const char* oat_dir) {
879 // InstallerConnection.java (which invokes installd) transforms Java null arguments
880 // into '!'. Play it safe by handling it both.
881 // TODO: ensure we never get null.
882 // TODO: pass a flag instead of inferring if the output is dalvik cache.
883 return oat_dir == nullptr || oat_dir[0] == '!';
884}
885
Calin Juravled23dee72017-07-06 16:29:11 -0700886// Best-effort check whether we can fit the the path into our buffers.
887// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
888// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
889// extension to the cache path (5 bytes).
890// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
891static bool validate_dex_path_size(const std::string& dex_path) {
892 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
893 LOG(ERROR) << "dex_path too long: " << dex_path;
894 return false;
895 }
896 return true;
897}
898
Jeff Sharkey90aff262016-12-12 14:28:24 -0700899static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800900 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700901 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 return false;
903 }
904
905 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800906 // Oat dirs for secondary dex files are already validated.
907 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700908 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
909 return false;
910 }
911 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
912 return false;
913 }
914 } else {
915 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
916 return false;
917 }
918 }
919 return true;
920}
921
Calin Juravle7a570e82017-01-14 16:23:30 -0800922// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700923UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700924 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100925
Calin Juravle7a570e82017-01-14 16:23:30 -0800926 const std::string image_path = create_image_filename(out_oat_path);
927 if (image_path.empty()) {
928 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700929 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800930 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100931
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700932 // In case there is a stale image, remove it now. Ignore any error.
933 unlink(image_path.c_str());
934
935 // Not enabled, exit.
936 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700937 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100938 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700939 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
940 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700941 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800942 }
943 // Recreate is true since we do not want to modify a mapped image. If the app is
944 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -0700945 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -0800946 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -0700947 image_path,
948 UnlinkIgnoreResult);
949 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800950 // Could not create application image file. Go on since we can compile without it.
951 LOG(ERROR) << "installd could not create '" << image_path
952 << "' for image file during dexopt";
953 // If we have a valid image file path but no image fd, explicitly erase the image file.
954 if (unlink(image_path.c_str()) < 0) {
955 if (errno != ENOENT) {
956 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
957 }
958 }
959 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -0700960 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800961 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -0700962 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -0800963 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964
Victor Hsiehcb35a062020-08-13 16:11:13 -0700965 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -0800966}
967
968// Creates the dexopt swap file if necessary and return its fd.
969// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700970unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800971 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800972 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -0800973 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700974 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800975 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600976 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -0800977 if (swap_fd.get() < 0) {
978 // Could not create swap file. Optimistically go on and hope that we can compile
979 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600980 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -0800981 } else {
982 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600983 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800984 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
985 }
986 }
987 return swap_fd;
988}
989
990// Opens the reference profiles if needed.
991// 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 -0700992UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000993 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -0800994 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +0000995 // If we are not profile guided compilation, or we are compiling system server
996 // do not bother to open the profiles; we won't be using them.
997 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700998 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +0000999 }
1000
1001 // If this is a secondary dex path which is public do not open the profile.
1002 // We cannot compile public secondary dex paths with profiles. That's because
1003 // it will expose how the dex files are used by their owner.
1004 //
1005 // Note that the PackageManager is responsible to set the is_public flag for
1006 // primary apks and we do not check it here. In some cases, e.g. when
1007 // compiling with a public profile from the .dm file the PackageManager will
1008 // set is_public toghether with the profile guided compilation.
1009 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001010 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001011 }
Calin Juravle114f0812017-03-08 19:05:07 -08001012
1013 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001014 std::string location;
1015 if (is_secondary_dex) {
1016 location = dex_path;
1017 } else {
1018 if (profile_name == nullptr) {
1019 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001020 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001021 } else {
1022 location = profile_name;
1023 }
1024 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001025 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
1026 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001027}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001028
Victor Hsiehcb35a062020-08-13 16:11:13 -07001029// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1030// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001031bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001032 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -07001033 bool profile_guided, UniqueFile* in_vdex_wrapper,
1034 UniqueFile* out_vdex_wrapper) {
1035 CHECK(in_vdex_wrapper != nullptr);
1036 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001037 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1038 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001039 char in_odex_path[PKG_PATH_MAX];
1040 int dexopt_action = abs(dexopt_needed);
1041 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001042
1043 // Infer the name of the output VDEX.
1044 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1045 if (out_vdex_path_str.empty()) {
1046 return false;
1047 }
1048
1049 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001050 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001051 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1052 const char* path = nullptr;
1053 if (is_odex_location) {
1054 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1055 path = in_odex_path;
1056 } else {
1057 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001058 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001059 }
1060 } else {
1061 path = out_oat_path;
1062 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001063 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001064 if (in_vdex_path_str.empty()) {
1065 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001066 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001067 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001068 // We can update in place when all these conditions are met:
1069 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1070 // on /system typically cannot be updated in place).
1071 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1072 // cannot be currently used by a running process.
1073 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1074 // different vdex files to operate.
1075 update_vdex_in_place =
1076 (in_vdex_path_str == out_vdex_path_str) &&
1077 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1078 !profile_guided;
1079 if (update_vdex_in_place) {
1080 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001081 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1082 in_vdex_path_str);
1083 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001084 // If we failed to open the file, we cannot update it in place.
1085 update_vdex_in_place = false;
1086 }
1087 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001088 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1089 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001090 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001091 }
1092
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001093 // If we are updating the vdex in place, we do not need to recreate a vdex,
1094 // and can use the same existing one.
1095 if (update_vdex_in_place) {
1096 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1097 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001098 out_vdex_wrapper->reset(
1099 in_vdex_wrapper->fd(),
1100 out_vdex_path_str,
1101 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001102 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1103 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001104 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001105 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001106 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001107 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001108 out_vdex_path_str,
1109 UnlinkIgnoreResult);
1110 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001111 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1112 return false;
1113 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001114 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001115 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001116 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001117 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1118 return false;
1119 }
1120
1121 // If we got here we successfully opened the vdex files.
1122 return true;
1123}
1124
1125// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001126UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1127 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1128 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001129 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001130 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001131 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001132 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001133 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001134 out_oat_path,
1135 UnlinkIgnoreResult);
1136 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001137 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001138 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001139 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001141 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001142 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001143 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001144}
1145
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001146// Creates RDONLY fds for oat and vdex files, if exist.
1147// Returns false if it fails to create oat out path for the given apk path.
1148// Note that the method returns true even if the files could not be opened.
1149bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1150 const std::string& oat_dir,
1151 const std::string& instruction_set,
1152 bool is_secondary_dex,
1153 unique_fd* oat_file_fd,
1154 unique_fd* vdex_file_fd) {
1155 char oat_path[PKG_PATH_MAX];
1156 if (!create_oat_out_path(apk_path.c_str(),
1157 instruction_set.c_str(),
1158 oat_dir.c_str(),
1159 is_secondary_dex,
1160 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001161 LOG(ERROR) << "Could not create oat out path for "
1162 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001163 return false;
1164 }
1165 oat_file_fd->reset(open(oat_path, O_RDONLY));
1166 if (oat_file_fd->get() < 0) {
1167 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1168 }
1169
1170 std::string vdex_filename = create_vdex_filename(oat_path);
1171 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1172 if (vdex_file_fd->get() < 0) {
1173 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1174 }
1175
1176 return true;
1177}
1178
Calin Juravle80a21252017-01-17 14:43:25 -08001179// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001180// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1181// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1182// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001183class RunDexoptAnalyzer : public ExecVHelper {
1184 public:
1185 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001186 int vdex_fd,
1187 int oat_fd,
1188 int zip_fd,
1189 const std::string& instruction_set,
1190 const std::string& compiler_filter,
Calin Juravle3b758282021-06-08 08:04:52 -07001191 int profile_analysis_result,
David Brazdil4f6027a2019-03-19 11:44:21 +00001192 bool downgrade,
1193 const char* class_loader_context,
1194 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001195 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001196
1197 // We always run the analyzer in the background job.
1198 const char* dexoptanalyzer_bin = select_execution_binary(
1199 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001200
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001201 std::string dex_file_arg = "--dex-file=" + dex_file;
1202 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1203 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1204 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1205 std::string isa_arg = "--isa=" + instruction_set;
1206 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle3b758282021-06-08 08:04:52 -07001207 std::string profile_analysis_arg = "--profile-analysis-result="
1208 + std::to_string(profile_analysis_result);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001209 const char* downgrade_flag = "--downgrade";
1210 std::string class_loader_context_arg = "--class-loader-context=";
1211 if (class_loader_context != nullptr) {
1212 class_loader_context_arg += class_loader_context;
1213 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001214 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1215 if (!class_loader_context_fds.empty()) {
1216 class_loader_context_fds_arg += class_loader_context_fds;
1217 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001218
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001219 // program name, dex file, isa, filter
1220 AddArg(dex_file_arg);
1221 AddArg(isa_arg);
1222 AddArg(compiler_filter_arg);
1223 if (oat_fd >= 0) {
1224 AddArg(oat_fd_arg);
1225 }
1226 if (vdex_fd >= 0) {
1227 AddArg(vdex_fd_arg);
1228 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001229 AddArg(zip_fd_arg);
Calin Juravle3b758282021-06-08 08:04:52 -07001230 AddArg(profile_analysis_arg);
1231
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001232 if (downgrade) {
1233 AddArg(downgrade_flag);
1234 }
1235 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001236 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001237 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001238 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001239 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001240 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001241
Orion Hodson5f6b3ad2021-07-01 12:12:40 +01001242 // On-device signing related. odsign sets the system property odsign.verification.success if
1243 // AOT artifacts have the expected signatures.
1244 const bool trust_art_apex_data_files =
1245 ::android::base::GetBoolProperty("odsign.verification.success", false);
1246 if (!trust_art_apex_data_files) {
1247 AddRuntimeArg("-Xdeny-art-apex-data-files");
1248 }
1249
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001250 PrepareArgs(dexoptanalyzer_bin);
1251 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001252
1253 // Dexoptanalyzer mode which flattens the given class loader context and
1254 // prints a list of its dex files in that flattened order.
1255 RunDexoptAnalyzer(const char* class_loader_context) {
1256 CHECK(class_loader_context != nullptr);
1257
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);
1261
1262 AddArg("--flatten-class-loader-context");
1263 AddArg(std::string("--class-loader-context=") + class_loader_context);
1264 PrepareArgs(dexoptanalyzer_bin);
1265 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001266};
Calin Juravle80a21252017-01-17 14:43:25 -08001267
1268// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001269static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001270 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001271 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001272 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001273 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001274 return false;
1275 }
Calin Juravle114f0812017-03-08 19:05:07 -08001276 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001277
Calin Juravle80a21252017-01-17 14:43:25 -08001278 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001279 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1280 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001281 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001282 return false;
1283 }
1284
1285 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001286 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001287
Calin Juravle7d765462017-09-04 15:57:10 -07001288 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001289 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001290 return false;
1291 }
1292
1293 return true;
1294}
1295
Calin Juravle7d765462017-09-04 15:57:10 -07001296// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1297// secondary dex files. This return codes are returned by the child process created for
1298// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001299
Andreas Gampe194fe422018-02-28 20:16:19 -08001300enum DexoptAnalyzerSkipCodes {
1301 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001302 // Specific errors are encoded in the name.
1303 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1304 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1305 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1306 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1307 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001308 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001309 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001310};
Calin Juravle7d765462017-09-04 15:57:10 -07001311
1312// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001313// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1314// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001315// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1316// of dexoptanalyzer.
1317static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001318 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001319 // The result values are defined in dexoptanalyzer.
1320 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001321 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001322 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001323 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001324 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001325 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001326 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001327 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001328 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001329 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1330 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001331 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1332 " Expected odex file status for secondary dex %s"
1333 " : dexoptanalyzer result=%d",
1334 dex_path.c_str(),
1335 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001336 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001337 }
1338
1339 // Use a second switch for enum switch-case analysis.
1340 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001341 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001342 // If the file does not exist there's no need for dexopt.
1343 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1344 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001345
1346 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1347 *error_msg = "Dexoptanalyzer path validation failed";
1348 return false;
1349 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1350 *error_msg = "Dexoptanalyzer open zip failed";
1351 return false;
1352 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1353 *error_msg = "Dexoptanalyzer dir preparation failed";
1354 return false;
1355 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1356 *error_msg = "Dexoptanalyzer open output failed";
1357 return false;
1358 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1359 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001360 return false;
1361 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001362
1363 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1364 dex_path.c_str(),
1365 result);
1366 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001367}
1368
Calin Juravle7d765462017-09-04 15:57:10 -07001369enum SecondaryDexAccess {
1370 kSecondaryDexAccessReadOk = 0,
1371 kSecondaryDexAccessDoesNotExist = 1,
1372 kSecondaryDexAccessPermissionError = 2,
1373 kSecondaryDexAccessIOError = 3
1374};
1375
1376static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1377 // Check if the path exists and can be read. If not, there's nothing to do.
1378 if (access(dex_path.c_str(), R_OK) == 0) {
1379 return kSecondaryDexAccessReadOk;
1380 } else {
1381 if (errno == ENOENT) {
Martijn Coenenfd9ee2e2021-07-12 11:47:39 +02001382 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1383 "Secondary dex does not exist: %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001384 return kSecondaryDexAccessDoesNotExist;
1385 } else {
Martijn Coenenfd9ee2e2021-07-12 11:47:39 +02001386 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1387 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
Calin Juravle7d765462017-09-04 15:57:10 -07001388 return errno == EACCES
1389 ? kSecondaryDexAccessPermissionError
1390 : kSecondaryDexAccessIOError;
1391 }
1392 }
1393}
1394
1395static bool is_file_public(const std::string& filename) {
1396 struct stat file_stat;
1397 if (stat(filename.c_str(), &file_stat) == 0) {
1398 return (file_stat.st_mode & S_IROTH) != 0;
1399 }
1400 return false;
1401}
1402
1403// Create the oat file structure for the secondary dex 'dex_path' and assign
1404// the individual path component to the 'out_' parameters.
1405static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001406 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001407 size_t dirIndex = dex_path.rfind('/');
1408 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001409 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001410 return false;
1411 }
1412 // TODO(calin): we have similar computations in at lest 3 other places
1413 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1414 // using string append.
1415 std::string apk_dir = dex_path.substr(0, dirIndex);
1416 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1417 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1418
1419 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1420 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001421 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001422 return false;
1423 }
1424 return true;
1425}
1426
1427// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1428// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001429static bool validate_dexopt_storage_flags(int dexopt_flags,
1430 int* out_storage_flag,
1431 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001432 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1433 *out_storage_flag = FLAG_STORAGE_CE;
1434 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001435 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001436 return false;
1437 }
1438 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1439 *out_storage_flag = FLAG_STORAGE_DE;
1440 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001441 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001442 return false;
1443 }
1444 return true;
1445}
1446
David Brazdil4f6027a2019-03-19 11:44:21 +00001447static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1448 /* out */ std::vector<std::string>* context_dex_paths) {
1449 if (class_loader_context == nullptr) {
1450 return true;
1451 }
1452
1453 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1454
1455 // Pipe to get the hash result back from our child process.
1456 unique_fd pipe_read, pipe_write;
1457 if (!Pipe(&pipe_read, &pipe_write)) {
1458 PLOG(ERROR) << "Failed to create pipe";
1459 return false;
1460 }
1461
1462 pid_t pid = fork();
1463 if (pid == 0) {
1464 // child -- drop privileges before continuing.
1465 drop_capabilities(uid);
1466
1467 // Route stdout to `pipe_write`
1468 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1469 pipe_write.reset();
1470 pipe_read.reset();
1471
1472 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1473 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1474 }
1475
1476 /* parent */
1477 pipe_write.reset();
1478
1479 std::string str_dex_paths;
1480 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1481 PLOG(ERROR) << "Failed to read from pipe";
1482 return false;
1483 }
1484 pipe_read.reset();
1485
1486 int return_code = wait_child(pid);
1487 if (!WIFEXITED(return_code)) {
1488 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1489 return false;
1490 }
1491
1492 constexpr int kFlattenClassLoaderContextSuccess = 50;
1493 return_code = WEXITSTATUS(return_code);
1494 if (return_code != kFlattenClassLoaderContextSuccess) {
1495 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1496 return false;
1497 }
1498
1499 if (!str_dex_paths.empty()) {
1500 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1501 }
1502 return true;
1503}
1504
1505static int open_dex_paths(const std::vector<std::string>& dex_paths,
1506 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1507 for (const std::string& dex_path : dex_paths) {
1508 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1509 if (zip_fds->back().get() < 0) {
1510 *error_msg = StringPrintf(
1511 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1512 if (errno == ENOENT) {
1513 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1514 } else {
1515 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1516 }
1517 }
1518 }
1519 return 0;
1520}
1521
1522static std::string join_fds(const std::vector<unique_fd>& fds) {
1523 std::stringstream ss;
1524 bool is_first = true;
1525 for (const unique_fd& fd : fds) {
1526 if (is_first) {
1527 is_first = false;
1528 } else {
1529 ss << ":";
1530 }
1531 ss << fd.get();
1532 }
1533 return ss.str();
1534}
1535
Calin Juravlec9eab382017-01-25 01:17:17 -08001536// Processes the dex_path as a secondary dex files and return true if the path dex file should
Calin Juravle80a21252017-01-17 14:43:25 -08001537// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1538// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001539// When returning true, the output parameters will be:
1540// - is_public_out: whether or not the oat file should not be made public
1541// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1542// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001543static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001544 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001545 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001546 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001547 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001548 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001549 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001550 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1551 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001552 return false;
1553 }
Calin Juravle7d765462017-09-04 15:57:10 -07001554 // Compute the oat dir as it's not easy to extract it from the child computation.
1555 char oat_path[PKG_PATH_MAX];
1556 char oat_dir[PKG_PATH_MAX];
1557 char oat_isa_dir[PKG_PATH_MAX];
1558 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001559 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1560 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001561 return false;
1562 }
Calin Juravle7d765462017-09-04 15:57:10 -07001563 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001564
Calin Juravle80a21252017-01-17 14:43:25 -08001565 pid_t pid = fork();
1566 if (pid == 0) {
1567 // child -- drop privileges before continuing.
1568 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001569
1570 // Validate the path structure.
1571 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001572 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1573 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001574 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001575 }
1576
1577 // Open the dex file.
1578 unique_fd zip_fd;
1579 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1580 if (zip_fd.get() < 0) {
1581 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001582 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001583 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001584 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001585 }
1586 }
1587
David Brazdil4f6027a2019-03-19 11:44:21 +00001588 // Open class loader context dex files.
1589 std::vector<unique_fd> context_zip_fds;
1590 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1591 if (open_dex_paths_rc != 0) {
1592 _exit(open_dex_paths_rc);
1593 }
1594
Calin Juravle7d765462017-09-04 15:57:10 -07001595 // Prepare the oat directories.
1596 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001597 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001598 }
1599
1600 // Open the vdex/oat files if any.
1601 unique_fd oat_file_fd;
1602 unique_fd vdex_file_fd;
1603 if (!maybe_open_oat_and_vdex_file(dex_path,
1604 *oat_dir_out,
1605 instruction_set,
1606 true /* is_secondary_dex */,
1607 &oat_file_fd,
1608 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001609 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001610 }
1611
1612 // Analyze profiles.
Calin Juravle3b758282021-06-08 08:04:52 -07001613 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
Calin Juravle824a64d2018-01-18 20:23:17 -08001614 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001615
1616 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001617 // Note that we do not do it before the fork since opening the files is required to happen
1618 // after forking.
1619 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1620 vdex_file_fd.get(),
1621 oat_file_fd.get(),
1622 zip_fd.get(),
1623 instruction_set,
Calin Juravle3b758282021-06-08 08:04:52 -07001624 compiler_filter,
1625 profile_analysis_result,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001626 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001627 class_loader_context,
1628 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001629 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001630 }
1631
1632 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001633 int result = wait_child(pid);
1634 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001635 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1636 dex_path.c_str(),
1637 result);
1638 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001639 return false;
1640 }
1641 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001642 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001643 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1644 result,
1645 dexopt_needed_out,
1646 error_msg);
1647 if (!success) {
1648 LOG(ERROR) << *error_msg;
1649 }
Calin Juravle7d765462017-09-04 15:57:10 -07001650
1651 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1652
Calin Juravle80a21252017-01-17 14:43:25 -08001653 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001654 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1655 // makes the code simpler; force compilation is only needed during tests).
1656 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001657 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001658 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001659 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1660 }
1661
Calin Juravle7d765462017-09-04 15:57:10 -07001662 // Check if we should make the oat file public.
1663 // Note that if the dex file is not public the compiled code cannot be made public.
1664 // It is ok to check this flag outside in the parent process.
1665 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1666
Calin Juravle80a21252017-01-17 14:43:25 -08001667 return success;
1668}
1669
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001670static std::string format_dexopt_error(int status, const char* dex_path) {
1671 if (WIFEXITED(status)) {
1672 int int_code = WEXITSTATUS(status);
1673 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1674 if (code_name != nullptr) {
1675 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1676 }
1677 }
1678 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001679}
1680
Calin Juravlec9eab382017-01-25 01:17:17 -08001681int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001682 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001683 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001684 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001685 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001686 CHECK(pkgname != nullptr);
1687 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001688 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001689 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1690 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001691
Calin Juravled23dee72017-07-06 16:29:11 -07001692 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001693 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001694 return -1;
1695 }
1696
1697 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001698 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1699 class_loader_context);
1700 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001701 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001702 }
1703
Calin Juravleebc8a792017-04-04 20:21:05 -07001704 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001705 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1706 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1707 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001708 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001709 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001710 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001711 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001712 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001713 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001714
1715 // Check if we're dealing with a secondary dex file and if we need to compile it.
1716 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001717 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001718 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001719 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1720 *error_msg = "Failed acquiring context dex paths";
1721 return -1; // We had an error, logged in the process method.
1722 }
1723
Calin Juravlec9eab382017-01-25 01:17:17 -08001724 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001725 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00001726 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001727 oat_dir = oat_dir_str.c_str();
1728 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1729 return 0; // Nothing to do, report success.
1730 }
1731 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001732 if (error_msg->empty()) { // TODO: Make this a CHECK.
1733 *error_msg = "Failed processing secondary.";
1734 }
Calin Juravle80a21252017-01-17 14:43:25 -08001735 return -1; // We had an error, logged in the process method.
1736 }
1737 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001738 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001739 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001740 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1741 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1742 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001743
1744 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001745 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1746 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001747 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1748 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001749 return -1;
1750 }
1751
David Brazdil4f6027a2019-03-19 11:44:21 +00001752 // Open class loader context dex files.
1753 std::vector<unique_fd> context_input_fds;
1754 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1755 LOG(ERROR) << *error_msg;
1756 return -1;
1757 }
1758
Calin Juravle7a570e82017-01-14 16:23:30 -08001759 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001760 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1761 instruction_set, is_secondary_dex);
1762 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001763 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001764 return -1;
1765 }
1766
1767 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001768 UniqueFile in_vdex;
1769 UniqueFile out_vdex;
1770 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1771 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1772 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001773 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001774 return -1;
1775 }
1776
Calin Juravlecb556e32017-04-04 20:22:50 -07001777 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1778 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1779 // fully inherit their parent context).
1780 // Note that for primary apk the oat files are created before, in a separate installd
1781 // call which also does the restorecon. TODO(calin): unify the paths.
1782 if (is_secondary_dex) {
1783 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1784 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001785 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1786 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001787 return -1;
1788 }
1789 }
1790
Jeff Sharkey90aff262016-12-12 14:28:24 -07001791 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001792 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001793
Calin Juravle7a570e82017-01-14 16:23:30 -08001794 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001795 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001796 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001797
Victor Hsiehcb35a062020-08-13 16:11:13 -07001798 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001799 // We don't create an app image without reference profile since there is no speedup from
1800 // loading it in that case and instead will be a small overhead.
1801 generate_app_image = false;
1802 }
1803
1804 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001805 UniqueFile out_image = maybe_open_app_image(
1806 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001807
Victor Hsiehcb35a062020-08-13 16:11:13 -07001808 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001809 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001810 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1811 dex_metadata_path);
1812 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001813 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1814 }
1815 }
1816
Victor Hsieh8948a862020-08-07 11:30:55 -07001817 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1818 RUNTIME_NATIVE_BOOT_NAMESPACE,
1819 ENABLE_JITZYGOTE_IMAGE,
1820 /*default_value=*/ "");
1821 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1822
Victor Hsiehe98e6512020-08-10 15:39:22 -07001823 // Decide whether to use dex2oat64.
1824 bool use_dex2oat64 = false;
1825 // Check whether the device even supports 64-bit ABIs.
1826 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1827 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1828 }
1829 const char* dex2oat_bin = select_execution_binary(
1830 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1831 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1832 background_job_compile);
1833
Victor Hsiehc9821f12020-08-07 11:32:29 -07001834 auto execv_helper = std::make_unique<ExecVHelper>();
1835
Andreas Gampe023b2242018-02-28 16:03:25 -08001836 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001837
Victor Hsiehc9821f12020-08-07 11:32:29 -07001838 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001839 runner.Initialize(out_oat,
1840 out_vdex,
1841 out_image,
1842 in_dex,
1843 in_vdex,
1844 dex_metadata,
1845 reference_profile,
1846 class_loader_context,
1847 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001848 swap_fd.get(),
1849 instruction_set,
1850 compiler_filter,
1851 debuggable,
1852 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001853 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001854 target_sdk_version,
1855 enable_hidden_api_checks,
1856 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001857 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001858 compilation_reason);
1859
Jeff Sharkey90aff262016-12-12 14:28:24 -07001860 pid_t pid = fork();
1861 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001862 // Need to set schedpolicy before dropping privileges
1863 // for cgroup migration. See details at b/175178520.
1864 SetDex2OatScheduling(boot_complete);
1865
Jeff Sharkey90aff262016-12-12 14:28:24 -07001866 /* child -- drop privileges before continuing */
1867 drop_capabilities(uid);
1868
Victor Hsiehcb35a062020-08-13 16:11:13 -07001869 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001870 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1871 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001872 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001873 }
1874
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001875 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001876 } else {
1877 int res = wait_child(pid);
1878 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001879 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001880 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001881 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1882 << std::hex << std::setw(4) << res << ", process failed";
1883 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001884 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001885 }
1886 }
1887
Jeff Sharkey90aff262016-12-12 14:28:24 -07001888 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001889 out_oat.DisableCleanup();
1890 out_vdex.DisableCleanup();
1891 out_image.DisableCleanup();
1892 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001893
1894 return 0;
1895}
1896
Calin Juravlec9eab382017-01-25 01:17:17 -08001897// Try to remove the given directory. Log an error if the directory exists
1898// and is empty but could not be removed.
1899static bool rmdir_if_empty(const char* dir) {
1900 if (rmdir(dir) == 0) {
1901 return true;
1902 }
1903 if (errno == ENOENT || errno == ENOTEMPTY) {
1904 return true;
1905 }
1906 PLOG(ERROR) << "Failed to remove dir: " << dir;
1907 return false;
1908}
1909
1910// Try to unlink the given file. Log an error if the file exists and could not
1911// be unlinked.
1912static bool unlink_if_exists(const std::string& file) {
1913 if (unlink(file.c_str()) == 0) {
1914 return true;
1915 }
1916 if (errno == ENOENT) {
1917 return true;
1918
1919 }
1920 PLOG(ERROR) << "Could not unlink: " << file;
1921 return false;
1922}
1923
Calin Juravle7d765462017-09-04 15:57:10 -07001924enum ReconcileSecondaryDexResult {
1925 kReconcileSecondaryDexExists = 0,
1926 kReconcileSecondaryDexCleanedUp = 1,
1927 kReconcileSecondaryDexValidationError = 2,
1928 kReconcileSecondaryDexCleanUpError = 3,
1929 kReconcileSecondaryDexAccessIOError = 4,
1930};
Calin Juravlec9eab382017-01-25 01:17:17 -08001931
1932// Reconcile the secondary dex 'dex_path' and its generated oat files.
1933// Return true if all the parameters are valid and the secondary dex file was
1934// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1935// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1936// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1937// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1938// Return false if there were errors during processing. In this case
1939// out_secondary_dex_exists will be set to false.
1940bool reconcile_secondary_dex_file(const std::string& dex_path,
1941 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001942 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08001943 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001944 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001945 if (isas.size() == 0) {
1946 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1947 return false;
1948 }
1949
Calin Juravle7d765462017-09-04 15:57:10 -07001950 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1951 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1952 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001953 return false;
1954 }
1955
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001956 // As a security measure we want to unlink art artifacts with the reduced capabilities
1957 // of the package user id. So we fork and drop capabilities in the child.
1958 pid_t pid = fork();
1959 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001960 /* child -- drop privileges before continuing */
1961 drop_capabilities(uid);
1962
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001963 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07001964 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07001965 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001966 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1967 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001968 _exit(kReconcileSecondaryDexValidationError);
1969 }
1970
1971 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1972 switch (access_check) {
1973 case kSecondaryDexAccessDoesNotExist:
1974 // File does not exist. Proceed with cleaning.
1975 break;
1976 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1977 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1978 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1979 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02001980 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1981 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07001982 _exit(kReconcileSecondaryDexValidationError);
1983 }
1984
1985 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001986 char oat_path[PKG_PATH_MAX];
1987 char oat_dir[PKG_PATH_MAX];
1988 char oat_isa_dir[PKG_PATH_MAX];
1989 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001990 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001991 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001992 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001993 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001994 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001995 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001996 }
Calin Juravle51314092017-05-18 15:33:05 -07001997
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001998 // Delete oat/vdex/art files.
1999 result = unlink_if_exists(oat_path) && result;
2000 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2001 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002002
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002003 // Delete profiles.
2004 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002005 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002006 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002007 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002008 result = unlink_if_exists(current_profile) && result;
2009 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002010
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002011 // We upgraded once the location of current profile for secondary dex files.
2012 // Check for any previous left-overs and remove them as well.
2013 std::string old_current_profile = dex_path + ".prof";
2014 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002015
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002016 // Try removing the directories as well, they might be empty.
2017 result = rmdir_if_empty(oat_isa_dir) && result;
2018 result = rmdir_if_empty(oat_dir) && result;
2019 }
Calin Juravle7d765462017-09-04 15:57:10 -07002020 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002021 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2022 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07002023 }
2024 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002025 }
2026
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002027 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002028 if (!WIFEXITED(return_code)) {
2029 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2030 } else {
2031 return_code = WEXITSTATUS(return_code);
2032 }
2033
2034 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2035
2036 switch (return_code) {
2037 case kReconcileSecondaryDexCleanedUp:
2038 case kReconcileSecondaryDexValidationError:
2039 // If we couldn't validate assume the dex file does not exist.
2040 // This will purge the entry from the PM records.
2041 *out_secondary_dex_exists = false;
2042 return true;
2043 case kReconcileSecondaryDexExists:
2044 *out_secondary_dex_exists = true;
2045 return true;
2046 case kReconcileSecondaryDexAccessIOError:
2047 // We had an access IO error.
2048 // Return false so that we can try again.
2049 // The value of out_secondary_dex_exists does not matter in this case and by convention
2050 // is set to false.
2051 *out_secondary_dex_exists = false;
2052 return false;
2053 default:
2054 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2055 *out_secondary_dex_exists = false;
2056 return false;
2057 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002058}
2059
Alan Stokesa25d90c2017-10-16 10:56:00 +01002060// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2061// Returns true if all parameters are valid and the hash successfully computed and stored in
2062// out_secondary_dex_hash.
2063// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2064// the app.
2065// For any other errors (e.g. if any of the parameters are invalid) returns false.
2066bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002067 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002068 std::vector<uint8_t>* out_secondary_dex_hash) {
2069 out_secondary_dex_hash->clear();
2070
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002071 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002072
2073 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2074 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2075 << storage_flag;
2076 return false;
2077 }
2078
2079 // Pipe to get the hash result back from our child process.
2080 unique_fd pipe_read, pipe_write;
2081 if (!Pipe(&pipe_read, &pipe_write)) {
2082 PLOG(ERROR) << "Failed to create pipe";
2083 return false;
2084 }
2085
2086 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2087 // access data the app itself can access.
2088 pid_t pid = fork();
2089 if (pid == 0) {
2090 // child -- drop privileges before continuing
2091 drop_capabilities(uid);
2092 pipe_read.reset();
2093
2094 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002095 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2096 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002097 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002098 }
2099
2100 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2101 if (fd == -1) {
2102 if (errno == EACCES || errno == ENOENT) {
2103 // Not treated as an error.
2104 _exit(0);
2105 }
2106 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002107 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2108 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002109 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002110 }
2111
2112 SHA256_CTX ctx;
2113 SHA256_Init(&ctx);
2114
2115 std::vector<uint8_t> buffer(65536);
2116 while (true) {
2117 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2118 if (bytes_read == 0) {
2119 break;
2120 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002121 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2122 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002123 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002124 }
2125
2126 SHA256_Update(&ctx, buffer.data(), bytes_read);
2127 }
2128
2129 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2130 SHA256_Final(hash.data(), &ctx);
2131 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002132 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002133 }
2134
2135 _exit(0);
2136 }
2137
2138 // parent
2139 pipe_write.reset();
2140
2141 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2142 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2143 out_secondary_dex_hash->clear();
2144 }
2145 return wait_child(pid) == 0;
2146}
2147
Jeff Sharkey90aff262016-12-12 14:28:24 -07002148// Helper for move_ab, so that we can have common failure-case cleanup.
2149static bool unlink_and_rename(const char* from, const char* to) {
2150 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2151 // return a failure.
2152 struct stat s;
2153 if (stat(to, &s) == 0) {
2154 if (!S_ISREG(s.st_mode)) {
2155 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2156 return false;
2157 }
2158 if (unlink(to) != 0) {
2159 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2160 return false;
2161 }
2162 } else {
2163 // This may be a permission problem. We could investigate the error code, but we'll just
2164 // let the rename failure do the work for us.
2165 }
2166
2167 // Try to rename "to" to "from."
2168 if (rename(from, to) != 0) {
2169 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2170 return false;
2171 }
2172 return true;
2173}
2174
2175// Move/rename a B artifact (from) to an A artifact (to).
2176static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2177 // Check whether B exists.
2178 {
2179 struct stat s;
2180 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002181 // Ignore for now. The service calling this isn't smart enough to
2182 // understand lack of artifacts at the moment.
2183 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002184 return false;
2185 }
2186 if (!S_ISREG(s.st_mode)) {
2187 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2188 // Try to unlink, but swallow errors.
2189 unlink(b_path.c_str());
2190 return false;
2191 }
2192 }
2193
2194 // Rename B to A.
2195 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2196 // Delete the b_path so we don't try again (or fail earlier).
2197 if (unlink(b_path.c_str()) != 0) {
2198 PLOG(ERROR) << "Could not unlink " << b_path;
2199 }
2200
2201 return false;
2202 }
2203
2204 return true;
2205}
2206
2207bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2208 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002209 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2210 if (slot_suffix.empty()) {
2211 return false;
2212 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002213
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002214 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2215 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2216 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002217 }
2218
2219 // Validate other inputs.
2220 if (validate_apk_path(apk_path) != 0) {
2221 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2222 return false;
2223 }
2224 if (validate_apk_path(oat_dir) != 0) {
2225 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2226 return false;
2227 }
2228
2229 char a_path[PKG_PATH_MAX];
2230 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2231 return false;
2232 }
2233 const std::string a_vdex_path = create_vdex_filename(a_path);
2234 const std::string a_image_path = create_image_filename(a_path);
2235
2236 // B path = A path + slot suffix.
2237 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2238 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2239 const std::string b_image_path = StringPrintf("%s.%s",
2240 a_image_path.c_str(),
2241 slot_suffix.c_str());
2242
2243 bool success = true;
2244 if (move_ab_path(b_path, a_path)) {
2245 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2246 // Note: we can live without an app image. As such, ignore failure to move the image file.
2247 // If we decide to require the app image, or the app image being moved correctly,
2248 // then change accordingly.
2249 constexpr bool kIgnoreAppImageFailure = true;
2250
2251 if (!a_image_path.empty()) {
2252 if (!move_ab_path(b_image_path, a_image_path)) {
2253 unlink(a_image_path.c_str());
2254 if (!kIgnoreAppImageFailure) {
2255 success = false;
2256 }
2257 }
2258 }
2259 } else {
2260 // Cleanup: delete B image, ignore errors.
2261 unlink(b_image_path.c_str());
2262 success = false;
2263 }
2264 } else {
2265 // Cleanup: delete B image, ignore errors.
2266 unlink(b_vdex_path.c_str());
2267 unlink(b_image_path.c_str());
2268 success = false;
2269 }
2270 return success;
2271}
2272
Calin Juravleea214ad2021-06-11 09:17:20 -07002273int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002274 // Delete the oat/odex file.
2275 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002276 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002277 /*is_secondary_dex*/false, out_path)) {
Calin Juravleea214ad2021-06-11 09:17:20 -07002278 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2279 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002280 }
2281
2282 // In case of a permission failure report the issue. Otherwise just print a warning.
Calin Juravleea214ad2021-06-11 09:17:20 -07002283 auto unlink_and_check = [](const char* path) -> int64_t {
2284 struct stat file_stat;
2285 if (stat(path, &file_stat) != 0) {
2286 if (errno != ENOENT) {
2287 PLOG(ERROR) << "Could not stat " << path;
2288 return -1;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002289 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002290 return 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002291 }
Calin Juravleea214ad2021-06-11 09:17:20 -07002292
2293 if (unlink(path) != 0) {
2294 if (errno != ENOENT) {
2295 PLOG(ERROR) << "Could not unlink " << path;
2296 return -1;
2297 }
2298 }
2299 return static_cast<int64_t>(file_stat.st_size);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002300 };
2301
2302 // Delete the oat/odex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002303 int64_t return_value_oat = unlink_and_check(out_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002304
2305 // Derive and delete the app image.
Calin Juravleea214ad2021-06-11 09:17:20 -07002306 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07002307
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002308 // Derive and delete the vdex file.
Calin Juravleea214ad2021-06-11 09:17:20 -07002309 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002310
Calin Juravleea214ad2021-06-11 09:17:20 -07002311 // Report result
2312 if (return_value_oat == -1
2313 || return_value_art == -1
2314 || return_value_vdex == -1) {
2315 return -1;
2316 }
2317
2318 return return_value_oat + return_value_art + return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002319}
2320
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002321static bool is_absolute_path(const std::string& path) {
2322 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2323 LOG(ERROR) << "Invalid absolute path " << path;
2324 return false;
2325 } else {
2326 return true;
2327 }
2328}
2329
2330static bool is_valid_instruction_set(const std::string& instruction_set) {
2331 // TODO: add explicit whitelisting of instruction sets
2332 if (instruction_set.find('/') != std::string::npos) {
2333 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2334 return false;
2335 } else {
2336 return true;
2337 }
2338}
2339
2340bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2341 const char *apk_path, const char *instruction_set) {
2342 std::string oat_dir_ = oat_dir;
2343 std::string apk_path_ = apk_path;
2344 std::string instruction_set_ = instruction_set;
2345
2346 if (!is_absolute_path(oat_dir_)) return false;
2347 if (!is_absolute_path(apk_path_)) return false;
2348 if (!is_valid_instruction_set(instruction_set_)) return false;
2349
2350 std::string::size_type end = apk_path_.rfind('.');
2351 std::string::size_type start = apk_path_.rfind('/', end);
2352 if (end == std::string::npos || start == std::string::npos) {
2353 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2354 return false;
2355 }
2356
2357 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2358 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2359 const char* res = res_.c_str();
2360 if (strlen(res) >= PKG_PATH_MAX) {
2361 LOG(ERROR) << "Result too large";
2362 return false;
2363 } else {
2364 strlcpy(path, res, PKG_PATH_MAX);
2365 return true;
2366 }
2367}
2368
2369bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2370 const char *instruction_set) {
2371 std::string apk_path_ = apk_path;
2372 std::string instruction_set_ = instruction_set;
2373
2374 if (!is_absolute_path(apk_path_)) return false;
2375 if (!is_valid_instruction_set(instruction_set_)) return false;
2376
2377 std::string::size_type end = apk_path_.rfind('.');
2378 std::string::size_type start = apk_path_.rfind('/', end);
2379 if (end == std::string::npos || start == std::string::npos) {
2380 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2381 return false;
2382 }
2383
2384 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2385 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2386}
2387
2388bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2389 const char *instruction_set) {
2390 std::string src_ = src;
2391 std::string instruction_set_ = instruction_set;
2392
2393 if (!is_absolute_path(src_)) return false;
2394 if (!is_valid_instruction_set(instruction_set_)) return false;
2395
2396 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2397 if (*it == '/') {
2398 *it = '@';
2399 }
2400 }
2401
2402 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2403 + DALVIK_CACHE_POSTFIX;
2404 const char* res = res_.c_str();
2405 if (strlen(res) >= PKG_PATH_MAX) {
2406 LOG(ERROR) << "Result too large";
2407 return false;
2408 } else {
2409 strlcpy(path, res, PKG_PATH_MAX);
2410 return true;
2411 }
2412}
2413
Calin Juravle59f7ab82018-04-27 17:50:23 -07002414bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2415 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002416 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2417 for (const std::string& elem : classpaths_elems) {
2418 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2419 if (fd < 0) {
2420 PLOG(ERROR) << "Could not open classpath elem " << elem;
2421 return false;
2422 } else {
2423 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002424 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002425 }
2426 }
2427 return true;
2428}
2429
2430static bool create_app_profile_snapshot(int32_t app_id,
2431 const std::string& package_name,
2432 const std::string& profile_name,
2433 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002434 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2435
Calin Juravle824a64d2018-01-18 20:23:17 -08002436 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002437 if (snapshot_fd < 0) {
2438 return false;
2439 }
2440
2441 std::vector<unique_fd> profiles_fd;
2442 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002443 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2444 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002445 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2446 return false;
2447 }
2448
2449 profiles_fd.push_back(std::move(reference_profile_fd));
2450
Calin Juravle0d0a4922018-01-23 19:54:11 -08002451 // Open the class paths elements. These will be used to filter out profile data that does
2452 // not belong to the classpath during merge.
2453 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002454 std::vector<std::string> dex_locations;
2455 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002456 return false;
2457 }
2458
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002459 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002460 // This is specifically a snapshot for an app, so don't use boot image profiles.
2461 args.SetupMerge(profiles_fd,
2462 snapshot_fd,
2463 apk_fds,
2464 dex_locations,
2465 /* for_snapshot= */ true,
2466 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002467 pid_t pid = fork();
2468 if (pid == 0) {
2469 /* child -- drop privileges before continuing */
2470 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002471 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002472 }
2473
2474 /* parent */
2475 int return_code = wait_child(pid);
2476 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002477 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002478 return false;
2479 }
2480
Calin Juravle78728f32019-11-08 17:55:46 -08002481 // Verify that profman finished successfully.
2482 int profman_code = WEXITSTATUS(return_code);
2483 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2484 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2485 << ":" << profman_code;
2486 return false;
2487 }
Calin Juravle29591732017-11-20 17:46:19 -08002488 return true;
2489}
2490
Calin Juravle0d0a4922018-01-23 19:54:11 -08002491static bool create_boot_image_profile_snapshot(const std::string& package_name,
2492 const std::string& profile_name,
2493 const std::string& classpath) {
2494 // The reference profile directory for the android package might not be prepared. Do it now.
2495 const std::string ref_profile_dir =
2496 create_primary_reference_profile_package_dir_path(package_name);
2497 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2498 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2499 return false;
2500 }
2501
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002502 // Return false for empty class path since it may otherwise return true below if profiles is
2503 // empty.
2504 if (classpath.empty()) {
2505 PLOG(ERROR) << "Class path is empty";
2506 return false;
2507 }
2508
Calin Juravle0d0a4922018-01-23 19:54:11 -08002509 // Open and create the snapshot profile.
2510 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2511
2512 // Collect all non empty profiles.
2513 // The collection will traverse all applications profiles and find the non empty files.
2514 // This has the potential of inspecting a large number of files and directories (depending
2515 // on the number of applications and users). So there is a slight increase in the chance
2516 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2517 // fail the snapshot and aggregate whatever profile we could open.
2518 //
2519 // The profile snapshot is a best effort based on available data it's ok if some data
2520 // from some apps is missing. It will be counter productive for the snapshot to fail
2521 // because we could not open or read some of the files.
2522 std::vector<std::string> profiles;
2523 if (!collect_profiles(&profiles)) {
2524 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2525 }
2526
2527 // If we have no profiles return early.
2528 if (profiles.empty()) {
2529 return true;
2530 }
2531
2532 // Open the classpath elements. These will be used to filter out profile data that does
2533 // not belong to the classpath during merge.
2534 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002535 std::vector<std::string> dex_locations;
2536 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002537 return false;
2538 }
2539
2540 // If we could not open any files from the classpath return an error.
2541 if (apk_fds.empty()) {
2542 LOG(ERROR) << "Could not open any of the classpath elements.";
2543 return false;
2544 }
2545
2546 // Aggregate the profiles in batches of kAggregationBatchSize.
2547 // We do this to avoid opening a huge a amount of files.
2548 static constexpr size_t kAggregationBatchSize = 10;
2549
Calin Juravle0d0a4922018-01-23 19:54:11 -08002550 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002551 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002552 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
Calin Juravlee01f8712021-06-03 18:16:54 -07002553 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002554 if (fd.get() >= 0) {
2555 profiles_fd.push_back(std::move(fd));
2556 }
2557 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002558
2559 // We aggregate (read & write) into the same fd multiple times in a row.
2560 // We need to reset the cursor every time to ensure we read the whole file every time.
2561 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2562 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2563 return false;
2564 }
2565
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002566 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002567 args.SetupMerge(profiles_fd,
2568 snapshot_fd,
2569 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002570 dex_locations,
2571 /*for_snapshot=*/true,
2572 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002573 pid_t pid = fork();
2574 if (pid == 0) {
2575 /* child -- drop privileges before continuing */
2576 drop_capabilities(AID_SYSTEM);
2577
Calin Juravle59f7ab82018-04-27 17:50:23 -07002578 // The introduction of new access flags into boot jars causes them to
2579 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002580 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002581 }
2582
2583 /* parent */
2584 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002585
Calin Juravle0d0a4922018-01-23 19:54:11 -08002586 if (!WIFEXITED(return_code)) {
2587 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2588 return false;
2589 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002590
2591 // Verify that profman finished successfully.
2592 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002593 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2594 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2595 << ":" << profman_code;
2596 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002597 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002598 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002599
Calin Juravle0d0a4922018-01-23 19:54:11 -08002600 return true;
2601}
2602
2603bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2604 const std::string& profile_name, const std::string& classpath) {
2605 if (app_id == -1) {
2606 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2607 } else {
2608 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2609 }
2610}
2611
Calin Juravlec3b049e2018-01-18 22:32:58 -08002612bool prepare_app_profile(const std::string& package_name,
2613 userid_t user_id,
2614 appid_t app_id,
2615 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002616 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002617 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002618 // Prepare the current profile.
2619 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2620 /*is_secondary_dex*/ false);
2621 uid_t uid = multiuser_get_uid(user_id, app_id);
2622 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2623 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2624 return false;
2625 }
2626
2627 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002628 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002629 return true;
2630 }
2631
2632 // We have a dex metdata. Merge the profile into the reference profile.
2633 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2634 /*read_write*/ true, /*is_secondary_dex*/ false);
2635 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2636 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002637 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2638 if (apk_fd < 0) {
2639 PLOG(ERROR) << "Could not open code path " << code_path;
2640 return false;
2641 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002642
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002643 RunProfman args;
2644 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2645 std::move(ref_profile_fd),
2646 std::move(apk_fd),
2647 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002648 pid_t pid = fork();
2649 if (pid == 0) {
2650 /* child -- drop privileges before continuing */
2651 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2652 drop_capabilities(app_shared_gid);
2653
Calin Juravlef63d4792018-01-30 17:43:34 +00002654 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002655 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002656 }
2657
2658 /* parent */
2659 int return_code = wait_child(pid);
2660 if (!WIFEXITED(return_code)) {
2661 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2662 return false;
2663 }
2664 return true;
2665}
2666
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002667} // namespace installd
2668} // namespace android