blob: 204953cd0701c2ec8d57f797ba1e144e167e5710 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Martijn Coenen6de402a2021-04-26 16:23:40 +020039#include <async_safe/log.h>
Calin Juravle80a21252017-01-17 14:43:25 -080040#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include <cutils/properties.h>
42#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000048#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080052#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070053#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060054#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070055#include "installd_deps.h"
56#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070057#include "run_dex2oat.h"
Victor Hsiehcb35a062020-08-13 16:11:13 -070058#include "unique_file.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070059#include "utils.h"
60
Victor Hsieh76f19ba2020-08-10 14:37:26 -070061using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070062using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070063using android::base::GetBoolProperty;
64using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000065using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010066using android::base::ReadFully;
67using android::base::StringPrintf;
68using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080069using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070070
71namespace android {
72namespace installd {
73
Andreas Gampefa2dadd2018-02-28 19:52:47 -080074
Calin Juravle114f0812017-03-08 19:05:07 -080075// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
76struct FreeDelete {
77 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
78 void operator()(const void* ptr) const {
79 free(const_cast<void*>(ptr));
80 }
81};
82
83// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
84template <typename T>
85using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
86
Calin Juravle1a0af3b2017-03-09 14:33:33 -080087static unique_fd invalid_unique_fd() {
88 return unique_fd(-1);
89}
90
Andreas Gampe6a9cf722017-07-24 16:49:10 -070091static bool is_debug_runtime() {
92 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
93}
94
David Sehra3b5ab62017-10-25 14:27:29 -070095static bool is_debuggable_build() {
96 return android::base::GetBoolProperty("ro.debuggable", false);
97}
98
Jeff Sharkey90aff262016-12-12 14:28:24 -070099static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800100 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700101 if (ufd.get() < 0) {
102 if (errno != ENOENT) {
103 PLOG(WARNING) << "Could not open profile " << profile;
104 return false;
105 } else {
106 // Nothing to clear. That's ok.
107 return true;
108 }
109 }
110
111 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
112 if (errno != EWOULDBLOCK) {
113 PLOG(WARNING) << "Error locking profile " << profile;
114 }
115 // This implies that the app owning this profile is running
116 // (and has acquired the lock).
117 //
118 // If we can't acquire the lock bail out since clearing is useless anyway
119 // (the app will write again to the profile).
120 //
121 // Note:
122 // This does not impact the this is not an issue for the profiling correctness.
123 // In case this is needed because of an app upgrade, profiles will still be
124 // eventually cleared by the app itself due to checksum mismatch.
125 // If this is needed because profman advised, then keeping the data around
126 // until the next run is again not an issue.
127 //
128 // If the app attempts to acquire a lock while we've held one here,
129 // it will simply skip the current write cycle.
130 return false;
131 }
132
133 bool truncated = ftruncate(ufd.get(), 0) == 0;
134 if (!truncated) {
135 PLOG(WARNING) << "Could not truncate " << profile;
136 }
137 if (flock(ufd.get(), LOCK_UN) != 0) {
138 PLOG(WARNING) << "Error unlocking profile " << profile;
139 }
140 return truncated;
141}
142
Calin Juravle114f0812017-03-08 19:05:07 -0800143// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800144// The location is the profile name for primary apks or the dex path for secondary dex files.
145static bool clear_reference_profile(const std::string& package_name, const std::string& location,
146 bool is_secondary_dex) {
147 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700148}
149
Calin Juravle114f0812017-03-08 19:05:07 -0800150// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800151// The location is the profile name for primary apks or the dex path for secondary dex files.
152static bool clear_current_profile(const std::string& package_name, const std::string& location,
153 userid_t user, bool is_secondary_dex) {
154 return clear_profile(create_current_profile_path(user, package_name, location,
155 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700156}
157
Calin Juravle114f0812017-03-08 19:05:07 -0800158// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800159// The location is the profile name for primary apks or the dex path for secondary dex files.
160bool clear_primary_reference_profile(const std::string& package_name,
161 const std::string& location) {
162 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800163}
164
165// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800166// The location is the profile name for primary apks or the dex path for secondary dex files.
167bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700168 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800169 // 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 -0700170 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
171 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800172 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700173 }
174 return success;
175}
176
Calin Juravle114f0812017-03-08 19:05:07 -0800177// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800178bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
179 userid_t user) {
180 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800181}
182
Calin Juravlef74a7372019-02-28 20:29:41 -0800183// Determines which binary we should use for execution (the debug or non-debug version).
184// e.g. dex2oatd vs dex2oat
185static const char* select_execution_binary(const char* binary, const char* debug_binary,
186 bool background_job_compile) {
187 return select_execution_binary(
188 binary,
189 debug_binary,
190 background_job_compile,
191 is_debug_runtime(),
192 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
193 is_debuggable_build());
194}
195
196// Determines which binary we should use for execution (the debug or non-debug version).
197// e.g. dex2oatd vs dex2oat
198// This is convenient method which is much easier to test because it doesn't read
199// system properties.
200const char* select_execution_binary(
201 const char* binary,
202 const char* debug_binary,
203 bool background_job_compile,
204 bool is_debug_runtime,
205 bool is_release,
206 bool is_debuggable_build) {
207 // Do not use debug binaries for release candidates (to give more soak time).
208 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
209
210 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
211 // the file is present (it may not be on images with very little space available).
212 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
213
214 return useDebug ? debug_binary : binary;
215}
216
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000217// Namespace for Android Runtime flags applied during boot time.
218static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
219// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000220static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000221
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700222// Phenotype property name for enabling profiling the boot class path.
223static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
224
Calin Juravlef85ddb92020-05-01 14:05:40 -0700225static bool IsBootClassPathProfilingEnable() {
226 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
227 profile_boot_class_path =
228 server_configurable_flags::GetServerConfigurableFlag(
229 RUNTIME_NATIVE_BOOT_NAMESPACE,
230 PROFILE_BOOT_CLASS_PATH,
231 /*default_value=*/ profile_boot_class_path);
232 return profile_boot_class_path == "true";
233}
234
Victor Hsiehcb35a062020-08-13 16:11:13 -0700235static void UnlinkIgnoreResult(const std::string& path) {
236 if (unlink(path.c_str()) < 0) {
237 PLOG(ERROR) << "Failed to unlink " << path;
238 }
239}
240
Jeff Sharkey90aff262016-12-12 14:28:24 -0700241/*
242 * Whether dexopt should use a swap file when compiling an APK.
243 *
244 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
245 * itself, anyways).
246 *
247 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
248 *
249 * Otherwise, return true if this is a low-mem device.
250 *
251 * Otherwise, return default value.
252 */
253static bool kAlwaysProvideSwapFile = false;
254static bool kDefaultProvideSwapFile = true;
255
256static bool ShouldUseSwapFileForDexopt() {
257 if (kAlwaysProvideSwapFile) {
258 return true;
259 }
260
261 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700262 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
263 if (!dex2oat_prop_buf.empty()) {
264 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700265 }
266
267 // Shortcut for default value. This is an implementation optimization for the process sketched
268 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
269 // as low-mem is never returning false. The compiler will optimize this away if it can.
270 if (kDefaultProvideSwapFile) {
271 return true;
272 }
273
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700274 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700275 return true;
276 }
277
278 // Default value must be false here.
279 return kDefaultProvideSwapFile;
280}
281
Richard Uhler76cc0272016-12-08 10:46:35 +0000282static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700283 if (set_to_bg) {
284 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800285 PLOG(ERROR) << "set_sched_policy failed";
286 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700287 }
288 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800289 PLOG(ERROR) << "setpriority failed";
290 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700291 }
292 }
293}
294
Calin Juravle29591732017-11-20 17:46:19 -0800295static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
296 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800297 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800298 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800299 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800300 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800301 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700302 }
Calin Juravle114f0812017-03-08 19:05:07 -0800303 // Profiles should belong to the app; make sure of that by giving ownership to
304 // the app uid. If we cannot do that, there's no point in returning the fd
305 // since dex2oat/profman will fail with SElinux denials.
306 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000307 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800308 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800309 }
Calin Juravle29591732017-11-20 17:46:19 -0800310 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800311}
312
Calin Juravle29591732017-11-20 17:46:19 -0800313static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800314 // Do not follow symlinks when opening a profile:
315 // - primary profiles should not contain symlinks in their paths
316 // - secondary dex paths should have been already resolved and validated
317 flags |= O_NOFOLLOW;
318
Calin Juravle29591732017-11-20 17:46:19 -0800319 // Check if we need to create the profile
320 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
321 unique_fd fd;
322 if ((flags & O_CREAT) != 0) {
323 fd = create_profile(uid, profile, flags);
324 } else {
325 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
326 }
327
Calin Juravle114f0812017-03-08 19:05:07 -0800328 if (fd.get() < 0) {
329 if (errno != ENOENT) {
330 // Profiles might be missing for various reasons. For example, in a
331 // multi-user environment, the profile directory for one user can be created
332 // after we start a merge. In this case the current profile for that user
333 // will not be found.
334 // Also, the secondary dex profiles might be deleted by the app at any time,
335 // so we can't we need to prepare if they are missing.
336 PLOG(ERROR) << "Failed to open profile " << profile;
337 }
338 return invalid_unique_fd();
339 }
340
Jeff Sharkey90aff262016-12-12 14:28:24 -0700341 return fd;
342}
343
Calin Juravle824a64d2018-01-18 20:23:17 -0800344static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
345 const std::string& location, bool is_secondary_dex) {
346 std::string profile = create_current_profile_path(user, package_name, location,
347 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800348 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800349}
350
Calin Juravle824a64d2018-01-18 20:23:17 -0800351static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
352 const std::string& location, bool read_write, bool is_secondary_dex) {
353 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800354 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
355}
356
Victor Hsiehcb35a062020-08-13 16:11:13 -0700357static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
358 const std::string& location, bool read_write, bool is_secondary_dex) {
359 std::string profile_path = create_reference_profile_path(package_name, location,
360 is_secondary_dex);
361 unique_fd ufd = open_profile(uid, profile_path, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
362 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
363 clear_profile(path);
364 });
365}
366
Calin Juravle29591732017-11-20 17:46:19 -0800367static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800368 const std::string& location) {
369 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800370 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800371}
372
Calin Juravle824a64d2018-01-18 20:23:17 -0800373static void open_profile_files(uid_t uid, const std::string& package_name,
374 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800375 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700376 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800377 *reference_profile_fd = open_reference_profile(uid, package_name, location,
378 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700379
Calin Juravle114f0812017-03-08 19:05:07 -0800380 // For secondary dex files, we don't really need the user but we use it for sanity checks.
381 // Note: the user owning the dex file should be the current user.
382 std::vector<userid_t> users;
383 if (is_secondary_dex){
384 users.push_back(multiuser_get_user_id(uid));
385 } else {
386 users = get_known_users(/*volume_uuid*/ nullptr);
387 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700388 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800389 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
390 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700391 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800392 if (profile_fd.get() >= 0) {
393 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700394 }
395 }
396}
397
Calin Juravle76561322019-11-14 09:08:52 -0800398static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
399static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
400static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
401static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
402static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
403static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
404static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700405
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800406class RunProfman : public ExecVHelper {
407 public:
408 void SetupArgs(const std::vector<unique_fd>& profile_fds,
409 const unique_fd& reference_profile_fd,
410 const std::vector<unique_fd>& apk_fds,
411 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800412 bool copy_and_update,
413 bool for_snapshot,
414 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800415
416 // TODO(calin): Assume for now we run in the bg compile job (which is in
417 // most of the invocation). With the current data flow, is not very easy or
418 // clean to discover this in RunProfman (it will require quite a messy refactoring).
419 const char* profman_bin = select_execution_binary(
420 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700421
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800422 if (copy_and_update) {
423 CHECK_EQ(1u, profile_fds.size());
424 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000425 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800426 if (reference_profile_fd != -1) {
427 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000428 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800429
430 for (const unique_fd& fd : profile_fds) {
431 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
432 }
433
434 for (const unique_fd& fd : apk_fds) {
435 AddArg("--apk-fd=" + std::to_string(fd.get()));
436 }
437
438 for (const std::string& dex_location : dex_locations) {
439 AddArg("--dex-location=" + dex_location);
440 }
441
442 if (copy_and_update) {
443 AddArg("--copy-and-update-profile-key");
444 }
445
Calin Juravle78728f32019-11-08 17:55:46 -0800446 if (for_snapshot) {
447 AddArg("--force-merge");
448 }
449
450 if (for_boot_image) {
451 AddArg("--boot-image-merge");
452 }
453
yawannga27559e2020-11-13 19:17:44 +0000454 // The percent won't exceed 100, otherwise, don't set it and use the
455 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000456 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000457 "dalvik.vm.bgdexopt.new-classes-percent",
458 /*default*/std::numeric_limits<uint32_t>::max());
459 if (min_new_classes_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000460 AddArg("--min-new-classes-percent-change=" +
461 std::to_string(min_new_classes_percent_change));
462 }
463
yawannga27559e2020-11-13 19:17:44 +0000464 // The percent won't exceed 100, otherwise, don't set it and use the
465 // default one set in profman.
yawanng6fe34a52020-11-06 05:13:53 +0000466 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
yawannga27559e2020-11-13 19:17:44 +0000467 "dalvik.vm.bgdexopt.new-methods-percent",
468 /*default*/std::numeric_limits<uint32_t>::max());
469 if (min_new_methods_percent_change <= 100) {
yawanng6fe34a52020-11-06 05:13:53 +0000470 AddArg("--min-new-methods-percent-change=" +
471 std::to_string(min_new_methods_percent_change));
472 }
473
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800474 // Do not add after dex2oat_flags, they should override others for debugging.
475 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800476 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700477
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800478 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
479 const unique_fd& reference_profile_fd,
480 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800481 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
482 bool for_snapshot = false,
483 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800484 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800485 reference_profile_fd,
486 apk_fds,
487 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800488 /*copy_and_update=*/ false,
489 for_snapshot,
490 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800491 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700492
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800493 void SetupCopyAndUpdate(unique_fd&& profile_fd,
494 unique_fd&& reference_profile_fd,
495 unique_fd&& apk_fd,
496 const std::string& dex_location) {
497 // The fds need to stay open longer than the scope of the function, so put them into a local
498 // variable vector.
499 profiles_fd_.push_back(std::move(profile_fd));
500 apk_fds_.push_back(std::move(apk_fd));
501 reference_profile_fd_ = std::move(reference_profile_fd);
502 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800503 SetupArgs(profiles_fd_,
504 reference_profile_fd_,
505 apk_fds_,
506 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800507 /*copy_and_update=*/true,
508 /*for_snapshot*/false,
509 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800510 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000511
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800512 void SetupDump(const std::vector<unique_fd>& profiles_fd,
513 const unique_fd& reference_profile_fd,
514 const std::vector<std::string>& dex_locations,
515 const std::vector<unique_fd>& apk_fds,
516 const unique_fd& output_fd) {
517 AddArg("--dump-only");
518 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800519 SetupArgs(profiles_fd,
520 reference_profile_fd,
521 apk_fds,
522 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800523 /*copy_and_update=*/false,
524 /*for_snapshot*/false,
525 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800526 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000527
Victor Hsiehc9821f12020-08-07 11:32:29 -0700528 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800529 void Exec() {
530 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
531 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000532
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800533 private:
534 unique_fd reference_profile_fd_;
535 std::vector<unique_fd> profiles_fd_;
536 std::vector<unique_fd> apk_fds_;
537};
Mathieu Chartier31636522018-11-09 23:53:07 +0000538
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800539
Calin Juravlef63d4792018-01-30 17:43:34 +0000540
Jeff Sharkey90aff262016-12-12 14:28:24 -0700541// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800542// The location is the package name for primary apks or the dex path for secondary dex files.
543// Returns true if there is enough information in the current profiles that makes it
544// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700545// If the return value is true all the current profiles would have been merged into
546// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800547static bool analyze_profiles(uid_t uid, const std::string& package_name,
548 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800549 std::vector<unique_fd> profiles_fd;
550 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800551 open_profile_files(uid, package_name, location, is_secondary_dex,
552 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800553 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700554 // Skip profile guided compilation because no profiles were found.
555 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700556 return false;
557 }
558
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800559 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700560 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
561 const std::vector<std::string>& dex_locations = std::vector<std::string>();
562 profman_merge.SetupMerge(
563 profiles_fd,
564 reference_profile_fd,
565 apk_fds,
566 dex_locations,
567 /* for_snapshot= */ false,
568 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700569 pid_t pid = fork();
570 if (pid == 0) {
571 /* child -- drop privileges before continuing */
572 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800573 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700574 }
575 /* parent */
576 int return_code = wait_child(pid);
577 bool need_to_compile = false;
578 bool should_clear_current_profiles = false;
579 bool should_clear_reference_profile = false;
580 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800581 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700582 } else {
583 return_code = WEXITSTATUS(return_code);
584 switch (return_code) {
585 case PROFMAN_BIN_RETURN_CODE_COMPILE:
586 need_to_compile = true;
587 should_clear_current_profiles = true;
588 should_clear_reference_profile = false;
589 break;
590 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
591 need_to_compile = false;
592 should_clear_current_profiles = false;
593 should_clear_reference_profile = false;
594 break;
595 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800596 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700597 need_to_compile = false;
598 should_clear_current_profiles = true;
599 should_clear_reference_profile = true;
600 break;
601 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
602 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
603 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800604 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605 need_to_compile = false;
606 should_clear_current_profiles = false;
607 should_clear_reference_profile = false;
608 break;
Calin Juravle76561322019-11-14 09:08:52 -0800609 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
610 need_to_compile = false;
611 should_clear_current_profiles = true;
612 should_clear_reference_profile = true;
613 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 default:
615 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800616 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800617 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700618 need_to_compile = false;
619 should_clear_current_profiles = true;
620 should_clear_reference_profile = true;
621 break;
622 }
623 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800624
Jeff Sharkey90aff262016-12-12 14:28:24 -0700625 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800626 if (is_secondary_dex) {
627 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800628 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
629 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800630 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800631 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800632 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 }
634 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800635 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700636 }
637 return need_to_compile;
638}
639
Calin Juravle114f0812017-03-08 19:05:07 -0800640// Decides if profile guided compilation is needed or not based on existing profiles.
641// The analysis is done for the primary apks of the given package.
642// Returns true if there is enough information in the current profiles that makes it
643// worth to recompile the package.
644// If the return value is true all the current profiles would have been merged into
645// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800646bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
647 const std::string& profile_name) {
648 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800649}
650
Calin Juravle408cd4a2018-01-20 23:34:18 -0800651bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
652 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800653 std::vector<unique_fd> profile_fds;
654 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800655 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
656 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700657
Calin Juravle408cd4a2018-01-20 23:34:18 -0800658 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800659 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700660
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800661 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700662 const bool has_profiles = !profile_fds.empty();
663
664 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800665 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700666 return false;
667 }
668
Calin Juravle114f0812017-03-08 19:05:07 -0800669 unique_fd output_fd(open(out_file_name.c_str(),
670 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800672 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700673 return false;
674 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800675
Jeff Sharkey90aff262016-12-12 14:28:24 -0700676 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800677 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800678 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
679 if (apk_fd == -1) {
680 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
681 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700682 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700683 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800684 apk_fds.push_back(std::move(apk_fd));
685
Jeff Sharkey90aff262016-12-12 14:28:24 -0700686
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800687 RunProfman profman_dump;
688 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689 pid_t pid = fork();
690 if (pid == 0) {
691 /* child -- drop privileges before continuing */
692 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800693 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694 }
695 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700696 int return_code = wait_child(pid);
697 if (!WIFEXITED(return_code)) {
698 LOG(WARNING) << "profman failed for package " << pkgname << ": "
699 << return_code;
700 return false;
701 }
702 return true;
703}
704
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700705bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800706 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700707 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
708 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800709 package_name,
710 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700711 /*read_write*/ true,
712 /*secondary*/ false));
713 if (in_fd.get() < 0) {
714 PLOG(WARNING) << "Could not open profile " << system_profile;
715 return false;
716 }
717 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800718 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700719 return false;
720 }
721
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700722 // As a security measure we want to write the profile information with the reduced capabilities
723 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700724 pid_t pid = fork();
725 if (pid == 0) {
726 /* child -- drop privileges before continuing */
727 drop_capabilities(packageUid);
728
729 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
730 if (errno != EWOULDBLOCK) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200731 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
732 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700733 }
734 // This implies that the app owning this profile is running
735 // (and has acquired the lock).
736 //
737 // The app never acquires the lock for the reference profiles of primary apks.
738 // Only dex2oat from installd will do that. Since installd is single threaded
739 // we should not see this case. Nevertheless be prepared for it.
Martijn Coenen6de402a2021-04-26 16:23:40 +0200740 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
741 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700742 return false;
743 }
744
745 bool truncated = ftruncate(out_fd.get(), 0) == 0;
746 if (!truncated) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200747 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
748 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700749 }
750
751 // Copy over data.
752 static constexpr size_t kBufferSize = 4 * 1024;
753 char buffer[kBufferSize];
754 while (true) {
755 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
756 if (bytes == 0) {
757 break;
758 }
759 write(out_fd.get(), buffer, bytes);
760 }
761 if (flock(out_fd.get(), LOCK_UN) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +0200762 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
763 package_name.c_str(), errno);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700764 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700765 // Use _exit since we don't want to run the global destructors in the child.
766 // b/62597429
767 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700768 }
769 /* parent */
770 int return_code = wait_child(pid);
771 return return_code == 0;
772}
773
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
775 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
776 if (EndsWith(oat_path, ".dex")) {
777 std::string new_path = oat_path;
778 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800779 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700780 return new_path;
781 }
782
783 // An odex entry. Not that this may not be an extension, e.g., in the OTA
784 // case (where the base name will have an extension for the B artifact).
785 size_t odex_pos = oat_path.rfind(".odex");
786 if (odex_pos != std::string::npos) {
787 std::string new_path = oat_path;
788 new_path.replace(odex_pos, strlen(".odex"), new_ext);
789 CHECK_NE(new_path.find(new_ext), std::string::npos);
790 return new_path;
791 }
792
793 // Don't know how to handle this.
794 return "";
795}
796
797// Translate the given oat path to an art (app image) path. An empty string
798// denotes an error.
799static std::string create_image_filename(const std::string& oat_path) {
800 return replace_file_extension(oat_path, ".art");
801}
802
803// Translate the given oat path to a vdex path. An empty string denotes an error.
804static std::string create_vdex_filename(const std::string& oat_path) {
805 return replace_file_extension(oat_path, ".vdex");
806}
807
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808static int open_output_file(const char* file_name, bool recreate, int permissions) {
809 int flags = O_RDWR | O_CREAT;
810 if (recreate) {
811 if (unlink(file_name) < 0) {
812 if (errno != ENOENT) {
813 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
814 }
815 }
816 flags |= O_EXCL;
817 }
818 return open(file_name, flags, permissions);
819}
820
Calin Juravle2289c0a2017-02-15 12:44:14 -0800821static bool set_permissions_and_ownership(
822 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
823 // Primary apks are owned by the system. Secondary dex files are owned by the app.
824 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825 if (fchmod(fd,
826 S_IRUSR|S_IWUSR|S_IRGRP |
827 (is_public ? S_IROTH : 0)) < 0) {
828 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
829 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800830 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700831 ALOGE("installd cannot chown '%s' during dexopt\n", path);
832 return false;
833 }
834 return true;
835}
836
837static bool IsOutputDalvikCache(const char* oat_dir) {
838 // InstallerConnection.java (which invokes installd) transforms Java null arguments
839 // into '!'. Play it safe by handling it both.
840 // TODO: ensure we never get null.
841 // TODO: pass a flag instead of inferring if the output is dalvik cache.
842 return oat_dir == nullptr || oat_dir[0] == '!';
843}
844
Calin Juravled23dee72017-07-06 16:29:11 -0700845// Best-effort check whether we can fit the the path into our buffers.
846// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
847// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
848// extension to the cache path (5 bytes).
849// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
850static bool validate_dex_path_size(const std::string& dex_path) {
851 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
852 LOG(ERROR) << "dex_path too long: " << dex_path;
853 return false;
854 }
855 return true;
856}
857
Jeff Sharkey90aff262016-12-12 14:28:24 -0700858static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800859 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700860 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700861 return false;
862 }
863
864 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800865 // Oat dirs for secondary dex files are already validated.
866 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
868 return false;
869 }
870 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
871 return false;
872 }
873 } else {
874 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
875 return false;
876 }
877 }
878 return true;
879}
880
Calin Juravle7a570e82017-01-14 16:23:30 -0800881// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700882UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700883 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100884
Calin Juravle7a570e82017-01-14 16:23:30 -0800885 const std::string image_path = create_image_filename(out_oat_path);
886 if (image_path.empty()) {
887 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700888 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800889 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100890
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700891 // In case there is a stale image, remove it now. Ignore any error.
892 unlink(image_path.c_str());
893
894 // Not enabled, exit.
895 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700896 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100897 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700898 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
899 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700900 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800901 }
902 // Recreate is true since we do not want to modify a mapped image. If the app is
903 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -0700904 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -0800905 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -0700906 image_path,
907 UnlinkIgnoreResult);
908 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800909 // Could not create application image file. Go on since we can compile without it.
910 LOG(ERROR) << "installd could not create '" << image_path
911 << "' for image file during dexopt";
912 // If we have a valid image file path but no image fd, explicitly erase the image file.
913 if (unlink(image_path.c_str()) < 0) {
914 if (errno != ENOENT) {
915 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
916 }
917 }
918 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -0700919 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800920 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -0700921 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -0800922 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700923
Victor Hsiehcb35a062020-08-13 16:11:13 -0700924 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -0800925}
926
927// Creates the dexopt swap file if necessary and return its fd.
928// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700929unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800930 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800931 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -0800932 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700933 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800934 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600935 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -0800936 if (swap_fd.get() < 0) {
937 // Could not create swap file. Optimistically go on and hope that we can compile
938 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600939 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -0800940 } else {
941 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600942 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800943 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
944 }
945 }
946 return swap_fd;
947}
948
949// Opens the reference profiles if needed.
950// 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 -0700951UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000952 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -0800953 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +0000954 // If we are not profile guided compilation, or we are compiling system server
955 // do not bother to open the profiles; we won't be using them.
956 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700957 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +0000958 }
959
960 // If this is a secondary dex path which is public do not open the profile.
961 // We cannot compile public secondary dex paths with profiles. That's because
962 // it will expose how the dex files are used by their owner.
963 //
964 // Note that the PackageManager is responsible to set the is_public flag for
965 // primary apks and we do not check it here. In some cases, e.g. when
966 // compiling with a public profile from the .dm file the PackageManager will
967 // set is_public toghether with the profile guided compilation.
968 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700969 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700970 }
Calin Juravle114f0812017-03-08 19:05:07 -0800971
972 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000973 std::string location;
974 if (is_secondary_dex) {
975 location = dex_path;
976 } else {
977 if (profile_name == nullptr) {
978 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700979 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000980 } else {
981 location = profile_name;
982 }
983 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700984 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
985 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -0800986}
Jeff Sharkey90aff262016-12-12 14:28:24 -0700987
Victor Hsiehcb35a062020-08-13 16:11:13 -0700988// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
989// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -0700990bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +0000991 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -0700992 bool profile_guided, UniqueFile* in_vdex_wrapper,
993 UniqueFile* out_vdex_wrapper) {
994 CHECK(in_vdex_wrapper != nullptr);
995 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700996 // Open the existing VDEX. We do this before creating the new output VDEX, which will
997 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +0000998 char in_odex_path[PKG_PATH_MAX];
999 int dexopt_action = abs(dexopt_needed);
1000 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001001
1002 // Infer the name of the output VDEX.
1003 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1004 if (out_vdex_path_str.empty()) {
1005 return false;
1006 }
1007
1008 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001009 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001010 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1011 const char* path = nullptr;
1012 if (is_odex_location) {
1013 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1014 path = in_odex_path;
1015 } else {
1016 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001017 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018 }
1019 } else {
1020 path = out_oat_path;
1021 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001022 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001023 if (in_vdex_path_str.empty()) {
1024 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001025 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001026 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001027 // We can update in place when all these conditions are met:
1028 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1029 // on /system typically cannot be updated in place).
1030 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1031 // cannot be currently used by a running process.
1032 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1033 // different vdex files to operate.
1034 update_vdex_in_place =
1035 (in_vdex_path_str == out_vdex_path_str) &&
1036 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1037 !profile_guided;
1038 if (update_vdex_in_place) {
1039 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001040 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1041 in_vdex_path_str);
1042 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001043 // If we failed to open the file, we cannot update it in place.
1044 update_vdex_in_place = false;
1045 }
1046 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001047 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1048 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001049 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001050 }
1051
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001052 // If we are updating the vdex in place, we do not need to recreate a vdex,
1053 // and can use the same existing one.
1054 if (update_vdex_in_place) {
1055 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1056 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001057 out_vdex_wrapper->reset(
1058 in_vdex_wrapper->fd(),
1059 out_vdex_path_str,
1060 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001061 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1062 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001063 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001064 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001065 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001066 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001067 out_vdex_path_str,
1068 UnlinkIgnoreResult);
1069 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001070 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1071 return false;
1072 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001073 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001074 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001075 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001076 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1077 return false;
1078 }
1079
1080 // If we got here we successfully opened the vdex files.
1081 return true;
1082}
1083
1084// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001085UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1086 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1087 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001088 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001089 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001090 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001091 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001092 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001093 out_oat_path,
1094 UnlinkIgnoreResult);
1095 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001096 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001097 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001098 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001099 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001100 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001101 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001102 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001103}
1104
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001105// Creates RDONLY fds for oat and vdex files, if exist.
1106// Returns false if it fails to create oat out path for the given apk path.
1107// Note that the method returns true even if the files could not be opened.
1108bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1109 const std::string& oat_dir,
1110 const std::string& instruction_set,
1111 bool is_secondary_dex,
1112 unique_fd* oat_file_fd,
1113 unique_fd* vdex_file_fd) {
1114 char oat_path[PKG_PATH_MAX];
1115 if (!create_oat_out_path(apk_path.c_str(),
1116 instruction_set.c_str(),
1117 oat_dir.c_str(),
1118 is_secondary_dex,
1119 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001120 LOG(ERROR) << "Could not create oat out path for "
1121 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001122 return false;
1123 }
1124 oat_file_fd->reset(open(oat_path, O_RDONLY));
1125 if (oat_file_fd->get() < 0) {
1126 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1127 }
1128
1129 std::string vdex_filename = create_vdex_filename(oat_path);
1130 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1131 if (vdex_file_fd->get() < 0) {
1132 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1133 }
1134
1135 return true;
1136}
1137
Calin Juravle80a21252017-01-17 14:43:25 -08001138// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001139// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1140// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1141// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001142class RunDexoptAnalyzer : public ExecVHelper {
1143 public:
1144 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001145 int vdex_fd,
1146 int oat_fd,
1147 int zip_fd,
1148 const std::string& instruction_set,
1149 const std::string& compiler_filter,
1150 bool profile_was_updated,
1151 bool downgrade,
1152 const char* class_loader_context,
1153 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001154 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001155
1156 // We always run the analyzer in the background job.
1157 const char* dexoptanalyzer_bin = select_execution_binary(
1158 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001159
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001160 std::string dex_file_arg = "--dex-file=" + dex_file;
1161 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1162 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1163 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1164 std::string isa_arg = "--isa=" + instruction_set;
1165 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1166 const char* assume_profile_changed = "--assume-profile-changed";
1167 const char* downgrade_flag = "--downgrade";
1168 std::string class_loader_context_arg = "--class-loader-context=";
1169 if (class_loader_context != nullptr) {
1170 class_loader_context_arg += class_loader_context;
1171 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001172 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1173 if (!class_loader_context_fds.empty()) {
1174 class_loader_context_fds_arg += class_loader_context_fds;
1175 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001176
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001177 // program name, dex file, isa, filter
1178 AddArg(dex_file_arg);
1179 AddArg(isa_arg);
1180 AddArg(compiler_filter_arg);
1181 if (oat_fd >= 0) {
1182 AddArg(oat_fd_arg);
1183 }
1184 if (vdex_fd >= 0) {
1185 AddArg(vdex_fd_arg);
1186 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001187 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001188 if (profile_was_updated) {
1189 AddArg(assume_profile_changed);
1190 }
1191 if (downgrade) {
1192 AddArg(downgrade_flag);
1193 }
1194 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001195 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001196 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001197 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001198 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001199 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001200
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001201 PrepareArgs(dexoptanalyzer_bin);
1202 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001203
1204 // Dexoptanalyzer mode which flattens the given class loader context and
1205 // prints a list of its dex files in that flattened order.
1206 RunDexoptAnalyzer(const char* class_loader_context) {
1207 CHECK(class_loader_context != nullptr);
1208
1209 // We always run the analyzer in the background job.
1210 const char* dexoptanalyzer_bin = select_execution_binary(
1211 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1212
1213 AddArg("--flatten-class-loader-context");
1214 AddArg(std::string("--class-loader-context=") + class_loader_context);
1215 PrepareArgs(dexoptanalyzer_bin);
1216 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001217};
Calin Juravle80a21252017-01-17 14:43:25 -08001218
1219// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001220static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001221 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001222 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001223 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001224 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001225 return false;
1226 }
Calin Juravle114f0812017-03-08 19:05:07 -08001227 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001228
Calin Juravle80a21252017-01-17 14:43:25 -08001229 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001230 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1231 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001232 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001233 return false;
1234 }
1235
1236 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001237 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001238
Calin Juravle7d765462017-09-04 15:57:10 -07001239 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001240 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001241 return false;
1242 }
1243
1244 return true;
1245}
1246
Calin Juravle7d765462017-09-04 15:57:10 -07001247// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1248// secondary dex files. This return codes are returned by the child process created for
1249// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001250
Andreas Gampe194fe422018-02-28 20:16:19 -08001251enum DexoptAnalyzerSkipCodes {
1252 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001253 // Specific errors are encoded in the name.
1254 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1255 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1256 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1257 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1258 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001259 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001260 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001261};
Calin Juravle7d765462017-09-04 15:57:10 -07001262
1263// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001264// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1265// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001266// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1267// of dexoptanalyzer.
1268static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001269 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001270 // The result values are defined in dexoptanalyzer.
1271 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001272 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001273 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001274 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001275 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001276 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001277 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001278 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001279 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001280 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1281 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001282 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1283 " Expected odex file status for secondary dex %s"
1284 " : dexoptanalyzer result=%d",
1285 dex_path.c_str(),
1286 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001287 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001288 }
1289
1290 // Use a second switch for enum switch-case analysis.
1291 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001292 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001293 // If the file does not exist there's no need for dexopt.
1294 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1295 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001296
1297 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1298 *error_msg = "Dexoptanalyzer path validation failed";
1299 return false;
1300 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1301 *error_msg = "Dexoptanalyzer open zip failed";
1302 return false;
1303 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1304 *error_msg = "Dexoptanalyzer dir preparation failed";
1305 return false;
1306 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1307 *error_msg = "Dexoptanalyzer open output failed";
1308 return false;
1309 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1310 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001311 return false;
1312 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001313
1314 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1315 dex_path.c_str(),
1316 result);
1317 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001318}
1319
Calin Juravle7d765462017-09-04 15:57:10 -07001320enum SecondaryDexAccess {
1321 kSecondaryDexAccessReadOk = 0,
1322 kSecondaryDexAccessDoesNotExist = 1,
1323 kSecondaryDexAccessPermissionError = 2,
1324 kSecondaryDexAccessIOError = 3
1325};
1326
1327static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1328 // Check if the path exists and can be read. If not, there's nothing to do.
1329 if (access(dex_path.c_str(), R_OK) == 0) {
1330 return kSecondaryDexAccessReadOk;
1331 } else {
1332 if (errno == ENOENT) {
1333 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1334 return kSecondaryDexAccessDoesNotExist;
1335 } else {
1336 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1337 return errno == EACCES
1338 ? kSecondaryDexAccessPermissionError
1339 : kSecondaryDexAccessIOError;
1340 }
1341 }
1342}
1343
1344static bool is_file_public(const std::string& filename) {
1345 struct stat file_stat;
1346 if (stat(filename.c_str(), &file_stat) == 0) {
1347 return (file_stat.st_mode & S_IROTH) != 0;
1348 }
1349 return false;
1350}
1351
1352// Create the oat file structure for the secondary dex 'dex_path' and assign
1353// the individual path component to the 'out_' parameters.
1354static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001355 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001356 size_t dirIndex = dex_path.rfind('/');
1357 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001358 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001359 return false;
1360 }
1361 // TODO(calin): we have similar computations in at lest 3 other places
1362 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1363 // using string append.
1364 std::string apk_dir = dex_path.substr(0, dirIndex);
1365 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1366 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1367
1368 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1369 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001370 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001371 return false;
1372 }
1373 return true;
1374}
1375
1376// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1377// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001378static bool validate_dexopt_storage_flags(int dexopt_flags,
1379 int* out_storage_flag,
1380 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001381 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1382 *out_storage_flag = FLAG_STORAGE_CE;
1383 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001384 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001385 return false;
1386 }
1387 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1388 *out_storage_flag = FLAG_STORAGE_DE;
1389 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001390 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001391 return false;
1392 }
1393 return true;
1394}
1395
David Brazdil4f6027a2019-03-19 11:44:21 +00001396static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1397 /* out */ std::vector<std::string>* context_dex_paths) {
1398 if (class_loader_context == nullptr) {
1399 return true;
1400 }
1401
1402 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1403
1404 // Pipe to get the hash result back from our child process.
1405 unique_fd pipe_read, pipe_write;
1406 if (!Pipe(&pipe_read, &pipe_write)) {
1407 PLOG(ERROR) << "Failed to create pipe";
1408 return false;
1409 }
1410
1411 pid_t pid = fork();
1412 if (pid == 0) {
1413 // child -- drop privileges before continuing.
1414 drop_capabilities(uid);
1415
1416 // Route stdout to `pipe_write`
1417 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1418 pipe_write.reset();
1419 pipe_read.reset();
1420
1421 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1422 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1423 }
1424
1425 /* parent */
1426 pipe_write.reset();
1427
1428 std::string str_dex_paths;
1429 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1430 PLOG(ERROR) << "Failed to read from pipe";
1431 return false;
1432 }
1433 pipe_read.reset();
1434
1435 int return_code = wait_child(pid);
1436 if (!WIFEXITED(return_code)) {
1437 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1438 return false;
1439 }
1440
1441 constexpr int kFlattenClassLoaderContextSuccess = 50;
1442 return_code = WEXITSTATUS(return_code);
1443 if (return_code != kFlattenClassLoaderContextSuccess) {
1444 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1445 return false;
1446 }
1447
1448 if (!str_dex_paths.empty()) {
1449 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1450 }
1451 return true;
1452}
1453
1454static int open_dex_paths(const std::vector<std::string>& dex_paths,
1455 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1456 for (const std::string& dex_path : dex_paths) {
1457 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1458 if (zip_fds->back().get() < 0) {
1459 *error_msg = StringPrintf(
1460 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1461 if (errno == ENOENT) {
1462 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1463 } else {
1464 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1465 }
1466 }
1467 }
1468 return 0;
1469}
1470
1471static std::string join_fds(const std::vector<unique_fd>& fds) {
1472 std::stringstream ss;
1473 bool is_first = true;
1474 for (const unique_fd& fd : fds) {
1475 if (is_first) {
1476 is_first = false;
1477 } else {
1478 ss << ":";
1479 }
1480 ss << fd.get();
1481 }
1482 return ss.str();
1483}
1484
Calin Juravlec9eab382017-01-25 01:17:17 -08001485// 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 -08001486// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1487// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001488// When returning true, the output parameters will be:
1489// - is_public_out: whether or not the oat file should not be made public
1490// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1491// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001492static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001493 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001494 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001495 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001496 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001497 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001498 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001499 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1500 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001501 return false;
1502 }
Calin Juravle7d765462017-09-04 15:57:10 -07001503 // Compute the oat dir as it's not easy to extract it from the child computation.
1504 char oat_path[PKG_PATH_MAX];
1505 char oat_dir[PKG_PATH_MAX];
1506 char oat_isa_dir[PKG_PATH_MAX];
1507 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001508 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1509 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001510 return false;
1511 }
Calin Juravle7d765462017-09-04 15:57:10 -07001512 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001513
Calin Juravle80a21252017-01-17 14:43:25 -08001514 pid_t pid = fork();
1515 if (pid == 0) {
1516 // child -- drop privileges before continuing.
1517 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001518
1519 // Validate the path structure.
1520 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001521 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1522 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001523 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001524 }
1525
1526 // Open the dex file.
1527 unique_fd zip_fd;
1528 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1529 if (zip_fd.get() < 0) {
1530 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001531 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001532 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001533 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001534 }
1535 }
1536
David Brazdil4f6027a2019-03-19 11:44:21 +00001537 // Open class loader context dex files.
1538 std::vector<unique_fd> context_zip_fds;
1539 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1540 if (open_dex_paths_rc != 0) {
1541 _exit(open_dex_paths_rc);
1542 }
1543
Calin Juravle7d765462017-09-04 15:57:10 -07001544 // Prepare the oat directories.
1545 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001546 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001547 }
1548
1549 // Open the vdex/oat files if any.
1550 unique_fd oat_file_fd;
1551 unique_fd vdex_file_fd;
1552 if (!maybe_open_oat_and_vdex_file(dex_path,
1553 *oat_dir_out,
1554 instruction_set,
1555 true /* is_secondary_dex */,
1556 &oat_file_fd,
1557 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001558 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001559 }
1560
1561 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001562 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1563 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001564
1565 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001566 // Note that we do not do it before the fork since opening the files is required to happen
1567 // after forking.
1568 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1569 vdex_file_fd.get(),
1570 oat_file_fd.get(),
1571 zip_fd.get(),
1572 instruction_set,
1573 compiler_filter, profile_was_updated,
1574 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001575 class_loader_context,
1576 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001577 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001578 }
1579
1580 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001581 int result = wait_child(pid);
1582 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001583 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1584 dex_path.c_str(),
1585 result);
1586 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001587 return false;
1588 }
1589 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001590 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001591 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1592 result,
1593 dexopt_needed_out,
1594 error_msg);
1595 if (!success) {
1596 LOG(ERROR) << *error_msg;
1597 }
Calin Juravle7d765462017-09-04 15:57:10 -07001598
1599 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1600
Calin Juravle80a21252017-01-17 14:43:25 -08001601 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001602 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1603 // makes the code simpler; force compilation is only needed during tests).
1604 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001605 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001606 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001607 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1608 }
1609
Calin Juravle7d765462017-09-04 15:57:10 -07001610 // Check if we should make the oat file public.
1611 // Note that if the dex file is not public the compiled code cannot be made public.
1612 // It is ok to check this flag outside in the parent process.
1613 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1614
Calin Juravle80a21252017-01-17 14:43:25 -08001615 return success;
1616}
1617
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001618static std::string format_dexopt_error(int status, const char* dex_path) {
1619 if (WIFEXITED(status)) {
1620 int int_code = WEXITSTATUS(status);
1621 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1622 if (code_name != nullptr) {
1623 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1624 }
1625 }
1626 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001627}
1628
Calin Juravlec9eab382017-01-25 01:17:17 -08001629int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001630 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001631 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001632 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001633 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001634 CHECK(pkgname != nullptr);
1635 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001636 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001637 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1638 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001639
Calin Juravled23dee72017-07-06 16:29:11 -07001640 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001641 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001642 return -1;
1643 }
1644
1645 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001646 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1647 class_loader_context);
1648 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001649 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001650 }
1651
Calin Juravleebc8a792017-04-04 20:21:05 -07001652 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001653 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1654 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1655 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001656 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001657 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001658 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001659 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001660 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001661 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001662
1663 // Check if we're dealing with a secondary dex file and if we need to compile it.
1664 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001665 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001666 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001667 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1668 *error_msg = "Failed acquiring context dex paths";
1669 return -1; // We had an error, logged in the process method.
1670 }
1671
Calin Juravlec9eab382017-01-25 01:17:17 -08001672 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001673 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00001674 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001675 oat_dir = oat_dir_str.c_str();
1676 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1677 return 0; // Nothing to do, report success.
1678 }
1679 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001680 if (error_msg->empty()) { // TODO: Make this a CHECK.
1681 *error_msg = "Failed processing secondary.";
1682 }
Calin Juravle80a21252017-01-17 14:43:25 -08001683 return -1; // We had an error, logged in the process method.
1684 }
1685 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001686 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001687 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001688 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1689 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1690 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001691
1692 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001693 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1694 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001695 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1696 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001697 return -1;
1698 }
1699
David Brazdil4f6027a2019-03-19 11:44:21 +00001700 // Open class loader context dex files.
1701 std::vector<unique_fd> context_input_fds;
1702 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1703 LOG(ERROR) << *error_msg;
1704 return -1;
1705 }
1706
Calin Juravle7a570e82017-01-14 16:23:30 -08001707 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001708 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1709 instruction_set, is_secondary_dex);
1710 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001711 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001712 return -1;
1713 }
1714
1715 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001716 UniqueFile in_vdex;
1717 UniqueFile out_vdex;
1718 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1719 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1720 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001721 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001722 return -1;
1723 }
1724
Calin Juravlecb556e32017-04-04 20:22:50 -07001725 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1726 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1727 // fully inherit their parent context).
1728 // Note that for primary apk the oat files are created before, in a separate installd
1729 // call which also does the restorecon. TODO(calin): unify the paths.
1730 if (is_secondary_dex) {
1731 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1732 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001733 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1734 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001735 return -1;
1736 }
1737 }
1738
Jeff Sharkey90aff262016-12-12 14:28:24 -07001739 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001740 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001741
Calin Juravle7a570e82017-01-14 16:23:30 -08001742 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001743 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001744 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001745
Victor Hsiehcb35a062020-08-13 16:11:13 -07001746 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001747 // We don't create an app image without reference profile since there is no speedup from
1748 // loading it in that case and instead will be a small overhead.
1749 generate_app_image = false;
1750 }
1751
1752 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001753 UniqueFile out_image = maybe_open_app_image(
1754 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001755
Victor Hsiehcb35a062020-08-13 16:11:13 -07001756 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001757 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001758 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1759 dex_metadata_path);
1760 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001761 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1762 }
1763 }
1764
Victor Hsieh8948a862020-08-07 11:30:55 -07001765 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1766 RUNTIME_NATIVE_BOOT_NAMESPACE,
1767 ENABLE_JITZYGOTE_IMAGE,
1768 /*default_value=*/ "");
1769 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1770
Victor Hsiehe98e6512020-08-10 15:39:22 -07001771 // Decide whether to use dex2oat64.
1772 bool use_dex2oat64 = false;
1773 // Check whether the device even supports 64-bit ABIs.
1774 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1775 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1776 }
1777 const char* dex2oat_bin = select_execution_binary(
1778 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1779 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1780 background_job_compile);
1781
Victor Hsiehc9821f12020-08-07 11:32:29 -07001782 auto execv_helper = std::make_unique<ExecVHelper>();
1783
Andreas Gampe023b2242018-02-28 16:03:25 -08001784 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001785
Victor Hsiehc9821f12020-08-07 11:32:29 -07001786 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001787 runner.Initialize(out_oat,
1788 out_vdex,
1789 out_image,
1790 in_dex,
1791 in_vdex,
1792 dex_metadata,
1793 reference_profile,
1794 class_loader_context,
1795 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001796 swap_fd.get(),
1797 instruction_set,
1798 compiler_filter,
1799 debuggable,
1800 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001801 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001802 target_sdk_version,
1803 enable_hidden_api_checks,
1804 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001805 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001806 compilation_reason);
1807
Jeff Sharkey90aff262016-12-12 14:28:24 -07001808 pid_t pid = fork();
1809 if (pid == 0) {
Wei Wange0dbd9b2020-12-11 17:24:19 +00001810 // Need to set schedpolicy before dropping privileges
1811 // for cgroup migration. See details at b/175178520.
1812 SetDex2OatScheduling(boot_complete);
1813
Jeff Sharkey90aff262016-12-12 14:28:24 -07001814 /* child -- drop privileges before continuing */
1815 drop_capabilities(uid);
1816
Victor Hsiehcb35a062020-08-13 16:11:13 -07001817 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001818 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1819 out_oat.path().c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001820 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001821 }
1822
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001823 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001824 } else {
1825 int res = wait_child(pid);
1826 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001827 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001828 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001829 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1830 << std::hex << std::setw(4) << res << ", process failed";
1831 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001832 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001833 }
1834 }
1835
Jeff Sharkey90aff262016-12-12 14:28:24 -07001836 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001837 out_oat.DisableCleanup();
1838 out_vdex.DisableCleanup();
1839 out_image.DisableCleanup();
1840 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001841
1842 return 0;
1843}
1844
Calin Juravlec9eab382017-01-25 01:17:17 -08001845// Try to remove the given directory. Log an error if the directory exists
1846// and is empty but could not be removed.
1847static bool rmdir_if_empty(const char* dir) {
1848 if (rmdir(dir) == 0) {
1849 return true;
1850 }
1851 if (errno == ENOENT || errno == ENOTEMPTY) {
1852 return true;
1853 }
1854 PLOG(ERROR) << "Failed to remove dir: " << dir;
1855 return false;
1856}
1857
1858// Try to unlink the given file. Log an error if the file exists and could not
1859// be unlinked.
1860static bool unlink_if_exists(const std::string& file) {
1861 if (unlink(file.c_str()) == 0) {
1862 return true;
1863 }
1864 if (errno == ENOENT) {
1865 return true;
1866
1867 }
1868 PLOG(ERROR) << "Could not unlink: " << file;
1869 return false;
1870}
1871
Calin Juravle7d765462017-09-04 15:57:10 -07001872enum ReconcileSecondaryDexResult {
1873 kReconcileSecondaryDexExists = 0,
1874 kReconcileSecondaryDexCleanedUp = 1,
1875 kReconcileSecondaryDexValidationError = 2,
1876 kReconcileSecondaryDexCleanUpError = 3,
1877 kReconcileSecondaryDexAccessIOError = 4,
1878};
Calin Juravlec9eab382017-01-25 01:17:17 -08001879
1880// Reconcile the secondary dex 'dex_path' and its generated oat files.
1881// Return true if all the parameters are valid and the secondary dex file was
1882// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1883// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1884// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1885// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1886// Return false if there were errors during processing. In this case
1887// out_secondary_dex_exists will be set to false.
1888bool reconcile_secondary_dex_file(const std::string& dex_path,
1889 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001890 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08001891 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001892 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001893 if (isas.size() == 0) {
1894 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1895 return false;
1896 }
1897
Calin Juravle7d765462017-09-04 15:57:10 -07001898 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1899 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1900 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001901 return false;
1902 }
1903
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001904 // As a security measure we want to unlink art artifacts with the reduced capabilities
1905 // of the package user id. So we fork and drop capabilities in the child.
1906 pid_t pid = fork();
1907 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001908 /* child -- drop privileges before continuing */
1909 drop_capabilities(uid);
1910
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001911 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07001912 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07001913 uid, storage_flag)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001914 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1915 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001916 _exit(kReconcileSecondaryDexValidationError);
1917 }
1918
1919 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1920 switch (access_check) {
1921 case kSecondaryDexAccessDoesNotExist:
1922 // File does not exist. Proceed with cleaning.
1923 break;
1924 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1925 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1926 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1927 default:
Martijn Coenen6de402a2021-04-26 16:23:40 +02001928 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1929 "Unexpected result from check_secondary_dex_access: %d", access_check);
Calin Juravle7d765462017-09-04 15:57:10 -07001930 _exit(kReconcileSecondaryDexValidationError);
1931 }
1932
1933 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001934 char oat_path[PKG_PATH_MAX];
1935 char oat_dir[PKG_PATH_MAX];
1936 char oat_isa_dir[PKG_PATH_MAX];
1937 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001938 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001939 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001940 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001941 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001942 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001943 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001944 }
Calin Juravle51314092017-05-18 15:33:05 -07001945
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001946 // Delete oat/vdex/art files.
1947 result = unlink_if_exists(oat_path) && result;
1948 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1949 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08001950
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001951 // Delete profiles.
1952 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001953 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001954 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001955 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001956 result = unlink_if_exists(current_profile) && result;
1957 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07001958
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001959 // We upgraded once the location of current profile for secondary dex files.
1960 // Check for any previous left-overs and remove them as well.
1961 std::string old_current_profile = dex_path + ".prof";
1962 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07001963
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001964 // Try removing the directories as well, they might be empty.
1965 result = rmdir_if_empty(oat_isa_dir) && result;
1966 result = rmdir_if_empty(oat_dir) && result;
1967 }
Calin Juravle7d765462017-09-04 15:57:10 -07001968 if (!result) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02001969 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1970 "Could not validate secondary dex path %s", dex_path.c_str());
Calin Juravle7d765462017-09-04 15:57:10 -07001971 }
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)) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002043 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2044 "Could not validate secondary dex path %s", dex_path.c_str());
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002045 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002046 }
2047
2048 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2049 if (fd == -1) {
2050 if (errno == EACCES || errno == ENOENT) {
2051 // Not treated as an error.
2052 _exit(0);
2053 }
2054 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Martijn Coenen6de402a2021-04-26 16:23:40 +02002055 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2056 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002057 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002058 }
2059
2060 SHA256_CTX ctx;
2061 SHA256_Init(&ctx);
2062
2063 std::vector<uint8_t> buffer(65536);
2064 while (true) {
2065 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2066 if (bytes_read == 0) {
2067 break;
2068 } else if (bytes_read == -1) {
Martijn Coenen6de402a2021-04-26 16:23:40 +02002069 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2070 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002071 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002072 }
2073
2074 SHA256_Update(&ctx, buffer.data(), bytes_read);
2075 }
2076
2077 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2078 SHA256_Final(hash.data(), &ctx);
2079 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002080 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002081 }
2082
2083 _exit(0);
2084 }
2085
2086 // parent
2087 pipe_write.reset();
2088
2089 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2090 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2091 out_secondary_dex_hash->clear();
2092 }
2093 return wait_child(pid) == 0;
2094}
2095
Jeff Sharkey90aff262016-12-12 14:28:24 -07002096// Helper for move_ab, so that we can have common failure-case cleanup.
2097static bool unlink_and_rename(const char* from, const char* to) {
2098 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2099 // return a failure.
2100 struct stat s;
2101 if (stat(to, &s) == 0) {
2102 if (!S_ISREG(s.st_mode)) {
2103 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2104 return false;
2105 }
2106 if (unlink(to) != 0) {
2107 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2108 return false;
2109 }
2110 } else {
2111 // This may be a permission problem. We could investigate the error code, but we'll just
2112 // let the rename failure do the work for us.
2113 }
2114
2115 // Try to rename "to" to "from."
2116 if (rename(from, to) != 0) {
2117 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2118 return false;
2119 }
2120 return true;
2121}
2122
2123// Move/rename a B artifact (from) to an A artifact (to).
2124static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2125 // Check whether B exists.
2126 {
2127 struct stat s;
2128 if (stat(b_path.c_str(), &s) != 0) {
Alex Light9f295662021-02-25 11:50:33 -08002129 // Ignore for now. The service calling this isn't smart enough to
2130 // understand lack of artifacts at the moment.
2131 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002132 return false;
2133 }
2134 if (!S_ISREG(s.st_mode)) {
2135 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2136 // Try to unlink, but swallow errors.
2137 unlink(b_path.c_str());
2138 return false;
2139 }
2140 }
2141
2142 // Rename B to A.
2143 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2144 // Delete the b_path so we don't try again (or fail earlier).
2145 if (unlink(b_path.c_str()) != 0) {
2146 PLOG(ERROR) << "Could not unlink " << b_path;
2147 }
2148
2149 return false;
2150 }
2151
2152 return true;
2153}
2154
2155bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2156 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002157 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2158 if (slot_suffix.empty()) {
2159 return false;
2160 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002161
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002162 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2163 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2164 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002165 }
2166
2167 // Validate other inputs.
2168 if (validate_apk_path(apk_path) != 0) {
2169 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2170 return false;
2171 }
2172 if (validate_apk_path(oat_dir) != 0) {
2173 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2174 return false;
2175 }
2176
2177 char a_path[PKG_PATH_MAX];
2178 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2179 return false;
2180 }
2181 const std::string a_vdex_path = create_vdex_filename(a_path);
2182 const std::string a_image_path = create_image_filename(a_path);
2183
2184 // B path = A path + slot suffix.
2185 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2186 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2187 const std::string b_image_path = StringPrintf("%s.%s",
2188 a_image_path.c_str(),
2189 slot_suffix.c_str());
2190
2191 bool success = true;
2192 if (move_ab_path(b_path, a_path)) {
2193 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2194 // Note: we can live without an app image. As such, ignore failure to move the image file.
2195 // If we decide to require the app image, or the app image being moved correctly,
2196 // then change accordingly.
2197 constexpr bool kIgnoreAppImageFailure = true;
2198
2199 if (!a_image_path.empty()) {
2200 if (!move_ab_path(b_image_path, a_image_path)) {
2201 unlink(a_image_path.c_str());
2202 if (!kIgnoreAppImageFailure) {
2203 success = false;
2204 }
2205 }
2206 }
2207 } else {
2208 // Cleanup: delete B image, ignore errors.
2209 unlink(b_image_path.c_str());
2210 success = false;
2211 }
2212 } else {
2213 // Cleanup: delete B image, ignore errors.
2214 unlink(b_vdex_path.c_str());
2215 unlink(b_image_path.c_str());
2216 success = false;
2217 }
2218 return success;
2219}
2220
2221bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2222 // Delete the oat/odex file.
2223 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002224 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002225 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002226 return false;
2227 }
2228
2229 // In case of a permission failure report the issue. Otherwise just print a warning.
2230 auto unlink_and_check = [](const char* path) -> bool {
2231 int result = unlink(path);
2232 if (result != 0) {
2233 if (errno == EACCES || errno == EPERM) {
2234 PLOG(ERROR) << "Could not unlink " << path;
2235 return false;
2236 }
2237 PLOG(WARNING) << "Could not unlink " << path;
2238 }
2239 return true;
2240 };
2241
2242 // Delete the oat/odex file.
2243 bool return_value_oat = unlink_and_check(out_path);
2244
2245 // Derive and delete the app image.
2246 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2247
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002248 // Derive and delete the vdex file.
2249 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2250
Jeff Sharkey90aff262016-12-12 14:28:24 -07002251 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002252 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002253}
2254
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002255static bool is_absolute_path(const std::string& path) {
2256 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2257 LOG(ERROR) << "Invalid absolute path " << path;
2258 return false;
2259 } else {
2260 return true;
2261 }
2262}
2263
2264static bool is_valid_instruction_set(const std::string& instruction_set) {
2265 // TODO: add explicit whitelisting of instruction sets
2266 if (instruction_set.find('/') != std::string::npos) {
2267 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2268 return false;
2269 } else {
2270 return true;
2271 }
2272}
2273
2274bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2275 const char *apk_path, const char *instruction_set) {
2276 std::string oat_dir_ = oat_dir;
2277 std::string apk_path_ = apk_path;
2278 std::string instruction_set_ = instruction_set;
2279
2280 if (!is_absolute_path(oat_dir_)) return false;
2281 if (!is_absolute_path(apk_path_)) return false;
2282 if (!is_valid_instruction_set(instruction_set_)) return false;
2283
2284 std::string::size_type end = apk_path_.rfind('.');
2285 std::string::size_type start = apk_path_.rfind('/', end);
2286 if (end == std::string::npos || start == std::string::npos) {
2287 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2288 return false;
2289 }
2290
2291 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2292 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2293 const char* res = res_.c_str();
2294 if (strlen(res) >= PKG_PATH_MAX) {
2295 LOG(ERROR) << "Result too large";
2296 return false;
2297 } else {
2298 strlcpy(path, res, PKG_PATH_MAX);
2299 return true;
2300 }
2301}
2302
2303bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2304 const char *instruction_set) {
2305 std::string apk_path_ = apk_path;
2306 std::string instruction_set_ = instruction_set;
2307
2308 if (!is_absolute_path(apk_path_)) return false;
2309 if (!is_valid_instruction_set(instruction_set_)) return false;
2310
2311 std::string::size_type end = apk_path_.rfind('.');
2312 std::string::size_type start = apk_path_.rfind('/', end);
2313 if (end == std::string::npos || start == std::string::npos) {
2314 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2315 return false;
2316 }
2317
2318 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2319 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2320}
2321
2322bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2323 const char *instruction_set) {
2324 std::string src_ = src;
2325 std::string instruction_set_ = instruction_set;
2326
2327 if (!is_absolute_path(src_)) return false;
2328 if (!is_valid_instruction_set(instruction_set_)) return false;
2329
2330 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2331 if (*it == '/') {
2332 *it = '@';
2333 }
2334 }
2335
2336 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2337 + DALVIK_CACHE_POSTFIX;
2338 const char* res = res_.c_str();
2339 if (strlen(res) >= PKG_PATH_MAX) {
2340 LOG(ERROR) << "Result too large";
2341 return false;
2342 } else {
2343 strlcpy(path, res, PKG_PATH_MAX);
2344 return true;
2345 }
2346}
2347
Calin Juravle59f7ab82018-04-27 17:50:23 -07002348bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2349 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002350 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2351 for (const std::string& elem : classpaths_elems) {
2352 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2353 if (fd < 0) {
2354 PLOG(ERROR) << "Could not open classpath elem " << elem;
2355 return false;
2356 } else {
2357 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002358 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002359 }
2360 }
2361 return true;
2362}
2363
2364static bool create_app_profile_snapshot(int32_t app_id,
2365 const std::string& package_name,
2366 const std::string& profile_name,
2367 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002368 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2369
Calin Juravle824a64d2018-01-18 20:23:17 -08002370 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002371 if (snapshot_fd < 0) {
2372 return false;
2373 }
2374
2375 std::vector<unique_fd> profiles_fd;
2376 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002377 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2378 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002379 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2380 return false;
2381 }
2382
2383 profiles_fd.push_back(std::move(reference_profile_fd));
2384
Calin Juravle0d0a4922018-01-23 19:54:11 -08002385 // Open the class paths elements. These will be used to filter out profile data that does
2386 // not belong to the classpath during merge.
2387 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002388 std::vector<std::string> dex_locations;
2389 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002390 return false;
2391 }
2392
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002393 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002394 // This is specifically a snapshot for an app, so don't use boot image profiles.
2395 args.SetupMerge(profiles_fd,
2396 snapshot_fd,
2397 apk_fds,
2398 dex_locations,
2399 /* for_snapshot= */ true,
2400 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002401 pid_t pid = fork();
2402 if (pid == 0) {
2403 /* child -- drop privileges before continuing */
2404 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002405 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002406 }
2407
2408 /* parent */
2409 int return_code = wait_child(pid);
2410 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002411 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002412 return false;
2413 }
2414
Calin Juravle78728f32019-11-08 17:55:46 -08002415 // Verify that profman finished successfully.
2416 int profman_code = WEXITSTATUS(return_code);
2417 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2418 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2419 << ":" << profman_code;
2420 return false;
2421 }
Calin Juravle29591732017-11-20 17:46:19 -08002422 return true;
2423}
2424
Calin Juravle0d0a4922018-01-23 19:54:11 -08002425static bool create_boot_image_profile_snapshot(const std::string& package_name,
2426 const std::string& profile_name,
2427 const std::string& classpath) {
2428 // The reference profile directory for the android package might not be prepared. Do it now.
2429 const std::string ref_profile_dir =
2430 create_primary_reference_profile_package_dir_path(package_name);
2431 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2432 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2433 return false;
2434 }
2435
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002436 // Return false for empty class path since it may otherwise return true below if profiles is
2437 // empty.
2438 if (classpath.empty()) {
2439 PLOG(ERROR) << "Class path is empty";
2440 return false;
2441 }
2442
Calin Juravle0d0a4922018-01-23 19:54:11 -08002443 // Open and create the snapshot profile.
2444 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2445
2446 // Collect all non empty profiles.
2447 // The collection will traverse all applications profiles and find the non empty files.
2448 // This has the potential of inspecting a large number of files and directories (depending
2449 // on the number of applications and users). So there is a slight increase in the chance
2450 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2451 // fail the snapshot and aggregate whatever profile we could open.
2452 //
2453 // The profile snapshot is a best effort based on available data it's ok if some data
2454 // from some apps is missing. It will be counter productive for the snapshot to fail
2455 // because we could not open or read some of the files.
2456 std::vector<std::string> profiles;
2457 if (!collect_profiles(&profiles)) {
2458 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2459 }
2460
2461 // If we have no profiles return early.
2462 if (profiles.empty()) {
2463 return true;
2464 }
2465
2466 // Open the classpath elements. These will be used to filter out profile data that does
2467 // not belong to the classpath during merge.
2468 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002469 std::vector<std::string> dex_locations;
2470 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002471 return false;
2472 }
2473
2474 // If we could not open any files from the classpath return an error.
2475 if (apk_fds.empty()) {
2476 LOG(ERROR) << "Could not open any of the classpath elements.";
2477 return false;
2478 }
2479
2480 // Aggregate the profiles in batches of kAggregationBatchSize.
2481 // We do this to avoid opening a huge a amount of files.
2482 static constexpr size_t kAggregationBatchSize = 10;
2483
Calin Juravle0d0a4922018-01-23 19:54:11 -08002484 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002485 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002486 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2487 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2488 if (fd.get() >= 0) {
2489 profiles_fd.push_back(std::move(fd));
2490 }
2491 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002492
2493 // We aggregate (read & write) into the same fd multiple times in a row.
2494 // We need to reset the cursor every time to ensure we read the whole file every time.
2495 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2496 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2497 return false;
2498 }
2499
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002500 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002501 args.SetupMerge(profiles_fd,
2502 snapshot_fd,
2503 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002504 dex_locations,
2505 /*for_snapshot=*/true,
2506 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002507 pid_t pid = fork();
2508 if (pid == 0) {
2509 /* child -- drop privileges before continuing */
2510 drop_capabilities(AID_SYSTEM);
2511
Calin Juravle59f7ab82018-04-27 17:50:23 -07002512 // The introduction of new access flags into boot jars causes them to
2513 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002514 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002515 }
2516
2517 /* parent */
2518 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002519
Calin Juravle0d0a4922018-01-23 19:54:11 -08002520 if (!WIFEXITED(return_code)) {
2521 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2522 return false;
2523 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002524
2525 // Verify that profman finished successfully.
2526 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002527 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2528 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2529 << ":" << profman_code;
2530 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002531 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002532 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002533
Calin Juravle0d0a4922018-01-23 19:54:11 -08002534 return true;
2535}
2536
2537bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2538 const std::string& profile_name, const std::string& classpath) {
2539 if (app_id == -1) {
2540 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2541 } else {
2542 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2543 }
2544}
2545
Calin Juravlec3b049e2018-01-18 22:32:58 -08002546bool prepare_app_profile(const std::string& package_name,
2547 userid_t user_id,
2548 appid_t app_id,
2549 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002550 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002551 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002552 // Prepare the current profile.
2553 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2554 /*is_secondary_dex*/ false);
2555 uid_t uid = multiuser_get_uid(user_id, app_id);
2556 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2557 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2558 return false;
2559 }
2560
2561 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002562 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002563 return true;
2564 }
2565
2566 // We have a dex metdata. Merge the profile into the reference profile.
2567 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2568 /*read_write*/ true, /*is_secondary_dex*/ false);
2569 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2570 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002571 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2572 if (apk_fd < 0) {
2573 PLOG(ERROR) << "Could not open code path " << code_path;
2574 return false;
2575 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002576
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002577 RunProfman args;
2578 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2579 std::move(ref_profile_fd),
2580 std::move(apk_fd),
2581 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002582 pid_t pid = fork();
2583 if (pid == 0) {
2584 /* child -- drop privileges before continuing */
2585 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2586 drop_capabilities(app_shared_gid);
2587
Calin Juravlef63d4792018-01-30 17:43:34 +00002588 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002589 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002590 }
2591
2592 /* parent */
2593 int return_code = wait_child(pid);
2594 if (!WIFEXITED(return_code)) {
2595 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2596 return false;
2597 }
2598 return true;
2599}
2600
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002601} // namespace installd
2602} // namespace android