blob: 45e43d0e9d58926afea902d7d784f4c5f19e6a20 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.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
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800454 // Do not add after dex2oat_flags, they should override others for debugging.
455 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800456 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700457
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800458 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
459 const unique_fd& reference_profile_fd,
460 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800461 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
462 bool for_snapshot = false,
463 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800464 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800465 reference_profile_fd,
466 apk_fds,
467 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800468 /*copy_and_update=*/ false,
469 for_snapshot,
470 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800471 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700472
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800473 void SetupCopyAndUpdate(unique_fd&& profile_fd,
474 unique_fd&& reference_profile_fd,
475 unique_fd&& apk_fd,
476 const std::string& dex_location) {
477 // The fds need to stay open longer than the scope of the function, so put them into a local
478 // variable vector.
479 profiles_fd_.push_back(std::move(profile_fd));
480 apk_fds_.push_back(std::move(apk_fd));
481 reference_profile_fd_ = std::move(reference_profile_fd);
482 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800483 SetupArgs(profiles_fd_,
484 reference_profile_fd_,
485 apk_fds_,
486 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800487 /*copy_and_update=*/true,
488 /*for_snapshot*/false,
489 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800490 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000491
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800492 void SetupDump(const std::vector<unique_fd>& profiles_fd,
493 const unique_fd& reference_profile_fd,
494 const std::vector<std::string>& dex_locations,
495 const std::vector<unique_fd>& apk_fds,
496 const unique_fd& output_fd) {
497 AddArg("--dump-only");
498 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800499 SetupArgs(profiles_fd,
500 reference_profile_fd,
501 apk_fds,
502 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800503 /*copy_and_update=*/false,
504 /*for_snapshot*/false,
505 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800506 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000507
Victor Hsiehc9821f12020-08-07 11:32:29 -0700508 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800509 void Exec() {
510 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
511 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000512
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800513 private:
514 unique_fd reference_profile_fd_;
515 std::vector<unique_fd> profiles_fd_;
516 std::vector<unique_fd> apk_fds_;
517};
Mathieu Chartier31636522018-11-09 23:53:07 +0000518
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800519
Calin Juravlef63d4792018-01-30 17:43:34 +0000520
Jeff Sharkey90aff262016-12-12 14:28:24 -0700521// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800522// The location is the package name for primary apks or the dex path for secondary dex files.
523// Returns true if there is enough information in the current profiles that makes it
524// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525// If the return value is true all the current profiles would have been merged into
526// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800527static bool analyze_profiles(uid_t uid, const std::string& package_name,
528 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800529 std::vector<unique_fd> profiles_fd;
530 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800531 open_profile_files(uid, package_name, location, is_secondary_dex,
532 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800533 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700534 // Skip profile guided compilation because no profiles were found.
535 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700536 return false;
537 }
538
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800539 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700540 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
541 const std::vector<std::string>& dex_locations = std::vector<std::string>();
542 profman_merge.SetupMerge(
543 profiles_fd,
544 reference_profile_fd,
545 apk_fds,
546 dex_locations,
547 /* for_snapshot= */ false,
548 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700549 pid_t pid = fork();
550 if (pid == 0) {
551 /* child -- drop privileges before continuing */
552 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800553 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700554 }
555 /* parent */
556 int return_code = wait_child(pid);
557 bool need_to_compile = false;
558 bool should_clear_current_profiles = false;
559 bool should_clear_reference_profile = false;
560 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800561 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700562 } else {
563 return_code = WEXITSTATUS(return_code);
564 switch (return_code) {
565 case PROFMAN_BIN_RETURN_CODE_COMPILE:
566 need_to_compile = true;
567 should_clear_current_profiles = true;
568 should_clear_reference_profile = false;
569 break;
570 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
571 need_to_compile = false;
572 should_clear_current_profiles = false;
573 should_clear_reference_profile = false;
574 break;
575 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800576 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700577 need_to_compile = false;
578 should_clear_current_profiles = true;
579 should_clear_reference_profile = true;
580 break;
581 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
582 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
583 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800584 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700585 need_to_compile = false;
586 should_clear_current_profiles = false;
587 should_clear_reference_profile = false;
588 break;
Calin Juravle76561322019-11-14 09:08:52 -0800589 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
590 need_to_compile = false;
591 should_clear_current_profiles = true;
592 should_clear_reference_profile = true;
593 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700594 default:
595 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800596 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800597 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598 need_to_compile = false;
599 should_clear_current_profiles = true;
600 should_clear_reference_profile = true;
601 break;
602 }
603 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800604
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800606 if (is_secondary_dex) {
607 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800608 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
609 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800610 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800611 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800612 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700613 }
614 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800615 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700616 }
617 return need_to_compile;
618}
619
Calin Juravle114f0812017-03-08 19:05:07 -0800620// Decides if profile guided compilation is needed or not based on existing profiles.
621// The analysis is done for the primary apks of the given package.
622// Returns true if there is enough information in the current profiles that makes it
623// worth to recompile the package.
624// If the return value is true all the current profiles would have been merged into
625// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800626bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
627 const std::string& profile_name) {
628 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800629}
630
Calin Juravle408cd4a2018-01-20 23:34:18 -0800631bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
632 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800633 std::vector<unique_fd> profile_fds;
634 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800635 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
636 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700637
Calin Juravle408cd4a2018-01-20 23:34:18 -0800638 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800639 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700640
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800641 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700642 const bool has_profiles = !profile_fds.empty();
643
644 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800645 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646 return false;
647 }
648
Calin Juravle114f0812017-03-08 19:05:07 -0800649 unique_fd output_fd(open(out_file_name.c_str(),
650 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700651 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800652 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 return false;
654 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800655
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800657 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800658 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
659 if (apk_fd == -1) {
660 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
661 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700662 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700663 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800664 apk_fds.push_back(std::move(apk_fd));
665
Jeff Sharkey90aff262016-12-12 14:28:24 -0700666
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800667 RunProfman profman_dump;
668 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700669 pid_t pid = fork();
670 if (pid == 0) {
671 /* child -- drop privileges before continuing */
672 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800673 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700674 }
675 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700676 int return_code = wait_child(pid);
677 if (!WIFEXITED(return_code)) {
678 LOG(WARNING) << "profman failed for package " << pkgname << ": "
679 << return_code;
680 return false;
681 }
682 return true;
683}
684
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700685bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800686 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700687 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
688 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800689 package_name,
690 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700691 /*read_write*/ true,
692 /*secondary*/ false));
693 if (in_fd.get() < 0) {
694 PLOG(WARNING) << "Could not open profile " << system_profile;
695 return false;
696 }
697 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800698 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700699 return false;
700 }
701
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700702 // As a security measure we want to write the profile information with the reduced capabilities
703 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700704 pid_t pid = fork();
705 if (pid == 0) {
706 /* child -- drop privileges before continuing */
707 drop_capabilities(packageUid);
708
709 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
710 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800711 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700712 }
713 // This implies that the app owning this profile is running
714 // (and has acquired the lock).
715 //
716 // The app never acquires the lock for the reference profiles of primary apks.
717 // Only dex2oat from installd will do that. Since installd is single threaded
718 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800719 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700720 return false;
721 }
722
723 bool truncated = ftruncate(out_fd.get(), 0) == 0;
724 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800725 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700726 }
727
728 // Copy over data.
729 static constexpr size_t kBufferSize = 4 * 1024;
730 char buffer[kBufferSize];
731 while (true) {
732 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
733 if (bytes == 0) {
734 break;
735 }
736 write(out_fd.get(), buffer, bytes);
737 }
738 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800739 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700740 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700741 // Use _exit since we don't want to run the global destructors in the child.
742 // b/62597429
743 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700744 }
745 /* parent */
746 int return_code = wait_child(pid);
747 return return_code == 0;
748}
749
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
751 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
752 if (EndsWith(oat_path, ".dex")) {
753 std::string new_path = oat_path;
754 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800755 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 return new_path;
757 }
758
759 // An odex entry. Not that this may not be an extension, e.g., in the OTA
760 // case (where the base name will have an extension for the B artifact).
761 size_t odex_pos = oat_path.rfind(".odex");
762 if (odex_pos != std::string::npos) {
763 std::string new_path = oat_path;
764 new_path.replace(odex_pos, strlen(".odex"), new_ext);
765 CHECK_NE(new_path.find(new_ext), std::string::npos);
766 return new_path;
767 }
768
769 // Don't know how to handle this.
770 return "";
771}
772
773// Translate the given oat path to an art (app image) path. An empty string
774// denotes an error.
775static std::string create_image_filename(const std::string& oat_path) {
776 return replace_file_extension(oat_path, ".art");
777}
778
779// Translate the given oat path to a vdex path. An empty string denotes an error.
780static std::string create_vdex_filename(const std::string& oat_path) {
781 return replace_file_extension(oat_path, ".vdex");
782}
783
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784static int open_output_file(const char* file_name, bool recreate, int permissions) {
785 int flags = O_RDWR | O_CREAT;
786 if (recreate) {
787 if (unlink(file_name) < 0) {
788 if (errno != ENOENT) {
789 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
790 }
791 }
792 flags |= O_EXCL;
793 }
794 return open(file_name, flags, permissions);
795}
796
Calin Juravle2289c0a2017-02-15 12:44:14 -0800797static bool set_permissions_and_ownership(
798 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
799 // Primary apks are owned by the system. Secondary dex files are owned by the app.
800 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700801 if (fchmod(fd,
802 S_IRUSR|S_IWUSR|S_IRGRP |
803 (is_public ? S_IROTH : 0)) < 0) {
804 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
805 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800806 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807 ALOGE("installd cannot chown '%s' during dexopt\n", path);
808 return false;
809 }
810 return true;
811}
812
813static bool IsOutputDalvikCache(const char* oat_dir) {
814 // InstallerConnection.java (which invokes installd) transforms Java null arguments
815 // into '!'. Play it safe by handling it both.
816 // TODO: ensure we never get null.
817 // TODO: pass a flag instead of inferring if the output is dalvik cache.
818 return oat_dir == nullptr || oat_dir[0] == '!';
819}
820
Calin Juravled23dee72017-07-06 16:29:11 -0700821// Best-effort check whether we can fit the the path into our buffers.
822// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
823// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
824// extension to the cache path (5 bytes).
825// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
826static bool validate_dex_path_size(const std::string& dex_path) {
827 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
828 LOG(ERROR) << "dex_path too long: " << dex_path;
829 return false;
830 }
831 return true;
832}
833
Jeff Sharkey90aff262016-12-12 14:28:24 -0700834static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800835 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700836 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700837 return false;
838 }
839
840 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800841 // Oat dirs for secondary dex files are already validated.
842 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700843 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
844 return false;
845 }
846 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
847 return false;
848 }
849 } else {
850 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
851 return false;
852 }
853 }
854 return true;
855}
856
Calin Juravle7a570e82017-01-14 16:23:30 -0800857// (re)Creates the app image if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700858UniqueFile maybe_open_app_image(const std::string& out_oat_path,
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700859 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100860
Calin Juravle7a570e82017-01-14 16:23:30 -0800861 const std::string image_path = create_image_filename(out_oat_path);
862 if (image_path.empty()) {
863 // Happens when the out_oat_path has an unknown extension.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700864 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800865 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100866
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700867 // In case there is a stale image, remove it now. Ignore any error.
868 unlink(image_path.c_str());
869
870 // Not enabled, exit.
871 if (!generate_app_image) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700872 return UniqueFile();
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100873 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700874 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
875 if (app_image_format.empty()) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700876 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -0800877 }
878 // Recreate is true since we do not want to modify a mapped image. If the app is
879 // already running and we modify the image file, it can cause crashes (b/27493510).
Victor Hsiehcb35a062020-08-13 16:11:13 -0700880 UniqueFile image_file(
Calin Juravle7a570e82017-01-14 16:23:30 -0800881 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
Victor Hsiehcb35a062020-08-13 16:11:13 -0700882 image_path,
883 UnlinkIgnoreResult);
884 if (image_file.fd() < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800885 // Could not create application image file. Go on since we can compile without it.
886 LOG(ERROR) << "installd could not create '" << image_path
887 << "' for image file during dexopt";
888 // If we have a valid image file path but no image fd, explicitly erase the image file.
889 if (unlink(image_path.c_str()) < 0) {
890 if (errno != ENOENT) {
891 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
892 }
893 }
894 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -0700895 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800896 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
Victor Hsiehcb35a062020-08-13 16:11:13 -0700897 image_file.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -0800898 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700899
Victor Hsiehcb35a062020-08-13 16:11:13 -0700900 return image_file;
Calin Juravle7a570e82017-01-14 16:23:30 -0800901}
902
903// Creates the dexopt swap file if necessary and return its fd.
904// Returns -1 if there's no need for a swap or in case of errors.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700905unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800906 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800907 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -0800908 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700909 auto swap_file_name = out_oat_path + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800910 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600911 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -0800912 if (swap_fd.get() < 0) {
913 // Could not create swap file. Optimistically go on and hope that we can compile
914 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600915 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -0800916 } else {
917 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600918 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800919 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
920 }
921 }
922 return swap_fd;
923}
924
925// Opens the reference profiles if needed.
926// 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 -0700927UniqueFile maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000928 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -0800929 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +0000930 // If we are not profile guided compilation, or we are compiling system server
931 // do not bother to open the profiles; we won't be using them.
932 if (!profile_guided || (pkgname[0] == '*')) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700933 return UniqueFile();
Calin Juravle5bd1c722018-02-01 17:23:54 +0000934 }
935
936 // If this is a secondary dex path which is public do not open the profile.
937 // We cannot compile public secondary dex paths with profiles. That's because
938 // it will expose how the dex files are used by their owner.
939 //
940 // Note that the PackageManager is responsible to set the is_public flag for
941 // primary apks and we do not check it here. In some cases, e.g. when
942 // compiling with a public profile from the .dm file the PackageManager will
943 // set is_public toghether with the profile guided compilation.
944 if (is_secondary_dex && is_public) {
Victor Hsiehcb35a062020-08-13 16:11:13 -0700945 return UniqueFile();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700946 }
Calin Juravle114f0812017-03-08 19:05:07 -0800947
948 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000949 std::string location;
950 if (is_secondary_dex) {
951 location = dex_path;
952 } else {
953 if (profile_name == nullptr) {
954 // This path is taken for system server re-compilation lunched from ZygoteInit.
Victor Hsiehcb35a062020-08-13 16:11:13 -0700955 return UniqueFile();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000956 } else {
957 location = profile_name;
958 }
959 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700960 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
961 is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -0800962}
Jeff Sharkey90aff262016-12-12 14:28:24 -0700963
Victor Hsiehcb35a062020-08-13 16:11:13 -0700964// Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
965// out_vdex_wrapper. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -0700966bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +0000967 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Victor Hsiehcb35a062020-08-13 16:11:13 -0700968 bool profile_guided, UniqueFile* in_vdex_wrapper,
969 UniqueFile* out_vdex_wrapper) {
970 CHECK(in_vdex_wrapper != nullptr);
971 CHECK(out_vdex_wrapper != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972 // Open the existing VDEX. We do this before creating the new output VDEX, which will
973 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +0000974 char in_odex_path[PKG_PATH_MAX];
975 int dexopt_action = abs(dexopt_needed);
976 bool is_odex_location = dexopt_needed < 0;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +0000977
978 // Infer the name of the output VDEX.
979 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
980 if (out_vdex_path_str.empty()) {
981 return false;
982 }
983
984 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +0000985 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700986 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
987 const char* path = nullptr;
988 if (is_odex_location) {
989 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
990 path = in_odex_path;
991 } else {
992 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -0800993 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700994 }
995 } else {
996 path = out_oat_path;
997 }
Victor Hsiehcb35a062020-08-13 16:11:13 -0700998 std::string in_vdex_path_str = create_vdex_filename(path);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700999 if (in_vdex_path_str.empty()) {
1000 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001001 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001003 // We can update in place when all these conditions are met:
1004 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1005 // on /system typically cannot be updated in place).
1006 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1007 // cannot be currently used by a running process.
1008 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1009 // different vdex files to operate.
1010 update_vdex_in_place =
1011 (in_vdex_path_str == out_vdex_path_str) &&
1012 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1013 !profile_guided;
1014 if (update_vdex_in_place) {
1015 // Open the file read-write to be able to update it.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001016 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1017 in_vdex_path_str);
1018 if (in_vdex_wrapper->fd() == -1) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001019 // If we failed to open the file, we cannot update it in place.
1020 update_vdex_in_place = false;
1021 }
1022 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001023 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1024 in_vdex_path_str);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001025 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001026 }
1027
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001028 // If we are updating the vdex in place, we do not need to recreate a vdex,
1029 // and can use the same existing one.
1030 if (update_vdex_in_place) {
1031 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1032 // have bogus stale vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001033 out_vdex_wrapper->reset(
1034 in_vdex_wrapper->fd(),
1035 out_vdex_path_str,
1036 UnlinkIgnoreResult);
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001037 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1038 // wrapper).
Victor Hsiehcb35a062020-08-13 16:11:13 -07001039 in_vdex_wrapper->DisableAutoClose();
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001040 } else {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001041 out_vdex_wrapper->reset(
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001042 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001043 out_vdex_path_str,
1044 UnlinkIgnoreResult);
1045 if (out_vdex_wrapper->fd() < 0) {
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001046 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1047 return false;
1048 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001049 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001050 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001051 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001052 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1053 return false;
1054 }
1055
1056 // If we got here we successfully opened the vdex files.
1057 return true;
1058}
1059
1060// Opens the output oat file for the given apk.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001061UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1062 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1063 char out_oat_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001064 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001065 return UniqueFile();
Calin Juravle7a570e82017-01-14 16:23:30 -08001066 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001067 UniqueFile oat(
Calin Juravle7a570e82017-01-14 16:23:30 -08001068 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
Victor Hsiehcb35a062020-08-13 16:11:13 -07001069 out_oat_path,
1070 UnlinkIgnoreResult);
1071 if (oat.fd() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001072 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001073 } else if (!set_permissions_and_ownership(
Victor Hsiehcb35a062020-08-13 16:11:13 -07001074 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001075 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001076 oat.reset();
Calin Juravle7a570e82017-01-14 16:23:30 -08001077 }
Victor Hsiehcb35a062020-08-13 16:11:13 -07001078 return oat;
Calin Juravle7a570e82017-01-14 16:23:30 -08001079}
1080
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001081// Creates RDONLY fds for oat and vdex files, if exist.
1082// Returns false if it fails to create oat out path for the given apk path.
1083// Note that the method returns true even if the files could not be opened.
1084bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1085 const std::string& oat_dir,
1086 const std::string& instruction_set,
1087 bool is_secondary_dex,
1088 unique_fd* oat_file_fd,
1089 unique_fd* vdex_file_fd) {
1090 char oat_path[PKG_PATH_MAX];
1091 if (!create_oat_out_path(apk_path.c_str(),
1092 instruction_set.c_str(),
1093 oat_dir.c_str(),
1094 is_secondary_dex,
1095 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001096 LOG(ERROR) << "Could not create oat out path for "
1097 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001098 return false;
1099 }
1100 oat_file_fd->reset(open(oat_path, O_RDONLY));
1101 if (oat_file_fd->get() < 0) {
1102 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1103 }
1104
1105 std::string vdex_filename = create_vdex_filename(oat_path);
1106 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1107 if (vdex_file_fd->get() < 0) {
1108 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1109 }
1110
1111 return true;
1112}
1113
Calin Juravle7a570e82017-01-14 16:23:30 -08001114// Updates the access times of out_oat_path based on those from apk_path.
1115void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1116 struct stat input_stat;
1117 memset(&input_stat, 0, sizeof(input_stat));
1118 if (stat(apk_path, &input_stat) != 0) {
1119 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1120 return;
1121 }
1122
1123 struct utimbuf ut;
1124 ut.actime = input_stat.st_atime;
1125 ut.modtime = input_stat.st_mtime;
1126 if (utime(out_oat_path, &ut) != 0) {
1127 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1128 }
1129}
1130
Calin Juravle80a21252017-01-17 14:43:25 -08001131// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001132// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1133// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1134// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001135class RunDexoptAnalyzer : public ExecVHelper {
1136 public:
1137 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001138 int vdex_fd,
1139 int oat_fd,
1140 int zip_fd,
1141 const std::string& instruction_set,
1142 const std::string& compiler_filter,
1143 bool profile_was_updated,
1144 bool downgrade,
1145 const char* class_loader_context,
1146 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001147 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001148
1149 // We always run the analyzer in the background job.
1150 const char* dexoptanalyzer_bin = select_execution_binary(
1151 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001152
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001153 std::string dex_file_arg = "--dex-file=" + dex_file;
1154 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1155 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1156 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1157 std::string isa_arg = "--isa=" + instruction_set;
1158 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1159 const char* assume_profile_changed = "--assume-profile-changed";
1160 const char* downgrade_flag = "--downgrade";
1161 std::string class_loader_context_arg = "--class-loader-context=";
1162 if (class_loader_context != nullptr) {
1163 class_loader_context_arg += class_loader_context;
1164 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001165 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1166 if (!class_loader_context_fds.empty()) {
1167 class_loader_context_fds_arg += class_loader_context_fds;
1168 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001169
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001170 // program name, dex file, isa, filter
1171 AddArg(dex_file_arg);
1172 AddArg(isa_arg);
1173 AddArg(compiler_filter_arg);
1174 if (oat_fd >= 0) {
1175 AddArg(oat_fd_arg);
1176 }
1177 if (vdex_fd >= 0) {
1178 AddArg(vdex_fd_arg);
1179 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001180 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001181 if (profile_was_updated) {
1182 AddArg(assume_profile_changed);
1183 }
1184 if (downgrade) {
1185 AddArg(downgrade_flag);
1186 }
1187 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001188 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001189 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001190 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001191 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001192 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001193
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001194 PrepareArgs(dexoptanalyzer_bin);
1195 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001196
1197 // Dexoptanalyzer mode which flattens the given class loader context and
1198 // prints a list of its dex files in that flattened order.
1199 RunDexoptAnalyzer(const char* class_loader_context) {
1200 CHECK(class_loader_context != nullptr);
1201
1202 // We always run the analyzer in the background job.
1203 const char* dexoptanalyzer_bin = select_execution_binary(
1204 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1205
1206 AddArg("--flatten-class-loader-context");
1207 AddArg(std::string("--class-loader-context=") + class_loader_context);
1208 PrepareArgs(dexoptanalyzer_bin);
1209 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001210};
Calin Juravle80a21252017-01-17 14:43:25 -08001211
1212// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001213static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001214 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001215 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001216 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001217 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001218 return false;
1219 }
Calin Juravle114f0812017-03-08 19:05:07 -08001220 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001221
Calin Juravle80a21252017-01-17 14:43:25 -08001222 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001223 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1224 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001225 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001226 return false;
1227 }
1228
1229 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001230 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001231
Calin Juravle7d765462017-09-04 15:57:10 -07001232 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001233 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001234 return false;
1235 }
1236
1237 return true;
1238}
1239
Calin Juravle7d765462017-09-04 15:57:10 -07001240// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1241// secondary dex files. This return codes are returned by the child process created for
1242// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001243
Andreas Gampe194fe422018-02-28 20:16:19 -08001244enum DexoptAnalyzerSkipCodes {
1245 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001246 // Specific errors are encoded in the name.
1247 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1248 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1249 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1250 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1251 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001252 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001253 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001254};
Calin Juravle7d765462017-09-04 15:57:10 -07001255
1256// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001257// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1258// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001259// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1260// of dexoptanalyzer.
1261static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001262 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001263 // The result values are defined in dexoptanalyzer.
1264 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001265 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001266 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001267 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001268 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001269 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001270 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001271 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001272 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001273 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1274 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001275 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1276 " Expected odex file status for secondary dex %s"
1277 " : dexoptanalyzer result=%d",
1278 dex_path.c_str(),
1279 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001280 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001281 }
1282
1283 // Use a second switch for enum switch-case analysis.
1284 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001285 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001286 // If the file does not exist there's no need for dexopt.
1287 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1288 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001289
1290 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1291 *error_msg = "Dexoptanalyzer path validation failed";
1292 return false;
1293 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1294 *error_msg = "Dexoptanalyzer open zip failed";
1295 return false;
1296 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1297 *error_msg = "Dexoptanalyzer dir preparation failed";
1298 return false;
1299 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1300 *error_msg = "Dexoptanalyzer open output failed";
1301 return false;
1302 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1303 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001304 return false;
1305 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001306
1307 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1308 dex_path.c_str(),
1309 result);
1310 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001311}
1312
Calin Juravle7d765462017-09-04 15:57:10 -07001313enum SecondaryDexAccess {
1314 kSecondaryDexAccessReadOk = 0,
1315 kSecondaryDexAccessDoesNotExist = 1,
1316 kSecondaryDexAccessPermissionError = 2,
1317 kSecondaryDexAccessIOError = 3
1318};
1319
1320static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1321 // Check if the path exists and can be read. If not, there's nothing to do.
1322 if (access(dex_path.c_str(), R_OK) == 0) {
1323 return kSecondaryDexAccessReadOk;
1324 } else {
1325 if (errno == ENOENT) {
1326 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1327 return kSecondaryDexAccessDoesNotExist;
1328 } else {
1329 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1330 return errno == EACCES
1331 ? kSecondaryDexAccessPermissionError
1332 : kSecondaryDexAccessIOError;
1333 }
1334 }
1335}
1336
1337static bool is_file_public(const std::string& filename) {
1338 struct stat file_stat;
1339 if (stat(filename.c_str(), &file_stat) == 0) {
1340 return (file_stat.st_mode & S_IROTH) != 0;
1341 }
1342 return false;
1343}
1344
1345// Create the oat file structure for the secondary dex 'dex_path' and assign
1346// the individual path component to the 'out_' parameters.
1347static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001348 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001349 size_t dirIndex = dex_path.rfind('/');
1350 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001351 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001352 return false;
1353 }
1354 // TODO(calin): we have similar computations in at lest 3 other places
1355 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1356 // using string append.
1357 std::string apk_dir = dex_path.substr(0, dirIndex);
1358 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1359 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1360
1361 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1362 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001363 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001364 return false;
1365 }
1366 return true;
1367}
1368
1369// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1370// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001371static bool validate_dexopt_storage_flags(int dexopt_flags,
1372 int* out_storage_flag,
1373 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001374 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1375 *out_storage_flag = FLAG_STORAGE_CE;
1376 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001377 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001378 return false;
1379 }
1380 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1381 *out_storage_flag = FLAG_STORAGE_DE;
1382 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001383 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001384 return false;
1385 }
1386 return true;
1387}
1388
David Brazdil4f6027a2019-03-19 11:44:21 +00001389static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1390 /* out */ std::vector<std::string>* context_dex_paths) {
1391 if (class_loader_context == nullptr) {
1392 return true;
1393 }
1394
1395 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1396
1397 // Pipe to get the hash result back from our child process.
1398 unique_fd pipe_read, pipe_write;
1399 if (!Pipe(&pipe_read, &pipe_write)) {
1400 PLOG(ERROR) << "Failed to create pipe";
1401 return false;
1402 }
1403
1404 pid_t pid = fork();
1405 if (pid == 0) {
1406 // child -- drop privileges before continuing.
1407 drop_capabilities(uid);
1408
1409 // Route stdout to `pipe_write`
1410 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1411 pipe_write.reset();
1412 pipe_read.reset();
1413
1414 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1415 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1416 }
1417
1418 /* parent */
1419 pipe_write.reset();
1420
1421 std::string str_dex_paths;
1422 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1423 PLOG(ERROR) << "Failed to read from pipe";
1424 return false;
1425 }
1426 pipe_read.reset();
1427
1428 int return_code = wait_child(pid);
1429 if (!WIFEXITED(return_code)) {
1430 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1431 return false;
1432 }
1433
1434 constexpr int kFlattenClassLoaderContextSuccess = 50;
1435 return_code = WEXITSTATUS(return_code);
1436 if (return_code != kFlattenClassLoaderContextSuccess) {
1437 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1438 return false;
1439 }
1440
1441 if (!str_dex_paths.empty()) {
1442 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1443 }
1444 return true;
1445}
1446
1447static int open_dex_paths(const std::vector<std::string>& dex_paths,
1448 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1449 for (const std::string& dex_path : dex_paths) {
1450 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1451 if (zip_fds->back().get() < 0) {
1452 *error_msg = StringPrintf(
1453 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1454 if (errno == ENOENT) {
1455 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1456 } else {
1457 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1458 }
1459 }
1460 }
1461 return 0;
1462}
1463
1464static std::string join_fds(const std::vector<unique_fd>& fds) {
1465 std::stringstream ss;
1466 bool is_first = true;
1467 for (const unique_fd& fd : fds) {
1468 if (is_first) {
1469 is_first = false;
1470 } else {
1471 ss << ":";
1472 }
1473 ss << fd.get();
1474 }
1475 return ss.str();
1476}
1477
Calin Juravlec9eab382017-01-25 01:17:17 -08001478// 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 -08001479// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1480// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001481// When returning true, the output parameters will be:
1482// - is_public_out: whether or not the oat file should not be made public
1483// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1484// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001485static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001486 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001487 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001488 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001489 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001490 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001491 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001492 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1493 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001494 return false;
1495 }
Calin Juravle7d765462017-09-04 15:57:10 -07001496 // Compute the oat dir as it's not easy to extract it from the child computation.
1497 char oat_path[PKG_PATH_MAX];
1498 char oat_dir[PKG_PATH_MAX];
1499 char oat_isa_dir[PKG_PATH_MAX];
1500 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001501 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1502 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001503 return false;
1504 }
Calin Juravle7d765462017-09-04 15:57:10 -07001505 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001506
Calin Juravle80a21252017-01-17 14:43:25 -08001507 pid_t pid = fork();
1508 if (pid == 0) {
1509 // child -- drop privileges before continuing.
1510 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001511
1512 // Validate the path structure.
1513 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1514 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001515 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001516 }
1517
1518 // Open the dex file.
1519 unique_fd zip_fd;
1520 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1521 if (zip_fd.get() < 0) {
1522 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001523 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001524 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001525 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001526 }
1527 }
1528
David Brazdil4f6027a2019-03-19 11:44:21 +00001529 // Open class loader context dex files.
1530 std::vector<unique_fd> context_zip_fds;
1531 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1532 if (open_dex_paths_rc != 0) {
1533 _exit(open_dex_paths_rc);
1534 }
1535
Calin Juravle7d765462017-09-04 15:57:10 -07001536 // Prepare the oat directories.
1537 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001538 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001539 }
1540
1541 // Open the vdex/oat files if any.
1542 unique_fd oat_file_fd;
1543 unique_fd vdex_file_fd;
1544 if (!maybe_open_oat_and_vdex_file(dex_path,
1545 *oat_dir_out,
1546 instruction_set,
1547 true /* is_secondary_dex */,
1548 &oat_file_fd,
1549 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001550 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001551 }
1552
1553 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001554 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1555 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001556
1557 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001558 // Note that we do not do it before the fork since opening the files is required to happen
1559 // after forking.
1560 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1561 vdex_file_fd.get(),
1562 oat_file_fd.get(),
1563 zip_fd.get(),
1564 instruction_set,
1565 compiler_filter, profile_was_updated,
1566 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001567 class_loader_context,
1568 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001569 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001570 }
1571
1572 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001573 int result = wait_child(pid);
1574 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001575 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1576 dex_path.c_str(),
1577 result);
1578 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001579 return false;
1580 }
1581 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001582 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001583 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1584 result,
1585 dexopt_needed_out,
1586 error_msg);
1587 if (!success) {
1588 LOG(ERROR) << *error_msg;
1589 }
Calin Juravle7d765462017-09-04 15:57:10 -07001590
1591 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1592
Calin Juravle80a21252017-01-17 14:43:25 -08001593 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001594 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1595 // makes the code simpler; force compilation is only needed during tests).
1596 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001597 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001598 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001599 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1600 }
1601
Calin Juravle7d765462017-09-04 15:57:10 -07001602 // Check if we should make the oat file public.
1603 // Note that if the dex file is not public the compiled code cannot be made public.
1604 // It is ok to check this flag outside in the parent process.
1605 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1606
Calin Juravle80a21252017-01-17 14:43:25 -08001607 return success;
1608}
1609
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001610static std::string format_dexopt_error(int status, const char* dex_path) {
1611 if (WIFEXITED(status)) {
1612 int int_code = WEXITSTATUS(status);
1613 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1614 if (code_name != nullptr) {
1615 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1616 }
1617 }
1618 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001619}
1620
Calin Juravlec9eab382017-01-25 01:17:17 -08001621int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001622 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001623 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001624 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001625 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001626 CHECK(pkgname != nullptr);
1627 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001628 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001629 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1630 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001631
Calin Juravled23dee72017-07-06 16:29:11 -07001632 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001633 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001634 return -1;
1635 }
1636
1637 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001638 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1639 class_loader_context);
1640 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001641 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001642 }
1643
Calin Juravleebc8a792017-04-04 20:21:05 -07001644 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001645 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1646 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1647 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001648 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001649 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001650 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001651 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001652 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001653 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001654
1655 // Check if we're dealing with a secondary dex file and if we need to compile it.
1656 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001657 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001658 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001659 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1660 *error_msg = "Failed acquiring context dex paths";
1661 return -1; // We had an error, logged in the process method.
1662 }
1663
Calin Juravlec9eab382017-01-25 01:17:17 -08001664 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001665 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00001666 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001667 oat_dir = oat_dir_str.c_str();
1668 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1669 return 0; // Nothing to do, report success.
1670 }
1671 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001672 if (error_msg->empty()) { // TODO: Make this a CHECK.
1673 *error_msg = "Failed processing secondary.";
1674 }
Calin Juravle80a21252017-01-17 14:43:25 -08001675 return -1; // We had an error, logged in the process method.
1676 }
1677 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001678 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001679 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001680 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1681 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1682 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001683
1684 // Open the input file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001685 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1686 if (in_dex.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001687 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1688 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001689 return -1;
1690 }
1691
David Brazdil4f6027a2019-03-19 11:44:21 +00001692 // Open class loader context dex files.
1693 std::vector<unique_fd> context_input_fds;
1694 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1695 LOG(ERROR) << *error_msg;
1696 return -1;
1697 }
1698
Calin Juravle7a570e82017-01-14 16:23:30 -08001699 // Create the output OAT file.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001700 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1701 instruction_set, is_secondary_dex);
1702 if (out_oat.fd() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001703 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001704 return -1;
1705 }
1706
1707 // Open vdex files.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001708 UniqueFile in_vdex;
1709 UniqueFile out_vdex;
1710 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1711 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1712 &out_vdex)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001713 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001714 return -1;
1715 }
1716
Calin Juravlecb556e32017-04-04 20:22:50 -07001717 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1718 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1719 // fully inherit their parent context).
1720 // Note that for primary apk the oat files are created before, in a separate installd
1721 // call which also does the restorecon. TODO(calin): unify the paths.
1722 if (is_secondary_dex) {
1723 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1724 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001725 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1726 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001727 return -1;
1728 }
1729 }
1730
Jeff Sharkey90aff262016-12-12 14:28:24 -07001731 // Create a swap file if necessary.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001732 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001733
Calin Juravle7a570e82017-01-14 16:23:30 -08001734 // Open the reference profile if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001735 UniqueFile reference_profile = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001736 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001737
Victor Hsiehcb35a062020-08-13 16:11:13 -07001738 if (reference_profile.fd() == -1) {
liulvping61907742018-08-21 09:36:52 +08001739 // We don't create an app image without reference profile since there is no speedup from
1740 // loading it in that case and instead will be a small overhead.
1741 generate_app_image = false;
1742 }
1743
1744 // Create the app image file if needed.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001745 UniqueFile out_image = maybe_open_app_image(
1746 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
liulvping61907742018-08-21 09:36:52 +08001747
Victor Hsiehcb35a062020-08-13 16:11:13 -07001748 UniqueFile dex_metadata;
Calin Juravle62c5a372018-02-01 17:03:23 +00001749 if (dex_metadata_path != nullptr) {
Victor Hsiehcb35a062020-08-13 16:11:13 -07001750 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1751 dex_metadata_path);
1752 if (dex_metadata.fd() < 0) {
Calin Juravle62c5a372018-02-01 17:03:23 +00001753 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1754 }
1755 }
1756
Victor Hsieh8948a862020-08-07 11:30:55 -07001757 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1758 RUNTIME_NATIVE_BOOT_NAMESPACE,
1759 ENABLE_JITZYGOTE_IMAGE,
1760 /*default_value=*/ "");
1761 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1762
Victor Hsiehe98e6512020-08-10 15:39:22 -07001763 // Decide whether to use dex2oat64.
1764 bool use_dex2oat64 = false;
1765 // Check whether the device even supports 64-bit ABIs.
1766 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1767 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1768 }
1769 const char* dex2oat_bin = select_execution_binary(
1770 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1771 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1772 background_job_compile);
1773
Victor Hsiehc9821f12020-08-07 11:32:29 -07001774 auto execv_helper = std::make_unique<ExecVHelper>();
1775
Andreas Gampe023b2242018-02-28 16:03:25 -08001776 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001777
Victor Hsiehc9821f12020-08-07 11:32:29 -07001778 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
Victor Hsiehcb35a062020-08-13 16:11:13 -07001779 runner.Initialize(out_oat,
1780 out_vdex,
1781 out_image,
1782 in_dex,
1783 in_vdex,
1784 dex_metadata,
1785 reference_profile,
1786 class_loader_context,
1787 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001788 swap_fd.get(),
1789 instruction_set,
1790 compiler_filter,
1791 debuggable,
1792 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001793 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001794 target_sdk_version,
1795 enable_hidden_api_checks,
1796 generate_compact_dex,
Victor Hsieh8948a862020-08-07 11:30:55 -07001797 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001798 compilation_reason);
1799
Jeff Sharkey90aff262016-12-12 14:28:24 -07001800 pid_t pid = fork();
1801 if (pid == 0) {
1802 /* child -- drop privileges before continuing */
1803 drop_capabilities(uid);
1804
Richard Uhler76cc0272016-12-08 10:46:35 +00001805 SetDex2OatScheduling(boot_complete);
Victor Hsiehcb35a062020-08-13 16:11:13 -07001806 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
1807 PLOG(ERROR) << "flock(" << out_oat.path() << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001808 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001809 }
1810
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001811 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001812 } else {
1813 int res = wait_child(pid);
1814 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001815 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001816 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001817 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1818 << std::hex << std::setw(4) << res << ", process failed";
1819 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001820 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001821 }
1822 }
1823
Victor Hsiehcb35a062020-08-13 16:11:13 -07001824 update_out_oat_access_times(dex_path, out_oat.path().c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -07001825
1826 // We've been successful, don't delete output.
Victor Hsiehcb35a062020-08-13 16:11:13 -07001827 out_oat.DisableCleanup();
1828 out_vdex.DisableCleanup();
1829 out_image.DisableCleanup();
1830 reference_profile.DisableCleanup();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001831
1832 return 0;
1833}
1834
Calin Juravlec9eab382017-01-25 01:17:17 -08001835// Try to remove the given directory. Log an error if the directory exists
1836// and is empty but could not be removed.
1837static bool rmdir_if_empty(const char* dir) {
1838 if (rmdir(dir) == 0) {
1839 return true;
1840 }
1841 if (errno == ENOENT || errno == ENOTEMPTY) {
1842 return true;
1843 }
1844 PLOG(ERROR) << "Failed to remove dir: " << dir;
1845 return false;
1846}
1847
1848// Try to unlink the given file. Log an error if the file exists and could not
1849// be unlinked.
1850static bool unlink_if_exists(const std::string& file) {
1851 if (unlink(file.c_str()) == 0) {
1852 return true;
1853 }
1854 if (errno == ENOENT) {
1855 return true;
1856
1857 }
1858 PLOG(ERROR) << "Could not unlink: " << file;
1859 return false;
1860}
1861
Calin Juravle7d765462017-09-04 15:57:10 -07001862enum ReconcileSecondaryDexResult {
1863 kReconcileSecondaryDexExists = 0,
1864 kReconcileSecondaryDexCleanedUp = 1,
1865 kReconcileSecondaryDexValidationError = 2,
1866 kReconcileSecondaryDexCleanUpError = 3,
1867 kReconcileSecondaryDexAccessIOError = 4,
1868};
Calin Juravlec9eab382017-01-25 01:17:17 -08001869
1870// Reconcile the secondary dex 'dex_path' and its generated oat files.
1871// Return true if all the parameters are valid and the secondary dex file was
1872// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1873// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1874// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1875// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1876// Return false if there were errors during processing. In this case
1877// out_secondary_dex_exists will be set to false.
1878bool reconcile_secondary_dex_file(const std::string& dex_path,
1879 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001880 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08001881 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001882 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001883 if (isas.size() == 0) {
1884 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1885 return false;
1886 }
1887
Calin Juravle7d765462017-09-04 15:57:10 -07001888 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1889 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1890 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001891 return false;
1892 }
1893
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001894 // As a security measure we want to unlink art artifacts with the reduced capabilities
1895 // of the package user id. So we fork and drop capabilities in the child.
1896 pid_t pid = fork();
1897 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001898 /* child -- drop privileges before continuing */
1899 drop_capabilities(uid);
1900
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001901 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07001902 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07001903 uid, storage_flag)) {
1904 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1905 _exit(kReconcileSecondaryDexValidationError);
1906 }
1907
1908 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1909 switch (access_check) {
1910 case kSecondaryDexAccessDoesNotExist:
1911 // File does not exist. Proceed with cleaning.
1912 break;
1913 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1914 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1915 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1916 default:
1917 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
1918 _exit(kReconcileSecondaryDexValidationError);
1919 }
1920
1921 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001922 char oat_path[PKG_PATH_MAX];
1923 char oat_dir[PKG_PATH_MAX];
1924 char oat_isa_dir[PKG_PATH_MAX];
1925 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001926 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001927 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001928 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001929 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
1930 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07001931 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001932 }
Calin Juravle51314092017-05-18 15:33:05 -07001933
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001934 // Delete oat/vdex/art files.
1935 result = unlink_if_exists(oat_path) && result;
1936 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1937 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08001938
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001939 // Delete profiles.
1940 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001941 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001942 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08001943 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001944 result = unlink_if_exists(current_profile) && result;
1945 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07001946
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001947 // We upgraded once the location of current profile for secondary dex files.
1948 // Check for any previous left-overs and remove them as well.
1949 std::string old_current_profile = dex_path + ".prof";
1950 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07001951
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001952 // Try removing the directories as well, they might be empty.
1953 result = rmdir_if_empty(oat_isa_dir) && result;
1954 result = rmdir_if_empty(oat_dir) && result;
1955 }
Calin Juravle7d765462017-09-04 15:57:10 -07001956 if (!result) {
1957 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
1958 }
1959 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08001960 }
1961
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001962 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07001963 if (!WIFEXITED(return_code)) {
1964 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
1965 } else {
1966 return_code = WEXITSTATUS(return_code);
1967 }
1968
1969 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
1970
1971 switch (return_code) {
1972 case kReconcileSecondaryDexCleanedUp:
1973 case kReconcileSecondaryDexValidationError:
1974 // If we couldn't validate assume the dex file does not exist.
1975 // This will purge the entry from the PM records.
1976 *out_secondary_dex_exists = false;
1977 return true;
1978 case kReconcileSecondaryDexExists:
1979 *out_secondary_dex_exists = true;
1980 return true;
1981 case kReconcileSecondaryDexAccessIOError:
1982 // We had an access IO error.
1983 // Return false so that we can try again.
1984 // The value of out_secondary_dex_exists does not matter in this case and by convention
1985 // is set to false.
1986 *out_secondary_dex_exists = false;
1987 return false;
1988 default:
1989 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
1990 *out_secondary_dex_exists = false;
1991 return false;
1992 }
Calin Juravlec9eab382017-01-25 01:17:17 -08001993}
1994
Alan Stokesa25d90c2017-10-16 10:56:00 +01001995// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
1996// Returns true if all parameters are valid and the hash successfully computed and stored in
1997// out_secondary_dex_hash.
1998// Also returns true with an empty hash if the file does not currently exist or is not accessible to
1999// the app.
2000// For any other errors (e.g. if any of the parameters are invalid) returns false.
2001bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002002 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002003 std::vector<uint8_t>* out_secondary_dex_hash) {
2004 out_secondary_dex_hash->clear();
2005
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002006 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002007
2008 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2009 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2010 << storage_flag;
2011 return false;
2012 }
2013
2014 // Pipe to get the hash result back from our child process.
2015 unique_fd pipe_read, pipe_write;
2016 if (!Pipe(&pipe_read, &pipe_write)) {
2017 PLOG(ERROR) << "Failed to create pipe";
2018 return false;
2019 }
2020
2021 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2022 // access data the app itself can access.
2023 pid_t pid = fork();
2024 if (pid == 0) {
2025 // child -- drop privileges before continuing
2026 drop_capabilities(uid);
2027 pipe_read.reset();
2028
2029 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2030 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002031 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002032 }
2033
2034 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2035 if (fd == -1) {
2036 if (errno == EACCES || errno == ENOENT) {
2037 // Not treated as an error.
2038 _exit(0);
2039 }
2040 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002041 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002042 }
2043
2044 SHA256_CTX ctx;
2045 SHA256_Init(&ctx);
2046
2047 std::vector<uint8_t> buffer(65536);
2048 while (true) {
2049 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2050 if (bytes_read == 0) {
2051 break;
2052 } else if (bytes_read == -1) {
2053 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002054 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002055 }
2056
2057 SHA256_Update(&ctx, buffer.data(), bytes_read);
2058 }
2059
2060 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2061 SHA256_Final(hash.data(), &ctx);
2062 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002063 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002064 }
2065
2066 _exit(0);
2067 }
2068
2069 // parent
2070 pipe_write.reset();
2071
2072 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2073 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2074 out_secondary_dex_hash->clear();
2075 }
2076 return wait_child(pid) == 0;
2077}
2078
Jeff Sharkey90aff262016-12-12 14:28:24 -07002079// Helper for move_ab, so that we can have common failure-case cleanup.
2080static bool unlink_and_rename(const char* from, const char* to) {
2081 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2082 // return a failure.
2083 struct stat s;
2084 if (stat(to, &s) == 0) {
2085 if (!S_ISREG(s.st_mode)) {
2086 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2087 return false;
2088 }
2089 if (unlink(to) != 0) {
2090 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2091 return false;
2092 }
2093 } else {
2094 // This may be a permission problem. We could investigate the error code, but we'll just
2095 // let the rename failure do the work for us.
2096 }
2097
2098 // Try to rename "to" to "from."
2099 if (rename(from, to) != 0) {
2100 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2101 return false;
2102 }
2103 return true;
2104}
2105
2106// Move/rename a B artifact (from) to an A artifact (to).
2107static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2108 // Check whether B exists.
2109 {
2110 struct stat s;
2111 if (stat(b_path.c_str(), &s) != 0) {
2112 // Silently ignore for now. The service calling this isn't smart enough to understand
2113 // lack of artifacts at the moment.
2114 return false;
2115 }
2116 if (!S_ISREG(s.st_mode)) {
2117 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2118 // Try to unlink, but swallow errors.
2119 unlink(b_path.c_str());
2120 return false;
2121 }
2122 }
2123
2124 // Rename B to A.
2125 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2126 // Delete the b_path so we don't try again (or fail earlier).
2127 if (unlink(b_path.c_str()) != 0) {
2128 PLOG(ERROR) << "Could not unlink " << b_path;
2129 }
2130
2131 return false;
2132 }
2133
2134 return true;
2135}
2136
2137bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2138 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002139 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2140 if (slot_suffix.empty()) {
2141 return false;
2142 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002143
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002144 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2145 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2146 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002147 }
2148
2149 // Validate other inputs.
2150 if (validate_apk_path(apk_path) != 0) {
2151 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2152 return false;
2153 }
2154 if (validate_apk_path(oat_dir) != 0) {
2155 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2156 return false;
2157 }
2158
2159 char a_path[PKG_PATH_MAX];
2160 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2161 return false;
2162 }
2163 const std::string a_vdex_path = create_vdex_filename(a_path);
2164 const std::string a_image_path = create_image_filename(a_path);
2165
2166 // B path = A path + slot suffix.
2167 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2168 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2169 const std::string b_image_path = StringPrintf("%s.%s",
2170 a_image_path.c_str(),
2171 slot_suffix.c_str());
2172
2173 bool success = true;
2174 if (move_ab_path(b_path, a_path)) {
2175 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2176 // Note: we can live without an app image. As such, ignore failure to move the image file.
2177 // If we decide to require the app image, or the app image being moved correctly,
2178 // then change accordingly.
2179 constexpr bool kIgnoreAppImageFailure = true;
2180
2181 if (!a_image_path.empty()) {
2182 if (!move_ab_path(b_image_path, a_image_path)) {
2183 unlink(a_image_path.c_str());
2184 if (!kIgnoreAppImageFailure) {
2185 success = false;
2186 }
2187 }
2188 }
2189 } else {
2190 // Cleanup: delete B image, ignore errors.
2191 unlink(b_image_path.c_str());
2192 success = false;
2193 }
2194 } else {
2195 // Cleanup: delete B image, ignore errors.
2196 unlink(b_vdex_path.c_str());
2197 unlink(b_image_path.c_str());
2198 success = false;
2199 }
2200 return success;
2201}
2202
2203bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2204 // Delete the oat/odex file.
2205 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002206 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002207 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002208 return false;
2209 }
2210
2211 // In case of a permission failure report the issue. Otherwise just print a warning.
2212 auto unlink_and_check = [](const char* path) -> bool {
2213 int result = unlink(path);
2214 if (result != 0) {
2215 if (errno == EACCES || errno == EPERM) {
2216 PLOG(ERROR) << "Could not unlink " << path;
2217 return false;
2218 }
2219 PLOG(WARNING) << "Could not unlink " << path;
2220 }
2221 return true;
2222 };
2223
2224 // Delete the oat/odex file.
2225 bool return_value_oat = unlink_and_check(out_path);
2226
2227 // Derive and delete the app image.
2228 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2229
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002230 // Derive and delete the vdex file.
2231 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2232
Jeff Sharkey90aff262016-12-12 14:28:24 -07002233 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002234 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002235}
2236
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002237static bool is_absolute_path(const std::string& path) {
2238 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2239 LOG(ERROR) << "Invalid absolute path " << path;
2240 return false;
2241 } else {
2242 return true;
2243 }
2244}
2245
2246static bool is_valid_instruction_set(const std::string& instruction_set) {
2247 // TODO: add explicit whitelisting of instruction sets
2248 if (instruction_set.find('/') != std::string::npos) {
2249 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2250 return false;
2251 } else {
2252 return true;
2253 }
2254}
2255
2256bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2257 const char *apk_path, const char *instruction_set) {
2258 std::string oat_dir_ = oat_dir;
2259 std::string apk_path_ = apk_path;
2260 std::string instruction_set_ = instruction_set;
2261
2262 if (!is_absolute_path(oat_dir_)) return false;
2263 if (!is_absolute_path(apk_path_)) return false;
2264 if (!is_valid_instruction_set(instruction_set_)) return false;
2265
2266 std::string::size_type end = apk_path_.rfind('.');
2267 std::string::size_type start = apk_path_.rfind('/', end);
2268 if (end == std::string::npos || start == std::string::npos) {
2269 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2270 return false;
2271 }
2272
2273 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2274 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2275 const char* res = res_.c_str();
2276 if (strlen(res) >= PKG_PATH_MAX) {
2277 LOG(ERROR) << "Result too large";
2278 return false;
2279 } else {
2280 strlcpy(path, res, PKG_PATH_MAX);
2281 return true;
2282 }
2283}
2284
2285bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2286 const char *instruction_set) {
2287 std::string apk_path_ = apk_path;
2288 std::string instruction_set_ = instruction_set;
2289
2290 if (!is_absolute_path(apk_path_)) return false;
2291 if (!is_valid_instruction_set(instruction_set_)) return false;
2292
2293 std::string::size_type end = apk_path_.rfind('.');
2294 std::string::size_type start = apk_path_.rfind('/', end);
2295 if (end == std::string::npos || start == std::string::npos) {
2296 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2297 return false;
2298 }
2299
2300 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2301 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2302}
2303
2304bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2305 const char *instruction_set) {
2306 std::string src_ = src;
2307 std::string instruction_set_ = instruction_set;
2308
2309 if (!is_absolute_path(src_)) return false;
2310 if (!is_valid_instruction_set(instruction_set_)) return false;
2311
2312 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2313 if (*it == '/') {
2314 *it = '@';
2315 }
2316 }
2317
2318 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2319 + DALVIK_CACHE_POSTFIX;
2320 const char* res = res_.c_str();
2321 if (strlen(res) >= PKG_PATH_MAX) {
2322 LOG(ERROR) << "Result too large";
2323 return false;
2324 } else {
2325 strlcpy(path, res, PKG_PATH_MAX);
2326 return true;
2327 }
2328}
2329
Calin Juravle59f7ab82018-04-27 17:50:23 -07002330bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2331 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002332 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2333 for (const std::string& elem : classpaths_elems) {
2334 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2335 if (fd < 0) {
2336 PLOG(ERROR) << "Could not open classpath elem " << elem;
2337 return false;
2338 } else {
2339 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002340 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002341 }
2342 }
2343 return true;
2344}
2345
2346static bool create_app_profile_snapshot(int32_t app_id,
2347 const std::string& package_name,
2348 const std::string& profile_name,
2349 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002350 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2351
Calin Juravle824a64d2018-01-18 20:23:17 -08002352 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002353 if (snapshot_fd < 0) {
2354 return false;
2355 }
2356
2357 std::vector<unique_fd> profiles_fd;
2358 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002359 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2360 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002361 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2362 return false;
2363 }
2364
2365 profiles_fd.push_back(std::move(reference_profile_fd));
2366
Calin Juravle0d0a4922018-01-23 19:54:11 -08002367 // Open the class paths elements. These will be used to filter out profile data that does
2368 // not belong to the classpath during merge.
2369 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002370 std::vector<std::string> dex_locations;
2371 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002372 return false;
2373 }
2374
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002375 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002376 // This is specifically a snapshot for an app, so don't use boot image profiles.
2377 args.SetupMerge(profiles_fd,
2378 snapshot_fd,
2379 apk_fds,
2380 dex_locations,
2381 /* for_snapshot= */ true,
2382 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002383 pid_t pid = fork();
2384 if (pid == 0) {
2385 /* child -- drop privileges before continuing */
2386 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002387 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002388 }
2389
2390 /* parent */
2391 int return_code = wait_child(pid);
2392 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002393 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002394 return false;
2395 }
2396
Calin Juravle78728f32019-11-08 17:55:46 -08002397 // Verify that profman finished successfully.
2398 int profman_code = WEXITSTATUS(return_code);
2399 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2400 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2401 << ":" << profman_code;
2402 return false;
2403 }
Calin Juravle29591732017-11-20 17:46:19 -08002404 return true;
2405}
2406
Calin Juravle0d0a4922018-01-23 19:54:11 -08002407static bool create_boot_image_profile_snapshot(const std::string& package_name,
2408 const std::string& profile_name,
2409 const std::string& classpath) {
2410 // The reference profile directory for the android package might not be prepared. Do it now.
2411 const std::string ref_profile_dir =
2412 create_primary_reference_profile_package_dir_path(package_name);
2413 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2414 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2415 return false;
2416 }
2417
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002418 // Return false for empty class path since it may otherwise return true below if profiles is
2419 // empty.
2420 if (classpath.empty()) {
2421 PLOG(ERROR) << "Class path is empty";
2422 return false;
2423 }
2424
Calin Juravle0d0a4922018-01-23 19:54:11 -08002425 // Open and create the snapshot profile.
2426 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2427
2428 // Collect all non empty profiles.
2429 // The collection will traverse all applications profiles and find the non empty files.
2430 // This has the potential of inspecting a large number of files and directories (depending
2431 // on the number of applications and users). So there is a slight increase in the chance
2432 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2433 // fail the snapshot and aggregate whatever profile we could open.
2434 //
2435 // The profile snapshot is a best effort based on available data it's ok if some data
2436 // from some apps is missing. It will be counter productive for the snapshot to fail
2437 // because we could not open or read some of the files.
2438 std::vector<std::string> profiles;
2439 if (!collect_profiles(&profiles)) {
2440 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2441 }
2442
2443 // If we have no profiles return early.
2444 if (profiles.empty()) {
2445 return true;
2446 }
2447
2448 // Open the classpath elements. These will be used to filter out profile data that does
2449 // not belong to the classpath during merge.
2450 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002451 std::vector<std::string> dex_locations;
2452 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002453 return false;
2454 }
2455
2456 // If we could not open any files from the classpath return an error.
2457 if (apk_fds.empty()) {
2458 LOG(ERROR) << "Could not open any of the classpath elements.";
2459 return false;
2460 }
2461
2462 // Aggregate the profiles in batches of kAggregationBatchSize.
2463 // We do this to avoid opening a huge a amount of files.
2464 static constexpr size_t kAggregationBatchSize = 10;
2465
Calin Juravle0d0a4922018-01-23 19:54:11 -08002466 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002467 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002468 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2469 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2470 if (fd.get() >= 0) {
2471 profiles_fd.push_back(std::move(fd));
2472 }
2473 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002474
2475 // We aggregate (read & write) into the same fd multiple times in a row.
2476 // We need to reset the cursor every time to ensure we read the whole file every time.
2477 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2478 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2479 return false;
2480 }
2481
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002482 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002483 args.SetupMerge(profiles_fd,
2484 snapshot_fd,
2485 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002486 dex_locations,
2487 /*for_snapshot=*/true,
2488 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002489 pid_t pid = fork();
2490 if (pid == 0) {
2491 /* child -- drop privileges before continuing */
2492 drop_capabilities(AID_SYSTEM);
2493
Calin Juravle59f7ab82018-04-27 17:50:23 -07002494 // The introduction of new access flags into boot jars causes them to
2495 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002496 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002497 }
2498
2499 /* parent */
2500 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002501
Calin Juravle0d0a4922018-01-23 19:54:11 -08002502 if (!WIFEXITED(return_code)) {
2503 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2504 return false;
2505 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002506
2507 // Verify that profman finished successfully.
2508 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002509 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2510 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2511 << ":" << profman_code;
2512 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002513 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002514 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002515
Calin Juravle0d0a4922018-01-23 19:54:11 -08002516 return true;
2517}
2518
2519bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2520 const std::string& profile_name, const std::string& classpath) {
2521 if (app_id == -1) {
2522 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2523 } else {
2524 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2525 }
2526}
2527
Calin Juravlec3b049e2018-01-18 22:32:58 -08002528bool prepare_app_profile(const std::string& package_name,
2529 userid_t user_id,
2530 appid_t app_id,
2531 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002532 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002533 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002534 // Prepare the current profile.
2535 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2536 /*is_secondary_dex*/ false);
2537 uid_t uid = multiuser_get_uid(user_id, app_id);
2538 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2539 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2540 return false;
2541 }
2542
2543 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002544 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002545 return true;
2546 }
2547
2548 // We have a dex metdata. Merge the profile into the reference profile.
2549 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2550 /*read_write*/ true, /*is_secondary_dex*/ false);
2551 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2552 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002553 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2554 if (apk_fd < 0) {
2555 PLOG(ERROR) << "Could not open code path " << code_path;
2556 return false;
2557 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002558
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002559 RunProfman args;
2560 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2561 std::move(ref_profile_fd),
2562 std::move(apk_fd),
2563 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002564 pid_t pid = fork();
2565 if (pid == 0) {
2566 /* child -- drop privileges before continuing */
2567 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2568 drop_capabilities(app_shared_gid);
2569
Calin Juravlef63d4792018-01-30 17:43:34 +00002570 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002571 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002572 }
2573
2574 /* parent */
2575 int return_code = wait_child(pid);
2576 if (!WIFEXITED(return_code)) {
2577 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2578 return false;
2579 }
2580 return true;
2581}
2582
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002583} // namespace installd
2584} // namespace android