blob: f583c9b11e3ea0cdbf410e9e3550ef88feabc36e [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>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070042#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010043#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000045#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070046#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000047#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
50#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080051#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070052#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060053#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070054#include "installd_deps.h"
55#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070056#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070057#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070058#include "utils.h"
59
Victor Hsieh76f19ba2020-08-10 14:37:26 -070060using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070061using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070062using android::base::GetBoolProperty;
63using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000064using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010065using android::base::ReadFully;
66using android::base::StringPrintf;
67using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080068using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070069
70namespace android {
71namespace installd {
72
Andreas Gampefa2dadd2018-02-28 19:52:47 -080073
Calin Juravle114f0812017-03-08 19:05:07 -080074// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
75struct FreeDelete {
76 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
77 void operator()(const void* ptr) const {
78 free(const_cast<void*>(ptr));
79 }
80};
81
82// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
83template <typename T>
84using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
85
Calin Juravle1a0af3b2017-03-09 14:33:33 -080086static unique_fd invalid_unique_fd() {
87 return unique_fd(-1);
88}
89
Andreas Gampe6a9cf722017-07-24 16:49:10 -070090static bool is_debug_runtime() {
91 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
92}
93
David Sehra3b5ab62017-10-25 14:27:29 -070094static bool is_debuggable_build() {
95 return android::base::GetBoolProperty("ro.debuggable", false);
96}
97
Jeff Sharkey90aff262016-12-12 14:28:24 -070098static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080099 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700100 if (ufd.get() < 0) {
101 if (errno != ENOENT) {
102 PLOG(WARNING) << "Could not open profile " << profile;
103 return false;
104 } else {
105 // Nothing to clear. That's ok.
106 return true;
107 }
108 }
109
110 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
111 if (errno != EWOULDBLOCK) {
112 PLOG(WARNING) << "Error locking profile " << profile;
113 }
114 // This implies that the app owning this profile is running
115 // (and has acquired the lock).
116 //
117 // If we can't acquire the lock bail out since clearing is useless anyway
118 // (the app will write again to the profile).
119 //
120 // Note:
121 // This does not impact the this is not an issue for the profiling correctness.
122 // In case this is needed because of an app upgrade, profiles will still be
123 // eventually cleared by the app itself due to checksum mismatch.
124 // If this is needed because profman advised, then keeping the data around
125 // until the next run is again not an issue.
126 //
127 // If the app attempts to acquire a lock while we've held one here,
128 // it will simply skip the current write cycle.
129 return false;
130 }
131
132 bool truncated = ftruncate(ufd.get(), 0) == 0;
133 if (!truncated) {
134 PLOG(WARNING) << "Could not truncate " << profile;
135 }
136 if (flock(ufd.get(), LOCK_UN) != 0) {
137 PLOG(WARNING) << "Error unlocking profile " << profile;
138 }
139 return truncated;
140}
141
Calin Juravle114f0812017-03-08 19:05:07 -0800142// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800143// The location is the profile name for primary apks or the dex path for secondary dex files.
144static bool clear_reference_profile(const std::string& package_name, const std::string& location,
145 bool is_secondary_dex) {
146 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700147}
148
Calin Juravle114f0812017-03-08 19:05:07 -0800149// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800150// The location is the profile name for primary apks or the dex path for secondary dex files.
151static bool clear_current_profile(const std::string& package_name, const std::string& location,
152 userid_t user, bool is_secondary_dex) {
153 return clear_profile(create_current_profile_path(user, package_name, location,
154 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700155}
156
Calin Juravle114f0812017-03-08 19:05:07 -0800157// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800158// The location is the profile name for primary apks or the dex path for secondary dex files.
159bool clear_primary_reference_profile(const std::string& package_name,
160 const std::string& location) {
161 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800162}
163
164// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800165// The location is the profile name for primary apks or the dex path for secondary dex files.
166bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700167 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800168 // 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 -0700169 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
170 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800171 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700172 }
173 return success;
174}
175
Calin Juravle114f0812017-03-08 19:05:07 -0800176// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800177bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
178 userid_t user) {
179 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800180}
181
Calin Juravlef74a7372019-02-28 20:29:41 -0800182// Determines which binary we should use for execution (the debug or non-debug version).
183// e.g. dex2oatd vs dex2oat
184static const char* select_execution_binary(const char* binary, const char* debug_binary,
185 bool background_job_compile) {
186 return select_execution_binary(
187 binary,
188 debug_binary,
189 background_job_compile,
190 is_debug_runtime(),
191 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
192 is_debuggable_build());
193}
194
195// Determines which binary we should use for execution (the debug or non-debug version).
196// e.g. dex2oatd vs dex2oat
197// This is convenient method which is much easier to test because it doesn't read
198// system properties.
199const char* select_execution_binary(
200 const char* binary,
201 const char* debug_binary,
202 bool background_job_compile,
203 bool is_debug_runtime,
204 bool is_release,
205 bool is_debuggable_build) {
206 // Do not use debug binaries for release candidates (to give more soak time).
207 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
208
209 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
210 // the file is present (it may not be on images with very little space available).
211 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
212
213 return useDebug ? debug_binary : binary;
214}
215
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000216// Namespace for Android Runtime flags applied during boot time.
217static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
218// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000219static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000220
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700221// Phenotype property name for enabling profiling the boot class path.
222static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
223
Calin Juravlef85ddb92020-05-01 14:05:40 -0700224static bool IsBootClassPathProfilingEnable() {
225 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
226 profile_boot_class_path =
227 server_configurable_flags::GetServerConfigurableFlag(
228 RUNTIME_NATIVE_BOOT_NAMESPACE,
229 PROFILE_BOOT_CLASS_PATH,
230 /*default_value=*/ profile_boot_class_path);
231 return profile_boot_class_path == "true";
232}
233
Victor Hsiehcb35a062020-08-13 16:11:13 -0700234static void UnlinkIgnoreResult(const std::string& path) {
235 if (unlink(path.c_str()) < 0) {
236 PLOG(ERROR) << "Failed to unlink " << path;
237 }
238}
239
Jeff Sharkey90aff262016-12-12 14:28:24 -0700240/*
241 * Whether dexopt should use a swap file when compiling an APK.
242 *
243 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
244 * itself, anyways).
245 *
246 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
247 *
248 * Otherwise, return true if this is a low-mem device.
249 *
250 * Otherwise, return default value.
251 */
252static bool kAlwaysProvideSwapFile = false;
253static bool kDefaultProvideSwapFile = true;
254
255static bool ShouldUseSwapFileForDexopt() {
256 if (kAlwaysProvideSwapFile) {
257 return true;
258 }
259
260 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700261 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
262 if (!dex2oat_prop_buf.empty()) {
263 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700264 }
265
266 // Shortcut for default value. This is an implementation optimization for the process sketched
267 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
268 // as low-mem is never returning false. The compiler will optimize this away if it can.
269 if (kDefaultProvideSwapFile) {
270 return true;
271 }
272
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700273 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700274 return true;
275 }
276
277 // Default value must be false here.
278 return kDefaultProvideSwapFile;
279}
280
Richard Uhler76cc0272016-12-08 10:46:35 +0000281static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700282 if (set_to_bg) {
283 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800284 PLOG(ERROR) << "set_sched_policy failed";
285 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700286 }
287 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800288 PLOG(ERROR) << "setpriority failed";
289 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700290 }
291 }
292}
293
Calin Juravle29591732017-11-20 17:46:19 -0800294static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
295 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800296 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800297 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800298 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800299 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800300 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700301 }
Calin Juravle114f0812017-03-08 19:05:07 -0800302 // Profiles should belong to the app; make sure of that by giving ownership to
303 // the app uid. If we cannot do that, there's no point in returning the fd
304 // since dex2oat/profman will fail with SElinux denials.
305 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000306 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800307 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800308 }
Calin Juravle29591732017-11-20 17:46:19 -0800309 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800310}
311
Calin Juravle29591732017-11-20 17:46:19 -0800312static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800313 // Do not follow symlinks when opening a profile:
314 // - primary profiles should not contain symlinks in their paths
315 // - secondary dex paths should have been already resolved and validated
316 flags |= O_NOFOLLOW;
317
Calin Juravle29591732017-11-20 17:46:19 -0800318 // Check if we need to create the profile
319 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
320 unique_fd fd;
321 if ((flags & O_CREAT) != 0) {
322 fd = create_profile(uid, profile, flags);
323 } else {
324 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
325 }
326
Calin Juravle114f0812017-03-08 19:05:07 -0800327 if (fd.get() < 0) {
328 if (errno != ENOENT) {
329 // Profiles might be missing for various reasons. For example, in a
330 // multi-user environment, the profile directory for one user can be created
331 // after we start a merge. In this case the current profile for that user
332 // will not be found.
333 // Also, the secondary dex profiles might be deleted by the app at any time,
334 // so we can't we need to prepare if they are missing.
335 PLOG(ERROR) << "Failed to open profile " << profile;
336 }
337 return invalid_unique_fd();
338 }
339
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340 return fd;
341}
342
Calin Juravle824a64d2018-01-18 20:23:17 -0800343static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
344 const std::string& location, bool is_secondary_dex) {
345 std::string profile = create_current_profile_path(user, package_name, location,
346 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800347 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800348}
349
Calin Juravle824a64d2018-01-18 20:23:17 -0800350static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
351 const std::string& location, bool read_write, bool is_secondary_dex) {
352 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800353 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
354}
355
Victor Hsiehcb35a062020-08-13 16:11:13 -0700356static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
357 const std::string& location, bool read_write, bool is_secondary_dex) {
358 std::string profile_path = create_reference_profile_path(package_name, location,
359 is_secondary_dex);
360 unique_fd ufd = open_profile(uid, profile_path, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
361 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
362 clear_profile(path);
363 });
364}
365
Calin Juravle29591732017-11-20 17:46:19 -0800366static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800367 const std::string& location) {
368 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800369 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800370}
371
Calin Juravle824a64d2018-01-18 20:23:17 -0800372static void open_profile_files(uid_t uid, const std::string& package_name,
373 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800374 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700375 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800376 *reference_profile_fd = open_reference_profile(uid, package_name, location,
377 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700378
Calin Juravle114f0812017-03-08 19:05:07 -0800379 // For secondary dex files, we don't really need the user but we use it for sanity checks.
380 // Note: the user owning the dex file should be the current user.
381 std::vector<userid_t> users;
382 if (is_secondary_dex){
383 users.push_back(multiuser_get_user_id(uid));
384 } else {
385 users = get_known_users(/*volume_uuid*/ nullptr);
386 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700387 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800388 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
389 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700390 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800391 if (profile_fd.get() >= 0) {
392 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700393 }
394 }
395}
396
Calin Juravle76561322019-11-14 09:08:52 -0800397static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
398static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
399static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
400static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
401static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
402static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
403static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700404
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800405class RunProfman : public ExecVHelper {
406 public:
407 void SetupArgs(const std::vector<unique_fd>& profile_fds,
408 const unique_fd& reference_profile_fd,
409 const std::vector<unique_fd>& apk_fds,
410 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800411 bool copy_and_update,
412 bool for_snapshot,
413 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800414
415 // TODO(calin): Assume for now we run in the bg compile job (which is in
416 // most of the invocation). With the current data flow, is not very easy or
417 // clean to discover this in RunProfman (it will require quite a messy refactoring).
418 const char* profman_bin = select_execution_binary(
419 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700420
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800421 if (copy_and_update) {
422 CHECK_EQ(1u, profile_fds.size());
423 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000424 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800425 if (reference_profile_fd != -1) {
426 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000427 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800428
429 for (const unique_fd& fd : profile_fds) {
430 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
431 }
432
433 for (const unique_fd& fd : apk_fds) {
434 AddArg("--apk-fd=" + std::to_string(fd.get()));
435 }
436
437 for (const std::string& dex_location : dex_locations) {
438 AddArg("--dex-location=" + dex_location);
439 }
440
441 if (copy_and_update) {
442 AddArg("--copy-and-update-profile-key");
443 }
444
Calin Juravle78728f32019-11-08 17:55:46 -0800445 if (for_snapshot) {
446 AddArg("--force-merge");
447 }
448
449 if (for_boot_image) {
450 AddArg("--boot-image-merge");
451 }
452
yawanng6fe34a52020-11-06 05:13:53 +0000453 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
454 "dalvik.vm.bgdexopt.new-classes-percent", /*default*/-1);
455 if (min_new_classes_percent_change >= 0 && min_new_classes_percent_change <= 100) {
456 AddArg("--min-new-classes-percent-change=" +
457 std::to_string(min_new_classes_percent_change));
458 }
459
460 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
461 "dalvik.vm.bgdexopt.new-methods-percent", /*default*/-1);
462 if (min_new_methods_percent_change >=0 && min_new_methods_percent_change <= 100) {
463 AddArg("--min-new-methods-percent-change=" +
464 std::to_string(min_new_methods_percent_change));
465 }
466
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800467 // Do not add after dex2oat_flags, they should override others for debugging.
468 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800469 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700470
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800471 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
472 const unique_fd& reference_profile_fd,
473 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800474 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
475 bool for_snapshot = false,
476 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800477 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800478 reference_profile_fd,
479 apk_fds,
480 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800481 /*copy_and_update=*/ false,
482 for_snapshot,
483 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800484 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700485
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800486 void SetupCopyAndUpdate(unique_fd&& profile_fd,
487 unique_fd&& reference_profile_fd,
488 unique_fd&& apk_fd,
489 const std::string& dex_location) {
490 // The fds need to stay open longer than the scope of the function, so put them into a local
491 // variable vector.
492 profiles_fd_.push_back(std::move(profile_fd));
493 apk_fds_.push_back(std::move(apk_fd));
494 reference_profile_fd_ = std::move(reference_profile_fd);
495 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800496 SetupArgs(profiles_fd_,
497 reference_profile_fd_,
498 apk_fds_,
499 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800500 /*copy_and_update=*/true,
501 /*for_snapshot*/false,
502 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800503 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000504
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800505 void SetupDump(const std::vector<unique_fd>& profiles_fd,
506 const unique_fd& reference_profile_fd,
507 const std::vector<std::string>& dex_locations,
508 const std::vector<unique_fd>& apk_fds,
509 const unique_fd& output_fd) {
510 AddArg("--dump-only");
511 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800512 SetupArgs(profiles_fd,
513 reference_profile_fd,
514 apk_fds,
515 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800516 /*copy_and_update=*/false,
517 /*for_snapshot*/false,
518 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800519 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000520
Victor Hsiehc9821f12020-08-07 11:32:29 -0700521 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800522 void Exec() {
523 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
524 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000525
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800526 private:
527 unique_fd reference_profile_fd_;
528 std::vector<unique_fd> profiles_fd_;
529 std::vector<unique_fd> apk_fds_;
530};
Mathieu Chartier31636522018-11-09 23:53:07 +0000531
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800532
Calin Juravlef63d4792018-01-30 17:43:34 +0000533
Jeff Sharkey90aff262016-12-12 14:28:24 -0700534// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800535// The location is the package name for primary apks or the dex path for secondary dex files.
536// Returns true if there is enough information in the current profiles that makes it
537// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700538// If the return value is true all the current profiles would have been merged into
539// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800540static bool analyze_profiles(uid_t uid, const std::string& package_name,
541 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800542 std::vector<unique_fd> profiles_fd;
543 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800544 open_profile_files(uid, package_name, location, is_secondary_dex,
545 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800546 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700547 // Skip profile guided compilation because no profiles were found.
548 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700549 return false;
550 }
551
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800552 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700553 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
554 const std::vector<std::string>& dex_locations = std::vector<std::string>();
555 profman_merge.SetupMerge(
556 profiles_fd,
557 reference_profile_fd,
558 apk_fds,
559 dex_locations,
560 /* for_snapshot= */ false,
561 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700562 pid_t pid = fork();
563 if (pid == 0) {
564 /* child -- drop privileges before continuing */
565 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800566 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700567 }
568 /* parent */
569 int return_code = wait_child(pid);
570 bool need_to_compile = false;
571 bool should_clear_current_profiles = false;
572 bool should_clear_reference_profile = false;
573 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800574 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700575 } else {
576 return_code = WEXITSTATUS(return_code);
577 switch (return_code) {
578 case PROFMAN_BIN_RETURN_CODE_COMPILE:
579 need_to_compile = true;
580 should_clear_current_profiles = true;
581 should_clear_reference_profile = false;
582 break;
583 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
584 need_to_compile = false;
585 should_clear_current_profiles = false;
586 should_clear_reference_profile = false;
587 break;
588 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800589 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700590 need_to_compile = false;
591 should_clear_current_profiles = true;
592 should_clear_reference_profile = true;
593 break;
594 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
595 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
596 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800597 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598 need_to_compile = false;
599 should_clear_current_profiles = false;
600 should_clear_reference_profile = false;
601 break;
Calin Juravle76561322019-11-14 09:08:52 -0800602 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
603 need_to_compile = false;
604 should_clear_current_profiles = true;
605 should_clear_reference_profile = true;
606 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700607 default:
608 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800609 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800610 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611 need_to_compile = false;
612 should_clear_current_profiles = true;
613 should_clear_reference_profile = true;
614 break;
615 }
616 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800617
Jeff Sharkey90aff262016-12-12 14:28:24 -0700618 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800619 if (is_secondary_dex) {
620 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800621 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
622 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800623 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800624 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800625 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 }
627 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800628 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700629 }
630 return need_to_compile;
631}
632
Calin Juravle114f0812017-03-08 19:05:07 -0800633// Decides if profile guided compilation is needed or not based on existing profiles.
634// The analysis is done for the primary apks of the given package.
635// Returns true if there is enough information in the current profiles that makes it
636// worth to recompile the package.
637// If the return value is true all the current profiles would have been merged into
638// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800639bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
640 const std::string& profile_name) {
641 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800642}
643
Calin Juravle408cd4a2018-01-20 23:34:18 -0800644bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
645 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800646 std::vector<unique_fd> profile_fds;
647 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800648 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
649 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700650
Calin Juravle408cd4a2018-01-20 23:34:18 -0800651 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800652 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800654 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700655 const bool has_profiles = !profile_fds.empty();
656
657 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800658 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700659 return false;
660 }
661
Calin Juravle114f0812017-03-08 19:05:07 -0800662 unique_fd output_fd(open(out_file_name.c_str(),
663 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800665 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700666 return false;
667 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800668
Jeff Sharkey90aff262016-12-12 14:28:24 -0700669 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800670 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800671 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
672 if (apk_fd == -1) {
673 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
674 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700675 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700676 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800677 apk_fds.push_back(std::move(apk_fd));
678
Jeff Sharkey90aff262016-12-12 14:28:24 -0700679
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800680 RunProfman profman_dump;
681 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700682 pid_t pid = fork();
683 if (pid == 0) {
684 /* child -- drop privileges before continuing */
685 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800686 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700687 }
688 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689 int return_code = wait_child(pid);
690 if (!WIFEXITED(return_code)) {
691 LOG(WARNING) << "profman failed for package " << pkgname << ": "
692 << return_code;
693 return false;
694 }
695 return true;
696}
697
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700698bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800699 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700700 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
701 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800702 package_name,
703 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700704 /*read_write*/ true,
705 /*secondary*/ false));
706 if (in_fd.get() < 0) {
707 PLOG(WARNING) << "Could not open profile " << system_profile;
708 return false;
709 }
710 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800711 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700712 return false;
713 }
714
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700715 // As a security measure we want to write the profile information with the reduced capabilities
716 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700717 pid_t pid = fork();
718 if (pid == 0) {
719 /* child -- drop privileges before continuing */
720 drop_capabilities(packageUid);
721
722 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
723 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800724 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700725 }
726 // This implies that the app owning this profile is running
727 // (and has acquired the lock).
728 //
729 // The app never acquires the lock for the reference profiles of primary apks.
730 // Only dex2oat from installd will do that. Since installd is single threaded
731 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800732 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700733 return false;
734 }
735
736 bool truncated = ftruncate(out_fd.get(), 0) == 0;
737 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800738 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700739 }
740
741 // Copy over data.
742 static constexpr size_t kBufferSize = 4 * 1024;
743 char buffer[kBufferSize];
744 while (true) {
745 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
746 if (bytes == 0) {
747 break;
748 }
749 write(out_fd.get(), buffer, bytes);
750 }
751 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800752 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700753 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700754 // Use _exit since we don't want to run the global destructors in the child.
755 // b/62597429
756 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700757 }
758 /* parent */
759 int return_code = wait_child(pid);
760 return return_code == 0;
761}
762
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
764 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
765 if (EndsWith(oat_path, ".dex")) {
766 std::string new_path = oat_path;
767 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800768 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 return new_path;
770 }
771
772 // An odex entry. Not that this may not be an extension, e.g., in the OTA
773 // case (where the base name will have an extension for the B artifact).
774 size_t odex_pos = oat_path.rfind(".odex");
775 if (odex_pos != std::string::npos) {
776 std::string new_path = oat_path;
777 new_path.replace(odex_pos, strlen(".odex"), new_ext);
778 CHECK_NE(new_path.find(new_ext), std::string::npos);
779 return new_path;
780 }
781
782 // Don't know how to handle this.
783 return "";
784}
785
786// Translate the given oat path to an art (app image) path. An empty string
787// denotes an error.
788static std::string create_image_filename(const std::string& oat_path) {
789 return replace_file_extension(oat_path, ".art");
790}
791
792// Translate the given oat path to a vdex path. An empty string denotes an error.
793static std::string create_vdex_filename(const std::string& oat_path) {
794 return replace_file_extension(oat_path, ".vdex");
795}
796
Jeff Sharkey90aff262016-12-12 14:28:24 -0700797static int open_output_file(const char* file_name, bool recreate, int permissions) {
798 int flags = O_RDWR | O_CREAT;
799 if (recreate) {
800 if (unlink(file_name) < 0) {
801 if (errno != ENOENT) {
802 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
803 }
804 }
805 flags |= O_EXCL;
806 }
807 return open(file_name, flags, permissions);
808}
809
Calin Juravle2289c0a2017-02-15 12:44:14 -0800810static bool set_permissions_and_ownership(
811 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
812 // Primary apks are owned by the system. Secondary dex files are owned by the app.
813 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 if (fchmod(fd,
815 S_IRUSR|S_IWUSR|S_IRGRP |
816 (is_public ? S_IROTH : 0)) < 0) {
817 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
818 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800819 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700820 ALOGE("installd cannot chown '%s' during dexopt\n", path);
821 return false;
822 }
823 return true;
824}
825
826static bool IsOutputDalvikCache(const char* oat_dir) {
827 // InstallerConnection.java (which invokes installd) transforms Java null arguments
828 // into '!'. Play it safe by handling it both.
829 // TODO: ensure we never get null.
830 // TODO: pass a flag instead of inferring if the output is dalvik cache.
831 return oat_dir == nullptr || oat_dir[0] == '!';
832}
833
Calin Juravled23dee72017-07-06 16:29:11 -0700834// Best-effort check whether we can fit the the path into our buffers.
835// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
836// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
837// extension to the cache path (5 bytes).
838// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
839static bool validate_dex_path_size(const std::string& dex_path) {
840 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
841 LOG(ERROR) << "dex_path too long: " << dex_path;
842 return false;
843 }
844 return true;
845}
846
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800848 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700849 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 return false;
851 }
852
853 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800854 // Oat dirs for secondary dex files are already validated.
855 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
857 return false;
858 }
859 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
860 return false;
861 }
862 } else {
863 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
864 return false;
865 }
866 }
867 return true;
868}
869
Calin Juravle7a570e82017-01-14 16:23:30 -0800870// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700871UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700872 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100873
Calin Juravle7a570e82017-01-14 16:23:30 -0800874 const std::string image_path = create_image_filename(out_oat_path);
875 if (image_path.empty()) {
876 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700877 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800878 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100879
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700880 // In case there is a stale image, remove it now. Ignore any error.
881 unlink(image_path.c_str());
882
883 // Not enabled, exit.
884 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700885 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100886 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700887 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
888 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700889 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800890 }
891 // Recreate is true since we do not want to modify a mapped image. If the app is
892 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -0700893 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -0800894 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -0700895 image_path,
896 UnlinkIgnoreResult);
897 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800898 // Could not create application image file. Go on since we can compile without it.
899 LOG(ERROR) << "installd could not create '" << image_path
900 << "' for image file during dexopt";
901 // If we have a valid image file path but no image fd, explicitly erase the image file.
902 if (unlink(image_path.c_str()) < 0) {
903 if (errno != ENOENT) {
904 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
905 }
906 }
907 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -0700908 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800909 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -0700910 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -0800911 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700912
Victor Hsiehcb35a062020-08-13 16:11:13 -0700913 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -0800914}
915
916// Creates the dexopt swap file if necessary and return its fd.
917// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700918unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800919 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800920 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -0800921 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700922 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800923 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600924 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -0800925 if (swap_fd.get() < 0) {
926 // Could not create swap file. Optimistically go on and hope that we can compile
927 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600928 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -0800929 } else {
930 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600931 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800932 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
933 }
934 }
935 return swap_fd;
936}
937
938// Opens the reference profiles if needed.
939// 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 -0700940UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000941 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -0800942 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +0000943 // If we are not profile guided compilation, or we are compiling system server
944 // do not bother to open the profiles; we won't be using them.
945 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700946 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +0000947 }
948
949 // If this is a secondary dex path which is public do not open the profile.
950 // We cannot compile public secondary dex paths with profiles. That's because
951 // it will expose how the dex files are used by their owner.
952 //
953 // Note that the PackageManager is responsible to set the is_public flag for
954 // primary apks and we do not check it here. In some cases, e.g. when
955 // compiling with a public profile from the .dm file the PackageManager will
956 // set is_public toghether with the profile guided compilation.
957 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700958 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700959 }
Calin Juravle114f0812017-03-08 19:05:07 -0800960
961 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000962 std::string location;
963 if (is_secondary_dex) {
964 location = dex_path;
965 } else {
966 if (profile_name == nullptr) {
967 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700968 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000969 } else {
970 location = profile_name;
971 }
972 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700973 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
974 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -0800975}
Jeff Sharkey90aff262016-12-12 14:28:24 -0700976
Victor Hsiehcb35a062020-08-13 16:11:13 -0700977// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
978// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -0700979bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +0000980 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -0700981 bool profile_guided, UniqueFile* in_vdex_wrapper,
982 UniqueFile* out_vdex_wrapper) {
983 CHECK(in_vdex_wrapper != nullptr);
984 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700985 // Open the existing VDEX. We do this before creating the new output VDEX, which will
986 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +0000987 char in_odex_path[PKG_PATH_MAX];
988 int dexopt_action = abs(dexopt_needed);
989 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +0000990
991 // Infer the name of the output VDEX.
992 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
993 if (out_vdex_path_str.empty()) {
994 return false;
995 }
996
997 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +0000998 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700999 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1000 const char* path = nullptr;
1001 if (is_odex_location) {
1002 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1003 path = in_odex_path;
1004 } else {
1005 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001006 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 }
1008 } else {
1009 path = out_oat_path;
1010 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001011 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001012 if (in_vdex_path_str.empty()) {
1013 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001014 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001015 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001016 // We can update in place when all these conditions are met:
1017 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1018 // on /system typically cannot be updated in place).
1019 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1020 // cannot be currently used by a running process.
1021 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1022 // different vdex files to operate.
1023 update_vdex_in_place =
1024 (in_vdex_path_str == out_vdex_path_str) &&
1025 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1026 !profile_guided;
1027 if (update_vdex_in_place) {
1028 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001029 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1030 in_vdex_path_str);
1031 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001032 // If we failed to open the file, we cannot update it in place.
1033 update_vdex_in_place = false;
1034 }
1035 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001036 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1037 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001038 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001039 }
1040
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001041 // If we are updating the vdex in place, we do not need to recreate a vdex,
1042 // and can use the same existing one.
1043 if (update_vdex_in_place) {
1044 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1045 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001046 out_vdex_wrapper->reset(
1047 in_vdex_wrapper->fd(),
1048 out_vdex_path_str,
1049 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001050 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1051 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001052 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001053 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001054 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001055 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001056 out_vdex_path_str,
1057 UnlinkIgnoreResult);
1058 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001059 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1060 return false;
1061 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001062 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001063 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001064 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001065 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1066 return false;
1067 }
1068
1069 // If we got here we successfully opened the vdex files.
1070 return true;
1071}
1072
1073// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001074UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1075 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1076 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001077 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001078 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001079 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001080 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001081 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001082 out_oat_path,
1083 UnlinkIgnoreResult);
1084 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001085 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001086 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001087 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001088 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001089 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001090 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001091 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001092}
1093
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001094// Creates RDONLY fds for oat and vdex files, if exist.
1095// Returns false if it fails to create oat out path for the given apk path.
1096// Note that the method returns true even if the files could not be opened.
1097bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1098 const std::string& oat_dir,
1099 const std::string& instruction_set,
1100 bool is_secondary_dex,
1101 unique_fd* oat_file_fd,
1102 unique_fd* vdex_file_fd) {
1103 char oat_path[PKG_PATH_MAX];
1104 if (!create_oat_out_path(apk_path.c_str(),
1105 instruction_set.c_str(),
1106 oat_dir.c_str(),
1107 is_secondary_dex,
1108 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001109 LOG(ERROR) << "Could not create oat out path for "
1110 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001111 return false;
1112 }
1113 oat_file_fd->reset(open(oat_path, O_RDONLY));
1114 if (oat_file_fd->get() < 0) {
1115 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1116 }
1117
1118 std::string vdex_filename = create_vdex_filename(oat_path);
1119 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1120 if (vdex_file_fd->get() < 0) {
1121 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1122 }
1123
1124 return true;
1125}
1126
Calin Juravle7a570e82017-01-14 16:23:30 -08001127// Updates the access times of out_oat_path based on those from apk_path.
1128void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1129 struct stat input_stat;
1130 memset(&input_stat, 0, sizeof(input_stat));
1131 if (stat(apk_path, &input_stat) != 0) {
1132 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1133 return;
1134 }
1135
1136 struct utimbuf ut;
1137 ut.actime = input_stat.st_atime;
1138 ut.modtime = input_stat.st_mtime;
1139 if (utime(out_oat_path, &ut) != 0) {
1140 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1141 }
1142}
1143
Calin Juravle80a21252017-01-17 14:43:25 -08001144// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001145// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1146// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1147// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001148class RunDexoptAnalyzer : public ExecVHelper {
1149 public:
1150 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001151 int vdex_fd,
1152 int oat_fd,
1153 int zip_fd,
1154 const std::string& instruction_set,
1155 const std::string& compiler_filter,
1156 bool profile_was_updated,
1157 bool downgrade,
1158 const char* class_loader_context,
1159 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001160 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001161
1162 // We always run the analyzer in the background job.
1163 const char* dexoptanalyzer_bin = select_execution_binary(
1164 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001165
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001166 std::string dex_file_arg = "--dex-file=" + dex_file;
1167 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1168 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1169 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1170 std::string isa_arg = "--isa=" + instruction_set;
1171 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1172 const char* assume_profile_changed = "--assume-profile-changed";
1173 const char* downgrade_flag = "--downgrade";
1174 std::string class_loader_context_arg = "--class-loader-context=";
1175 if (class_loader_context != nullptr) {
1176 class_loader_context_arg += class_loader_context;
1177 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001178 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1179 if (!class_loader_context_fds.empty()) {
1180 class_loader_context_fds_arg += class_loader_context_fds;
1181 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001182
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001183 // program name, dex file, isa, filter
1184 AddArg(dex_file_arg);
1185 AddArg(isa_arg);
1186 AddArg(compiler_filter_arg);
1187 if (oat_fd >= 0) {
1188 AddArg(oat_fd_arg);
1189 }
1190 if (vdex_fd >= 0) {
1191 AddArg(vdex_fd_arg);
1192 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001193 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001194 if (profile_was_updated) {
1195 AddArg(assume_profile_changed);
1196 }
1197 if (downgrade) {
1198 AddArg(downgrade_flag);
1199 }
1200 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001201 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001202 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001203 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001204 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001205 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001206
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001207 PrepareArgs(dexoptanalyzer_bin);
1208 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001209
1210 // Dexoptanalyzer mode which flattens the given class loader context and
1211 // prints a list of its dex files in that flattened order.
1212 RunDexoptAnalyzer(const char* class_loader_context) {
1213 CHECK(class_loader_context != nullptr);
1214
1215 // We always run the analyzer in the background job.
1216 const char* dexoptanalyzer_bin = select_execution_binary(
1217 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1218
1219 AddArg("--flatten-class-loader-context");
1220 AddArg(std::string("--class-loader-context=") + class_loader_context);
1221 PrepareArgs(dexoptanalyzer_bin);
1222 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001223};
Calin Juravle80a21252017-01-17 14:43:25 -08001224
1225// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001226static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001227 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001228 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001229 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001230 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001231 return false;
1232 }
Calin Juravle114f0812017-03-08 19:05:07 -08001233 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001234
Calin Juravle80a21252017-01-17 14:43:25 -08001235 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001236 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1237 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001238 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001239 return false;
1240 }
1241
1242 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001243 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001244
Calin Juravle7d765462017-09-04 15:57:10 -07001245 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001246 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001247 return false;
1248 }
1249
1250 return true;
1251}
1252
Calin Juravle7d765462017-09-04 15:57:10 -07001253// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1254// secondary dex files. This return codes are returned by the child process created for
1255// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001256
Andreas Gampe194fe422018-02-28 20:16:19 -08001257enum DexoptAnalyzerSkipCodes {
1258 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001259 // Specific errors are encoded in the name.
1260 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1261 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1262 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1263 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1264 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001265 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001266 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001267};
Calin Juravle7d765462017-09-04 15:57:10 -07001268
1269// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001270// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1271// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001272// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1273// of dexoptanalyzer.
1274static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001275 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001276 // The result values are defined in dexoptanalyzer.
1277 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001278 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001279 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001280 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001281 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001282 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001283 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001284 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001285 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001286 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1287 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001288 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1289 " Expected odex file status for secondary dex %s"
1290 " : dexoptanalyzer result=%d",
1291 dex_path.c_str(),
1292 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001293 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001294 }
1295
1296 // Use a second switch for enum switch-case analysis.
1297 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001298 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001299 // If the file does not exist there's no need for dexopt.
1300 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1301 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001302
1303 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1304 *error_msg = "Dexoptanalyzer path validation failed";
1305 return false;
1306 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1307 *error_msg = "Dexoptanalyzer open zip failed";
1308 return false;
1309 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1310 *error_msg = "Dexoptanalyzer dir preparation failed";
1311 return false;
1312 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1313 *error_msg = "Dexoptanalyzer open output failed";
1314 return false;
1315 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1316 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001317 return false;
1318 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001319
1320 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1321 dex_path.c_str(),
1322 result);
1323 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001324}
1325
Calin Juravle7d765462017-09-04 15:57:10 -07001326enum SecondaryDexAccess {
1327 kSecondaryDexAccessReadOk = 0,
1328 kSecondaryDexAccessDoesNotExist = 1,
1329 kSecondaryDexAccessPermissionError = 2,
1330 kSecondaryDexAccessIOError = 3
1331};
1332
1333static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1334 // Check if the path exists and can be read. If not, there's nothing to do.
1335 if (access(dex_path.c_str(), R_OK) == 0) {
1336 return kSecondaryDexAccessReadOk;
1337 } else {
1338 if (errno == ENOENT) {
1339 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1340 return kSecondaryDexAccessDoesNotExist;
1341 } else {
1342 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1343 return errno == EACCES
1344 ? kSecondaryDexAccessPermissionError
1345 : kSecondaryDexAccessIOError;
1346 }
1347 }
1348}
1349
1350static bool is_file_public(const std::string& filename) {
1351 struct stat file_stat;
1352 if (stat(filename.c_str(), &file_stat) == 0) {
1353 return (file_stat.st_mode & S_IROTH) != 0;
1354 }
1355 return false;
1356}
1357
1358// Create the oat file structure for the secondary dex 'dex_path' and assign
1359// the individual path component to the 'out_' parameters.
1360static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001361 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001362 size_t dirIndex = dex_path.rfind('/');
1363 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001364 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001365 return false;
1366 }
1367 // TODO(calin): we have similar computations in at lest 3 other places
1368 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1369 // using string append.
1370 std::string apk_dir = dex_path.substr(0, dirIndex);
1371 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1372 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1373
1374 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1375 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001376 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001377 return false;
1378 }
1379 return true;
1380}
1381
1382// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1383// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001384static bool validate_dexopt_storage_flags(int dexopt_flags,
1385 int* out_storage_flag,
1386 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001387 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1388 *out_storage_flag = FLAG_STORAGE_CE;
1389 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001390 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001391 return false;
1392 }
1393 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1394 *out_storage_flag = FLAG_STORAGE_DE;
1395 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001396 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001397 return false;
1398 }
1399 return true;
1400}
1401
David Brazdil4f6027a2019-03-19 11:44:21 +00001402static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1403 /* out */ std::vector<std::string>* context_dex_paths) {
1404 if (class_loader_context == nullptr) {
1405 return true;
1406 }
1407
1408 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1409
1410 // Pipe to get the hash result back from our child process.
1411 unique_fd pipe_read, pipe_write;
1412 if (!Pipe(&pipe_read, &pipe_write)) {
1413 PLOG(ERROR) << "Failed to create pipe";
1414 return false;
1415 }
1416
1417 pid_t pid = fork();
1418 if (pid == 0) {
1419 // child -- drop privileges before continuing.
1420 drop_capabilities(uid);
1421
1422 // Route stdout to `pipe_write`
1423 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1424 pipe_write.reset();
1425 pipe_read.reset();
1426
1427 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1428 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1429 }
1430
1431 /* parent */
1432 pipe_write.reset();
1433
1434 std::string str_dex_paths;
1435 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1436 PLOG(ERROR) << "Failed to read from pipe";
1437 return false;
1438 }
1439 pipe_read.reset();
1440
1441 int return_code = wait_child(pid);
1442 if (!WIFEXITED(return_code)) {
1443 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1444 return false;
1445 }
1446
1447 constexpr int kFlattenClassLoaderContextSuccess = 50;
1448 return_code = WEXITSTATUS(return_code);
1449 if (return_code != kFlattenClassLoaderContextSuccess) {
1450 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1451 return false;
1452 }
1453
1454 if (!str_dex_paths.empty()) {
1455 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1456 }
1457 return true;
1458}
1459
1460static int open_dex_paths(const std::vector<std::string>& dex_paths,
1461 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1462 for (const std::string& dex_path : dex_paths) {
1463 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1464 if (zip_fds->back().get() < 0) {
1465 *error_msg = StringPrintf(
1466 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1467 if (errno == ENOENT) {
1468 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1469 } else {
1470 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1471 }
1472 }
1473 }
1474 return 0;
1475}
1476
1477static std::string join_fds(const std::vector<unique_fd>& fds) {
1478 std::stringstream ss;
1479 bool is_first = true;
1480 for (const unique_fd& fd : fds) {
1481 if (is_first) {
1482 is_first = false;
1483 } else {
1484 ss << ":";
1485 }
1486 ss << fd.get();
1487 }
1488 return ss.str();
1489}
1490
Calin Juravlec9eab382017-01-25 01:17:17 -08001491// 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 -08001492// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1493// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001494// When returning true, the output parameters will be:
1495// - is_public_out: whether or not the oat file should not be made public
1496// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1497// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001498static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001499 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001500 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001501 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001502 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001503 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001504 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001505 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1506 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001507 return false;
1508 }
Calin Juravle7d765462017-09-04 15:57:10 -07001509 // Compute the oat dir as it's not easy to extract it from the child computation.
1510 char oat_path[PKG_PATH_MAX];
1511 char oat_dir[PKG_PATH_MAX];
1512 char oat_isa_dir[PKG_PATH_MAX];
1513 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001514 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1515 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001516 return false;
1517 }
Calin Juravle7d765462017-09-04 15:57:10 -07001518 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001519
Calin Juravle80a21252017-01-17 14:43:25 -08001520 pid_t pid = fork();
1521 if (pid == 0) {
1522 // child -- drop privileges before continuing.
1523 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001524
1525 // Validate the path structure.
1526 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1527 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001528 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001529 }
1530
1531 // Open the dex file.
1532 unique_fd zip_fd;
1533 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1534 if (zip_fd.get() < 0) {
1535 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001536 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001537 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001538 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001539 }
1540 }
1541
David Brazdil4f6027a2019-03-19 11:44:21 +00001542 // Open class loader context dex files.
1543 std::vector<unique_fd> context_zip_fds;
1544 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1545 if (open_dex_paths_rc != 0) {
1546 _exit(open_dex_paths_rc);
1547 }
1548
Calin Juravle7d765462017-09-04 15:57:10 -07001549 // Prepare the oat directories.
1550 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001551 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001552 }
1553
1554 // Open the vdex/oat files if any.
1555 unique_fd oat_file_fd;
1556 unique_fd vdex_file_fd;
1557 if (!maybe_open_oat_and_vdex_file(dex_path,
1558 *oat_dir_out,
1559 instruction_set,
1560 true /* is_secondary_dex */,
1561 &oat_file_fd,
1562 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001563 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001564 }
1565
1566 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001567 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1568 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001569
1570 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001571 // Note that we do not do it before the fork since opening the files is required to happen
1572 // after forking.
1573 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1574 vdex_file_fd.get(),
1575 oat_file_fd.get(),
1576 zip_fd.get(),
1577 instruction_set,
1578 compiler_filter, profile_was_updated,
1579 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001580 class_loader_context,
1581 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001582 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001583 }
1584
1585 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001586 int result = wait_child(pid);
1587 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001588 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1589 dex_path.c_str(),
1590 result);
1591 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001592 return false;
1593 }
1594 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001595 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001596 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1597 result,
1598 dexopt_needed_out,
1599 error_msg);
1600 if (!success) {
1601 LOG(ERROR) << *error_msg;
1602 }
Calin Juravle7d765462017-09-04 15:57:10 -07001603
1604 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1605
Calin Juravle80a21252017-01-17 14:43:25 -08001606 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001607 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1608 // makes the code simpler; force compilation is only needed during tests).
1609 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001610 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001611 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001612 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1613 }
1614
Calin Juravle7d765462017-09-04 15:57:10 -07001615 // Check if we should make the oat file public.
1616 // Note that if the dex file is not public the compiled code cannot be made public.
1617 // It is ok to check this flag outside in the parent process.
1618 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1619
Calin Juravle80a21252017-01-17 14:43:25 -08001620 return success;
1621}
1622
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001623static std::string format_dexopt_error(int status, const char* dex_path) {
1624 if (WIFEXITED(status)) {
1625 int int_code = WEXITSTATUS(status);
1626 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1627 if (code_name != nullptr) {
1628 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1629 }
1630 }
1631 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001632}
1633
Calin Juravlec9eab382017-01-25 01:17:17 -08001634int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001635 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001636 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001637 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001638 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001639 CHECK(pkgname != nullptr);
1640 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001641 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001642 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1643 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001644
Calin Juravled23dee72017-07-06 16:29:11 -07001645 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001646 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001647 return -1;
1648 }
1649
1650 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001651 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1652 class_loader_context);
1653 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001654 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001655 }
1656
Calin Juravleebc8a792017-04-04 20:21:05 -07001657 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001658 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1659 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1660 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001661 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001662 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001663 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001664 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001665 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001666 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001667
1668 // Check if we're dealing with a secondary dex file and if we need to compile it.
1669 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001670 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001671 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001672 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1673 *error_msg = "Failed acquiring context dex paths";
1674 return -1; // We had an error, logged in the process method.
1675 }
1676
Calin Juravlec9eab382017-01-25 01:17:17 -08001677 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001678 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00001679 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001680 oat_dir = oat_dir_str.c_str();
1681 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1682 return 0; // Nothing to do, report success.
1683 }
1684 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001685 if (error_msg->empty()) { // TODO: Make this a CHECK.
1686 *error_msg = "Failed processing secondary.";
1687 }
Calin Juravle80a21252017-01-17 14:43:25 -08001688 return -1; // We had an error, logged in the process method.
1689 }
1690 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001691 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001692 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001693 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1694 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1695 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001696
1697 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001698 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1699 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001700 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1701 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001702 return -1;
1703 }
1704
David Brazdil4f6027a2019-03-19 11:44:21 +00001705 // Open class loader context dex files.
1706 std::vector<unique_fd> context_input_fds;
1707 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1708 LOG(ERROR) << *error_msg;
1709 return -1;
1710 }
1711
Calin Juravle7a570e82017-01-14 16:23:30 -08001712 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001713 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1714 instruction_set, is_secondary_dex);
1715 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001716 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001717 return -1;
1718 }
1719
1720 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001721 UniqueFile in_vdex;
1722 UniqueFile out_vdex;
1723 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1724 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1725 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001726 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001727 return -1;
1728 }
1729
Calin Juravlecb556e32017-04-04 20:22:50 -07001730 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1731 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1732 // fully inherit their parent context).
1733 // Note that for primary apk the oat files are created before, in a separate installd
1734 // call which also does the restorecon. TODO(calin): unify the paths.
1735 if (is_secondary_dex) {
1736 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1737 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001738 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1739 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001740 return -1;
1741 }
1742 }
1743
Jeff Sharkey90aff262016-12-12 14:28:24 -07001744 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001745 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001746
Calin Juravle7a570e82017-01-14 16:23:30 -08001747 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001748 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001749 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001750
Victor Hsiehcb35a062020-08-13 16:11:13 -07001751 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001752 // We don't create an app image without reference profile since there is no speedup from
1753 // loading it in that case and instead will be a small overhead.
1754 generate_app_image = false;
1755 }
1756
1757 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001758 UniqueFile out_image = maybe_open_app_image(
1759 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001760
Victor Hsiehcb35a062020-08-13 16:11:13 -07001761 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001762 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001763 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1764 dex_metadata_path);
1765 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001766 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1767 }
1768 }
1769
Victor Hsieh8948a862020-08-07 11:30:55 -07001770 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1771 RUNTIME_NATIVE_BOOT_NAMESPACE,
1772 ENABLE_JITZYGOTE_IMAGE,
1773 /*default_value=*/ "");
1774 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1775
Victor Hsiehe98e6512020-08-10 15:39:22 -07001776 // Decide whether to use dex2oat64.
1777 bool use_dex2oat64 = false;
1778 // Check whether the device even supports 64-bit ABIs.
1779 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1780 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1781 }
1782 const char* dex2oat_bin = select_execution_binary(
1783 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1784 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1785 background_job_compile);
1786
Victor Hsiehc9821f12020-08-07 11:32:29 -07001787 auto execv_helper = std::make_unique<ExecVHelper>();
1788
Andreas Gampe023b2242018-02-28 16:03:25 -08001789 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001790
Victor Hsiehc9821f12020-08-07 11:32:29 -07001791 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001792 runner.Initialize(out_oat,
1793 out_vdex,
1794 out_image,
1795 in_dex,
1796 in_vdex,
1797 dex_metadata,
1798 reference_profile,
1799 class_loader_context,
1800 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001801 swap_fd.get(),
1802 instruction_set,
1803 compiler_filter,
1804 debuggable,
1805 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001806 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001807 target_sdk_version,
1808 enable_hidden_api_checks,
1809 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001810 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001811 compilation_reason);
1812
Jeff Sharkey90aff262016-12-12 14:28:24 -07001813 pid_t pid = fork();
1814 if (pid == 0) {
1815 /* child -- drop privileges before continuing */
1816 drop_capabilities(uid);
1817
Richard Uhler76cc0272016-12-08 10:46:35 +00001818 SetDex2OatScheduling(boot_complete);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001819 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
1820 PLOG(ERROR) << "flock(" << out_oat.path() << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001821 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001822 }
1823
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001824 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001825 } else {
1826 int res = wait_child(pid);
1827 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001828 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001829 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001830 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1831 << std::hex << std::setw(4) << res << ", process failed";
1832 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001833 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001834 }
1835 }
1836
Victor Hsiehcb35a062020-08-13 16:11:13 -07001837 update_out_oat_access_times(dex_path, out_oat.path().c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001838
1839 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001840 out_oat.DisableCleanup();
1841 out_vdex.DisableCleanup();
1842 out_image.DisableCleanup();
1843 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001844
1845 return 0;
1846}
1847
Calin Juravlec9eab382017-01-25 01:17:17 -08001848// Try to remove the given directory. Log an error if the directory exists
1849// and is empty but could not be removed.
1850static bool rmdir_if_empty(const char* dir) {
1851 if (rmdir(dir) == 0) {
1852 return true;
1853 }
1854 if (errno == ENOENT || errno == ENOTEMPTY) {
1855 return true;
1856 }
1857 PLOG(ERROR) << "Failed to remove dir: " << dir;
1858 return false;
1859}
1860
1861// Try to unlink the given file. Log an error if the file exists and could not
1862// be unlinked.
1863static bool unlink_if_exists(const std::string& file) {
1864 if (unlink(file.c_str()) == 0) {
1865 return true;
1866 }
1867 if (errno == ENOENT) {
1868 return true;
1869
1870 }
1871 PLOG(ERROR) << "Could not unlink: " << file;
1872 return false;
1873}
1874
Calin Juravle7d765462017-09-04 15:57:10 -07001875enum ReconcileSecondaryDexResult {
1876 kReconcileSecondaryDexExists = 0,
1877 kReconcileSecondaryDexCleanedUp = 1,
1878 kReconcileSecondaryDexValidationError = 2,
1879 kReconcileSecondaryDexCleanUpError = 3,
1880 kReconcileSecondaryDexAccessIOError = 4,
1881};
Calin Juravlec9eab382017-01-25 01:17:17 -08001882
1883// Reconcile the secondary dex 'dex_path' and its generated oat files.
1884// Return true if all the parameters are valid and the secondary dex file was
1885// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1886// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1887// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1888// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1889// Return false if there were errors during processing. In this case
1890// out_secondary_dex_exists will be set to false.
1891bool reconcile_secondary_dex_file(const std::string& dex_path,
1892 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001893 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08001894 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001895 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001896 if (isas.size() == 0) {
1897 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1898 return false;
1899 }
1900
Calin Juravle7d765462017-09-04 15:57:10 -07001901 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1902 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1903 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001904 return false;
1905 }
1906
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001907 // As a security measure we want to unlink art artifacts with the reduced capabilities
1908 // of the package user id. So we fork and drop capabilities in the child.
1909 pid_t pid = fork();
1910 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001911 /* child -- drop privileges before continuing */
1912 drop_capabilities(uid);
1913
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001914 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07001915 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07001916 uid, storage_flag)) {
1917 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1918 _exit(kReconcileSecondaryDexValidationError);
1919 }
1920
1921 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1922 switch (access_check) {
1923 case kSecondaryDexAccessDoesNotExist:
1924 // File does not exist. Proceed with cleaning.
1925 break;
1926 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1927 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1928 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1929 default:
1930 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
1931 _exit(kReconcileSecondaryDexValidationError);
1932 }
1933
1934 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001935 char oat_path[PKG_PATH_MAX];
1936 char oat_dir[PKG_PATH_MAX];
1937 char oat_isa_dir[PKG_PATH_MAX];
1938 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001939 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001940 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001941 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001942 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
1943 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001944 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001945 }
Calin Juravle51314092017-05-18 15:33:05 -07001946
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001947 // Delete oat/vdex/art files.
1948 result = unlink_if_exists(oat_path) && result;
1949 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1950 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08001951
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001952 // Delete profiles.
1953 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001954 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001955 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001956 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001957 result = unlink_if_exists(current_profile) && result;
1958 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07001959
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001960 // We upgraded once the location of current profile for secondary dex files.
1961 // Check for any previous left-overs and remove them as well.
1962 std::string old_current_profile = dex_path + ".prof";
1963 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07001964
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001965 // Try removing the directories as well, they might be empty.
1966 result = rmdir_if_empty(oat_isa_dir) && result;
1967 result = rmdir_if_empty(oat_dir) && result;
1968 }
Calin Juravle7d765462017-09-04 15:57:10 -07001969 if (!result) {
1970 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
1971 }
1972 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08001973 }
1974
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001975 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07001976 if (!WIFEXITED(return_code)) {
1977 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
1978 } else {
1979 return_code = WEXITSTATUS(return_code);
1980 }
1981
1982 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
1983
1984 switch (return_code) {
1985 case kReconcileSecondaryDexCleanedUp:
1986 case kReconcileSecondaryDexValidationError:
1987 // If we couldn't validate assume the dex file does not exist.
1988 // This will purge the entry from the PM records.
1989 *out_secondary_dex_exists = false;
1990 return true;
1991 case kReconcileSecondaryDexExists:
1992 *out_secondary_dex_exists = true;
1993 return true;
1994 case kReconcileSecondaryDexAccessIOError:
1995 // We had an access IO error.
1996 // Return false so that we can try again.
1997 // The value of out_secondary_dex_exists does not matter in this case and by convention
1998 // is set to false.
1999 *out_secondary_dex_exists = false;
2000 return false;
2001 default:
2002 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2003 *out_secondary_dex_exists = false;
2004 return false;
2005 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002006}
2007
Alan Stokesa25d90c2017-10-16 10:56:00 +01002008// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2009// Returns true if all parameters are valid and the hash successfully computed and stored in
2010// out_secondary_dex_hash.
2011// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2012// the app.
2013// For any other errors (e.g. if any of the parameters are invalid) returns false.
2014bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002015 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002016 std::vector<uint8_t>* out_secondary_dex_hash) {
2017 out_secondary_dex_hash->clear();
2018
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002019 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002020
2021 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2022 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2023 << storage_flag;
2024 return false;
2025 }
2026
2027 // Pipe to get the hash result back from our child process.
2028 unique_fd pipe_read, pipe_write;
2029 if (!Pipe(&pipe_read, &pipe_write)) {
2030 PLOG(ERROR) << "Failed to create pipe";
2031 return false;
2032 }
2033
2034 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2035 // access data the app itself can access.
2036 pid_t pid = fork();
2037 if (pid == 0) {
2038 // child -- drop privileges before continuing
2039 drop_capabilities(uid);
2040 pipe_read.reset();
2041
2042 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2043 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002044 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002045 }
2046
2047 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2048 if (fd == -1) {
2049 if (errno == EACCES || errno == ENOENT) {
2050 // Not treated as an error.
2051 _exit(0);
2052 }
2053 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002054 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002055 }
2056
2057 SHA256_CTX ctx;
2058 SHA256_Init(&ctx);
2059
2060 std::vector<uint8_t> buffer(65536);
2061 while (true) {
2062 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2063 if (bytes_read == 0) {
2064 break;
2065 } else if (bytes_read == -1) {
2066 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002067 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002068 }
2069
2070 SHA256_Update(&ctx, buffer.data(), bytes_read);
2071 }
2072
2073 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2074 SHA256_Final(hash.data(), &ctx);
2075 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002076 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002077 }
2078
2079 _exit(0);
2080 }
2081
2082 // parent
2083 pipe_write.reset();
2084
2085 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2086 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2087 out_secondary_dex_hash->clear();
2088 }
2089 return wait_child(pid) == 0;
2090}
2091
Jeff Sharkey90aff262016-12-12 14:28:24 -07002092// Helper for move_ab, so that we can have common failure-case cleanup.
2093static bool unlink_and_rename(const char* from, const char* to) {
2094 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2095 // return a failure.
2096 struct stat s;
2097 if (stat(to, &s) == 0) {
2098 if (!S_ISREG(s.st_mode)) {
2099 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2100 return false;
2101 }
2102 if (unlink(to) != 0) {
2103 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2104 return false;
2105 }
2106 } else {
2107 // This may be a permission problem. We could investigate the error code, but we'll just
2108 // let the rename failure do the work for us.
2109 }
2110
2111 // Try to rename "to" to "from."
2112 if (rename(from, to) != 0) {
2113 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2114 return false;
2115 }
2116 return true;
2117}
2118
2119// Move/rename a B artifact (from) to an A artifact (to).
2120static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2121 // Check whether B exists.
2122 {
2123 struct stat s;
2124 if (stat(b_path.c_str(), &s) != 0) {
2125 // Silently ignore for now. The service calling this isn't smart enough to understand
2126 // lack of artifacts at the moment.
2127 return false;
2128 }
2129 if (!S_ISREG(s.st_mode)) {
2130 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2131 // Try to unlink, but swallow errors.
2132 unlink(b_path.c_str());
2133 return false;
2134 }
2135 }
2136
2137 // Rename B to A.
2138 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2139 // Delete the b_path so we don't try again (or fail earlier).
2140 if (unlink(b_path.c_str()) != 0) {
2141 PLOG(ERROR) << "Could not unlink " << b_path;
2142 }
2143
2144 return false;
2145 }
2146
2147 return true;
2148}
2149
2150bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2151 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002152 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2153 if (slot_suffix.empty()) {
2154 return false;
2155 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002156
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002157 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2158 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2159 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002160 }
2161
2162 // Validate other inputs.
2163 if (validate_apk_path(apk_path) != 0) {
2164 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2165 return false;
2166 }
2167 if (validate_apk_path(oat_dir) != 0) {
2168 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2169 return false;
2170 }
2171
2172 char a_path[PKG_PATH_MAX];
2173 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2174 return false;
2175 }
2176 const std::string a_vdex_path = create_vdex_filename(a_path);
2177 const std::string a_image_path = create_image_filename(a_path);
2178
2179 // B path = A path + slot suffix.
2180 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2181 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2182 const std::string b_image_path = StringPrintf("%s.%s",
2183 a_image_path.c_str(),
2184 slot_suffix.c_str());
2185
2186 bool success = true;
2187 if (move_ab_path(b_path, a_path)) {
2188 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2189 // Note: we can live without an app image. As such, ignore failure to move the image file.
2190 // If we decide to require the app image, or the app image being moved correctly,
2191 // then change accordingly.
2192 constexpr bool kIgnoreAppImageFailure = true;
2193
2194 if (!a_image_path.empty()) {
2195 if (!move_ab_path(b_image_path, a_image_path)) {
2196 unlink(a_image_path.c_str());
2197 if (!kIgnoreAppImageFailure) {
2198 success = false;
2199 }
2200 }
2201 }
2202 } else {
2203 // Cleanup: delete B image, ignore errors.
2204 unlink(b_image_path.c_str());
2205 success = false;
2206 }
2207 } else {
2208 // Cleanup: delete B image, ignore errors.
2209 unlink(b_vdex_path.c_str());
2210 unlink(b_image_path.c_str());
2211 success = false;
2212 }
2213 return success;
2214}
2215
2216bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2217 // Delete the oat/odex file.
2218 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002219 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002220 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002221 return false;
2222 }
2223
2224 // In case of a permission failure report the issue. Otherwise just print a warning.
2225 auto unlink_and_check = [](const char* path) -> bool {
2226 int result = unlink(path);
2227 if (result != 0) {
2228 if (errno == EACCES || errno == EPERM) {
2229 PLOG(ERROR) << "Could not unlink " << path;
2230 return false;
2231 }
2232 PLOG(WARNING) << "Could not unlink " << path;
2233 }
2234 return true;
2235 };
2236
2237 // Delete the oat/odex file.
2238 bool return_value_oat = unlink_and_check(out_path);
2239
2240 // Derive and delete the app image.
2241 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2242
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002243 // Derive and delete the vdex file.
2244 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2245
Jeff Sharkey90aff262016-12-12 14:28:24 -07002246 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002247 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002248}
2249
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002250static bool is_absolute_path(const std::string& path) {
2251 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2252 LOG(ERROR) << "Invalid absolute path " << path;
2253 return false;
2254 } else {
2255 return true;
2256 }
2257}
2258
2259static bool is_valid_instruction_set(const std::string& instruction_set) {
2260 // TODO: add explicit whitelisting of instruction sets
2261 if (instruction_set.find('/') != std::string::npos) {
2262 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2263 return false;
2264 } else {
2265 return true;
2266 }
2267}
2268
2269bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2270 const char *apk_path, const char *instruction_set) {
2271 std::string oat_dir_ = oat_dir;
2272 std::string apk_path_ = apk_path;
2273 std::string instruction_set_ = instruction_set;
2274
2275 if (!is_absolute_path(oat_dir_)) return false;
2276 if (!is_absolute_path(apk_path_)) return false;
2277 if (!is_valid_instruction_set(instruction_set_)) return false;
2278
2279 std::string::size_type end = apk_path_.rfind('.');
2280 std::string::size_type start = apk_path_.rfind('/', end);
2281 if (end == std::string::npos || start == std::string::npos) {
2282 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2283 return false;
2284 }
2285
2286 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2287 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2288 const char* res = res_.c_str();
2289 if (strlen(res) >= PKG_PATH_MAX) {
2290 LOG(ERROR) << "Result too large";
2291 return false;
2292 } else {
2293 strlcpy(path, res, PKG_PATH_MAX);
2294 return true;
2295 }
2296}
2297
2298bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2299 const char *instruction_set) {
2300 std::string apk_path_ = apk_path;
2301 std::string instruction_set_ = instruction_set;
2302
2303 if (!is_absolute_path(apk_path_)) return false;
2304 if (!is_valid_instruction_set(instruction_set_)) return false;
2305
2306 std::string::size_type end = apk_path_.rfind('.');
2307 std::string::size_type start = apk_path_.rfind('/', end);
2308 if (end == std::string::npos || start == std::string::npos) {
2309 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2310 return false;
2311 }
2312
2313 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2314 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2315}
2316
2317bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2318 const char *instruction_set) {
2319 std::string src_ = src;
2320 std::string instruction_set_ = instruction_set;
2321
2322 if (!is_absolute_path(src_)) return false;
2323 if (!is_valid_instruction_set(instruction_set_)) return false;
2324
2325 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2326 if (*it == '/') {
2327 *it = '@';
2328 }
2329 }
2330
2331 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2332 + DALVIK_CACHE_POSTFIX;
2333 const char* res = res_.c_str();
2334 if (strlen(res) >= PKG_PATH_MAX) {
2335 LOG(ERROR) << "Result too large";
2336 return false;
2337 } else {
2338 strlcpy(path, res, PKG_PATH_MAX);
2339 return true;
2340 }
2341}
2342
Calin Juravle59f7ab82018-04-27 17:50:23 -07002343bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2344 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002345 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2346 for (const std::string& elem : classpaths_elems) {
2347 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2348 if (fd < 0) {
2349 PLOG(ERROR) << "Could not open classpath elem " << elem;
2350 return false;
2351 } else {
2352 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002353 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002354 }
2355 }
2356 return true;
2357}
2358
2359static bool create_app_profile_snapshot(int32_t app_id,
2360 const std::string& package_name,
2361 const std::string& profile_name,
2362 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002363 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2364
Calin Juravle824a64d2018-01-18 20:23:17 -08002365 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002366 if (snapshot_fd < 0) {
2367 return false;
2368 }
2369
2370 std::vector<unique_fd> profiles_fd;
2371 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002372 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2373 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002374 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2375 return false;
2376 }
2377
2378 profiles_fd.push_back(std::move(reference_profile_fd));
2379
Calin Juravle0d0a4922018-01-23 19:54:11 -08002380 // Open the class paths elements. These will be used to filter out profile data that does
2381 // not belong to the classpath during merge.
2382 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002383 std::vector<std::string> dex_locations;
2384 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002385 return false;
2386 }
2387
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002388 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002389 // This is specifically a snapshot for an app, so don't use boot image profiles.
2390 args.SetupMerge(profiles_fd,
2391 snapshot_fd,
2392 apk_fds,
2393 dex_locations,
2394 /* for_snapshot= */ true,
2395 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002396 pid_t pid = fork();
2397 if (pid == 0) {
2398 /* child -- drop privileges before continuing */
2399 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002400 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002401 }
2402
2403 /* parent */
2404 int return_code = wait_child(pid);
2405 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002406 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002407 return false;
2408 }
2409
Calin Juravle78728f32019-11-08 17:55:46 -08002410 // Verify that profman finished successfully.
2411 int profman_code = WEXITSTATUS(return_code);
2412 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2413 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2414 << ":" << profman_code;
2415 return false;
2416 }
Calin Juravle29591732017-11-20 17:46:19 -08002417 return true;
2418}
2419
Calin Juravle0d0a4922018-01-23 19:54:11 -08002420static bool create_boot_image_profile_snapshot(const std::string& package_name,
2421 const std::string& profile_name,
2422 const std::string& classpath) {
2423 // The reference profile directory for the android package might not be prepared. Do it now.
2424 const std::string ref_profile_dir =
2425 create_primary_reference_profile_package_dir_path(package_name);
2426 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2427 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2428 return false;
2429 }
2430
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002431 // Return false for empty class path since it may otherwise return true below if profiles is
2432 // empty.
2433 if (classpath.empty()) {
2434 PLOG(ERROR) << "Class path is empty";
2435 return false;
2436 }
2437
Calin Juravle0d0a4922018-01-23 19:54:11 -08002438 // Open and create the snapshot profile.
2439 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2440
2441 // Collect all non empty profiles.
2442 // The collection will traverse all applications profiles and find the non empty files.
2443 // This has the potential of inspecting a large number of files and directories (depending
2444 // on the number of applications and users). So there is a slight increase in the chance
2445 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2446 // fail the snapshot and aggregate whatever profile we could open.
2447 //
2448 // The profile snapshot is a best effort based on available data it's ok if some data
2449 // from some apps is missing. It will be counter productive for the snapshot to fail
2450 // because we could not open or read some of the files.
2451 std::vector<std::string> profiles;
2452 if (!collect_profiles(&profiles)) {
2453 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2454 }
2455
2456 // If we have no profiles return early.
2457 if (profiles.empty()) {
2458 return true;
2459 }
2460
2461 // Open the classpath elements. These will be used to filter out profile data that does
2462 // not belong to the classpath during merge.
2463 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002464 std::vector<std::string> dex_locations;
2465 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002466 return false;
2467 }
2468
2469 // If we could not open any files from the classpath return an error.
2470 if (apk_fds.empty()) {
2471 LOG(ERROR) << "Could not open any of the classpath elements.";
2472 return false;
2473 }
2474
2475 // Aggregate the profiles in batches of kAggregationBatchSize.
2476 // We do this to avoid opening a huge a amount of files.
2477 static constexpr size_t kAggregationBatchSize = 10;
2478
Calin Juravle0d0a4922018-01-23 19:54:11 -08002479 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002480 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002481 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2482 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2483 if (fd.get() >= 0) {
2484 profiles_fd.push_back(std::move(fd));
2485 }
2486 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002487
2488 // We aggregate (read & write) into the same fd multiple times in a row.
2489 // We need to reset the cursor every time to ensure we read the whole file every time.
2490 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2491 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2492 return false;
2493 }
2494
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002495 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002496 args.SetupMerge(profiles_fd,
2497 snapshot_fd,
2498 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002499 dex_locations,
2500 /*for_snapshot=*/true,
2501 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002502 pid_t pid = fork();
2503 if (pid == 0) {
2504 /* child -- drop privileges before continuing */
2505 drop_capabilities(AID_SYSTEM);
2506
Calin Juravle59f7ab82018-04-27 17:50:23 -07002507 // The introduction of new access flags into boot jars causes them to
2508 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002509 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002510 }
2511
2512 /* parent */
2513 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002514
Calin Juravle0d0a4922018-01-23 19:54:11 -08002515 if (!WIFEXITED(return_code)) {
2516 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2517 return false;
2518 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002519
2520 // Verify that profman finished successfully.
2521 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002522 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2523 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2524 << ":" << profman_code;
2525 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002526 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002527 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002528
Calin Juravle0d0a4922018-01-23 19:54:11 -08002529 return true;
2530}
2531
2532bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2533 const std::string& profile_name, const std::string& classpath) {
2534 if (app_id == -1) {
2535 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2536 } else {
2537 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2538 }
2539}
2540
Calin Juravlec3b049e2018-01-18 22:32:58 -08002541bool prepare_app_profile(const std::string& package_name,
2542 userid_t user_id,
2543 appid_t app_id,
2544 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002545 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002546 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002547 // Prepare the current profile.
2548 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2549 /*is_secondary_dex*/ false);
2550 uid_t uid = multiuser_get_uid(user_id, app_id);
2551 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2552 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2553 return false;
2554 }
2555
2556 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002557 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002558 return true;
2559 }
2560
2561 // We have a dex metdata. Merge the profile into the reference profile.
2562 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2563 /*read_write*/ true, /*is_secondary_dex*/ false);
2564 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2565 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002566 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2567 if (apk_fd < 0) {
2568 PLOG(ERROR) << "Could not open code path " << code_path;
2569 return false;
2570 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002571
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002572 RunProfman args;
2573 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2574 std::move(ref_profile_fd),
2575 std::move(apk_fd),
2576 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002577 pid_t pid = fork();
2578 if (pid == 0) {
2579 /* child -- drop privileges before continuing */
2580 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2581 drop_capabilities(app_shared_gid);
2582
Calin Juravlef63d4792018-01-30 17:43:34 +00002583 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002584 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002585 }
2586
2587 /* parent */
2588 int return_code = wait_child(pid);
2589 if (!WIFEXITED(return_code)) {
2590 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2591 return false;
2592 }
2593 return true;
2594}
2595
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002596} // namespace installd
2597} // namespace android