blob: 82ea7464757cd18795d30656f96105b273a2d2dd [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070042#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010043#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000045#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070046#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000047#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
50#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080051#include "dexopt_return_codes.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070052#include "execv_helper.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060053#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070054#include "installd_deps.h"
55#include "otapreopt_utils.h"
Victor Hsiehc9821f12020-08-07 11:32:29 -070056#include "run_dex2oat.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070057#include "utils.h"
58
Victor Hsieh76f19ba2020-08-10 14:37:26 -070059using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070060using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070061using android::base::GetBoolProperty;
62using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000063using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010064using android::base::ReadFully;
65using android::base::StringPrintf;
66using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080067using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070068
69namespace android {
70namespace installd {
71
Andreas Gampefa2dadd2018-02-28 19:52:47 -080072
Calin Juravle114f0812017-03-08 19:05:07 -080073// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
74struct FreeDelete {
75 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
76 void operator()(const void* ptr) const {
77 free(const_cast<void*>(ptr));
78 }
79};
80
81// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
82template <typename T>
83using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
84
Calin Juravle1a0af3b2017-03-09 14:33:33 -080085static unique_fd invalid_unique_fd() {
86 return unique_fd(-1);
87}
88
Andreas Gampe6a9cf722017-07-24 16:49:10 -070089static bool is_debug_runtime() {
90 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
91}
92
David Sehra3b5ab62017-10-25 14:27:29 -070093static bool is_debuggable_build() {
94 return android::base::GetBoolProperty("ro.debuggable", false);
95}
96
Jeff Sharkey90aff262016-12-12 14:28:24 -070097static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080098 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070099 if (ufd.get() < 0) {
100 if (errno != ENOENT) {
101 PLOG(WARNING) << "Could not open profile " << profile;
102 return false;
103 } else {
104 // Nothing to clear. That's ok.
105 return true;
106 }
107 }
108
109 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
110 if (errno != EWOULDBLOCK) {
111 PLOG(WARNING) << "Error locking profile " << profile;
112 }
113 // This implies that the app owning this profile is running
114 // (and has acquired the lock).
115 //
116 // If we can't acquire the lock bail out since clearing is useless anyway
117 // (the app will write again to the profile).
118 //
119 // Note:
120 // This does not impact the this is not an issue for the profiling correctness.
121 // In case this is needed because of an app upgrade, profiles will still be
122 // eventually cleared by the app itself due to checksum mismatch.
123 // If this is needed because profman advised, then keeping the data around
124 // until the next run is again not an issue.
125 //
126 // If the app attempts to acquire a lock while we've held one here,
127 // it will simply skip the current write cycle.
128 return false;
129 }
130
131 bool truncated = ftruncate(ufd.get(), 0) == 0;
132 if (!truncated) {
133 PLOG(WARNING) << "Could not truncate " << profile;
134 }
135 if (flock(ufd.get(), LOCK_UN) != 0) {
136 PLOG(WARNING) << "Error unlocking profile " << profile;
137 }
138 return truncated;
139}
140
Calin Juravle114f0812017-03-08 19:05:07 -0800141// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800142// The location is the profile name for primary apks or the dex path for secondary dex files.
143static bool clear_reference_profile(const std::string& package_name, const std::string& location,
144 bool is_secondary_dex) {
145 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700146}
147
Calin Juravle114f0812017-03-08 19:05:07 -0800148// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800149// The location is the profile name for primary apks or the dex path for secondary dex files.
150static bool clear_current_profile(const std::string& package_name, const std::string& location,
151 userid_t user, bool is_secondary_dex) {
152 return clear_profile(create_current_profile_path(user, package_name, location,
153 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154}
155
Calin Juravle114f0812017-03-08 19:05:07 -0800156// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800157// The location is the profile name for primary apks or the dex path for secondary dex files.
158bool clear_primary_reference_profile(const std::string& package_name,
159 const std::string& location) {
160 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800161}
162
163// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800164// The location is the profile name for primary apks or the dex path for secondary dex files.
165bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700166 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800167 // 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 -0700168 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
169 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800170 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700171 }
172 return success;
173}
174
Calin Juravle114f0812017-03-08 19:05:07 -0800175// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800176bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
177 userid_t user) {
178 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800179}
180
Calin Juravlef74a7372019-02-28 20:29:41 -0800181// Determines which binary we should use for execution (the debug or non-debug version).
182// e.g. dex2oatd vs dex2oat
183static const char* select_execution_binary(const char* binary, const char* debug_binary,
184 bool background_job_compile) {
185 return select_execution_binary(
186 binary,
187 debug_binary,
188 background_job_compile,
189 is_debug_runtime(),
190 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
191 is_debuggable_build());
192}
193
194// Determines which binary we should use for execution (the debug or non-debug version).
195// e.g. dex2oatd vs dex2oat
196// This is convenient method which is much easier to test because it doesn't read
197// system properties.
198const char* select_execution_binary(
199 const char* binary,
200 const char* debug_binary,
201 bool background_job_compile,
202 bool is_debug_runtime,
203 bool is_release,
204 bool is_debuggable_build) {
205 // Do not use debug binaries for release candidates (to give more soak time).
206 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
207
208 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
209 // the file is present (it may not be on images with very little space available).
210 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
211
212 return useDebug ? debug_binary : binary;
213}
214
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000215// Namespace for Android Runtime flags applied during boot time.
216static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
217// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000218static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000219
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700220// Phenotype property name for enabling profiling the boot class path.
221static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
222
Calin Juravlef85ddb92020-05-01 14:05:40 -0700223static bool IsBootClassPathProfilingEnable() {
224 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
225 profile_boot_class_path =
226 server_configurable_flags::GetServerConfigurableFlag(
227 RUNTIME_NATIVE_BOOT_NAMESPACE,
228 PROFILE_BOOT_CLASS_PATH,
229 /*default_value=*/ profile_boot_class_path);
230 return profile_boot_class_path == "true";
231}
232
Jeff Sharkey90aff262016-12-12 14:28:24 -0700233/*
234 * Whether dexopt should use a swap file when compiling an APK.
235 *
236 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
237 * itself, anyways).
238 *
239 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
240 *
241 * Otherwise, return true if this is a low-mem device.
242 *
243 * Otherwise, return default value.
244 */
245static bool kAlwaysProvideSwapFile = false;
246static bool kDefaultProvideSwapFile = true;
247
248static bool ShouldUseSwapFileForDexopt() {
249 if (kAlwaysProvideSwapFile) {
250 return true;
251 }
252
253 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700254 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
255 if (!dex2oat_prop_buf.empty()) {
256 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700257 }
258
259 // Shortcut for default value. This is an implementation optimization for the process sketched
260 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
261 // as low-mem is never returning false. The compiler will optimize this away if it can.
262 if (kDefaultProvideSwapFile) {
263 return true;
264 }
265
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700266 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700267 return true;
268 }
269
270 // Default value must be false here.
271 return kDefaultProvideSwapFile;
272}
273
Richard Uhler76cc0272016-12-08 10:46:35 +0000274static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700275 if (set_to_bg) {
276 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800277 PLOG(ERROR) << "set_sched_policy failed";
278 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700279 }
280 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800281 PLOG(ERROR) << "setpriority failed";
282 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700283 }
284 }
285}
286
Calin Juravle29591732017-11-20 17:46:19 -0800287static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
288 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800289 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800290 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800291 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800292 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800293 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700294 }
Calin Juravle114f0812017-03-08 19:05:07 -0800295 // Profiles should belong to the app; make sure of that by giving ownership to
296 // the app uid. If we cannot do that, there's no point in returning the fd
297 // since dex2oat/profman will fail with SElinux denials.
298 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000299 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800300 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800301 }
Calin Juravle29591732017-11-20 17:46:19 -0800302 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800303}
304
Calin Juravle29591732017-11-20 17:46:19 -0800305static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800306 // Do not follow symlinks when opening a profile:
307 // - primary profiles should not contain symlinks in their paths
308 // - secondary dex paths should have been already resolved and validated
309 flags |= O_NOFOLLOW;
310
Calin Juravle29591732017-11-20 17:46:19 -0800311 // Check if we need to create the profile
312 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
313 unique_fd fd;
314 if ((flags & O_CREAT) != 0) {
315 fd = create_profile(uid, profile, flags);
316 } else {
317 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
318 }
319
Calin Juravle114f0812017-03-08 19:05:07 -0800320 if (fd.get() < 0) {
321 if (errno != ENOENT) {
322 // Profiles might be missing for various reasons. For example, in a
323 // multi-user environment, the profile directory for one user can be created
324 // after we start a merge. In this case the current profile for that user
325 // will not be found.
326 // Also, the secondary dex profiles might be deleted by the app at any time,
327 // so we can't we need to prepare if they are missing.
328 PLOG(ERROR) << "Failed to open profile " << profile;
329 }
330 return invalid_unique_fd();
331 }
332
Jeff Sharkey90aff262016-12-12 14:28:24 -0700333 return fd;
334}
335
Calin Juravle824a64d2018-01-18 20:23:17 -0800336static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
337 const std::string& location, bool is_secondary_dex) {
338 std::string profile = create_current_profile_path(user, package_name, location,
339 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800340 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800341}
342
Calin Juravle824a64d2018-01-18 20:23:17 -0800343static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
344 const std::string& location, bool read_write, bool is_secondary_dex) {
345 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800346 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
347}
348
349static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800350 const std::string& location) {
351 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800352 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800353}
354
Calin Juravle824a64d2018-01-18 20:23:17 -0800355static void open_profile_files(uid_t uid, const std::string& package_name,
356 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800357 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700358 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800359 *reference_profile_fd = open_reference_profile(uid, package_name, location,
360 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700361
Calin Juravle114f0812017-03-08 19:05:07 -0800362 // For secondary dex files, we don't really need the user but we use it for sanity checks.
363 // Note: the user owning the dex file should be the current user.
364 std::vector<userid_t> users;
365 if (is_secondary_dex){
366 users.push_back(multiuser_get_user_id(uid));
367 } else {
368 users = get_known_users(/*volume_uuid*/ nullptr);
369 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700370 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800371 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
372 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700373 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800374 if (profile_fd.get() >= 0) {
375 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700376 }
377 }
378}
379
Calin Juravle76561322019-11-14 09:08:52 -0800380static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
381static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
382static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
383static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
384static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
385static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
386static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388class RunProfman : public ExecVHelper {
389 public:
390 void SetupArgs(const std::vector<unique_fd>& profile_fds,
391 const unique_fd& reference_profile_fd,
392 const std::vector<unique_fd>& apk_fds,
393 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800394 bool copy_and_update,
395 bool for_snapshot,
396 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800397
398 // TODO(calin): Assume for now we run in the bg compile job (which is in
399 // most of the invocation). With the current data flow, is not very easy or
400 // clean to discover this in RunProfman (it will require quite a messy refactoring).
401 const char* profman_bin = select_execution_binary(
402 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700403
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800404 if (copy_and_update) {
405 CHECK_EQ(1u, profile_fds.size());
406 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000407 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800408 if (reference_profile_fd != -1) {
409 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000410 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800411
412 for (const unique_fd& fd : profile_fds) {
413 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
414 }
415
416 for (const unique_fd& fd : apk_fds) {
417 AddArg("--apk-fd=" + std::to_string(fd.get()));
418 }
419
420 for (const std::string& dex_location : dex_locations) {
421 AddArg("--dex-location=" + dex_location);
422 }
423
424 if (copy_and_update) {
425 AddArg("--copy-and-update-profile-key");
426 }
427
Calin Juravle78728f32019-11-08 17:55:46 -0800428 if (for_snapshot) {
429 AddArg("--force-merge");
430 }
431
432 if (for_boot_image) {
433 AddArg("--boot-image-merge");
434 }
435
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800436 // Do not add after dex2oat_flags, they should override others for debugging.
437 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800438 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700439
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800440 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
441 const unique_fd& reference_profile_fd,
442 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800443 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
444 bool for_snapshot = false,
445 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800446 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800447 reference_profile_fd,
448 apk_fds,
449 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800450 /*copy_and_update=*/ false,
451 for_snapshot,
452 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800453 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700454
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800455 void SetupCopyAndUpdate(unique_fd&& profile_fd,
456 unique_fd&& reference_profile_fd,
457 unique_fd&& apk_fd,
458 const std::string& dex_location) {
459 // The fds need to stay open longer than the scope of the function, so put them into a local
460 // variable vector.
461 profiles_fd_.push_back(std::move(profile_fd));
462 apk_fds_.push_back(std::move(apk_fd));
463 reference_profile_fd_ = std::move(reference_profile_fd);
464 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800465 SetupArgs(profiles_fd_,
466 reference_profile_fd_,
467 apk_fds_,
468 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800469 /*copy_and_update=*/true,
470 /*for_snapshot*/false,
471 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800472 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000473
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800474 void SetupDump(const std::vector<unique_fd>& profiles_fd,
475 const unique_fd& reference_profile_fd,
476 const std::vector<std::string>& dex_locations,
477 const std::vector<unique_fd>& apk_fds,
478 const unique_fd& output_fd) {
479 AddArg("--dump-only");
480 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800481 SetupArgs(profiles_fd,
482 reference_profile_fd,
483 apk_fds,
484 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800485 /*copy_and_update=*/false,
486 /*for_snapshot*/false,
487 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800488 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000489
Victor Hsiehc9821f12020-08-07 11:32:29 -0700490 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800491 void Exec() {
492 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
493 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000494
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800495 private:
496 unique_fd reference_profile_fd_;
497 std::vector<unique_fd> profiles_fd_;
498 std::vector<unique_fd> apk_fds_;
499};
Mathieu Chartier31636522018-11-09 23:53:07 +0000500
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800501
Calin Juravlef63d4792018-01-30 17:43:34 +0000502
Jeff Sharkey90aff262016-12-12 14:28:24 -0700503// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800504// The location is the package name for primary apks or the dex path for secondary dex files.
505// Returns true if there is enough information in the current profiles that makes it
506// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700507// If the return value is true all the current profiles would have been merged into
508// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800509static bool analyze_profiles(uid_t uid, const std::string& package_name,
510 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800511 std::vector<unique_fd> profiles_fd;
512 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800513 open_profile_files(uid, package_name, location, is_secondary_dex,
514 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800515 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700516 // Skip profile guided compilation because no profiles were found.
517 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700518 return false;
519 }
520
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800521 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700522 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
523 const std::vector<std::string>& dex_locations = std::vector<std::string>();
524 profman_merge.SetupMerge(
525 profiles_fd,
526 reference_profile_fd,
527 apk_fds,
528 dex_locations,
529 /* for_snapshot= */ false,
530 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700531 pid_t pid = fork();
532 if (pid == 0) {
533 /* child -- drop privileges before continuing */
534 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800535 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700536 }
537 /* parent */
538 int return_code = wait_child(pid);
539 bool need_to_compile = false;
540 bool should_clear_current_profiles = false;
541 bool should_clear_reference_profile = false;
542 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800543 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700544 } else {
545 return_code = WEXITSTATUS(return_code);
546 switch (return_code) {
547 case PROFMAN_BIN_RETURN_CODE_COMPILE:
548 need_to_compile = true;
549 should_clear_current_profiles = true;
550 should_clear_reference_profile = false;
551 break;
552 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
553 need_to_compile = false;
554 should_clear_current_profiles = false;
555 should_clear_reference_profile = false;
556 break;
557 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800558 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700559 need_to_compile = false;
560 should_clear_current_profiles = true;
561 should_clear_reference_profile = true;
562 break;
563 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
564 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
565 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800566 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700567 need_to_compile = false;
568 should_clear_current_profiles = false;
569 should_clear_reference_profile = false;
570 break;
Calin Juravle76561322019-11-14 09:08:52 -0800571 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
572 need_to_compile = false;
573 should_clear_current_profiles = true;
574 should_clear_reference_profile = true;
575 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700576 default:
577 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800578 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800579 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700580 need_to_compile = false;
581 should_clear_current_profiles = true;
582 should_clear_reference_profile = true;
583 break;
584 }
585 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800586
Jeff Sharkey90aff262016-12-12 14:28:24 -0700587 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800588 if (is_secondary_dex) {
589 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800590 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
591 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800592 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800593 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800594 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700595 }
596 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800597 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598 }
599 return need_to_compile;
600}
601
Calin Juravle114f0812017-03-08 19:05:07 -0800602// Decides if profile guided compilation is needed or not based on existing profiles.
603// The analysis is done for the primary apks of the given package.
604// Returns true if there is enough information in the current profiles that makes it
605// worth to recompile the package.
606// If the return value is true all the current profiles would have been merged into
607// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800608bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
609 const std::string& profile_name) {
610 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800611}
612
Calin Juravle408cd4a2018-01-20 23:34:18 -0800613bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
614 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800615 std::vector<unique_fd> profile_fds;
616 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800617 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
618 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700619
Calin Juravle408cd4a2018-01-20 23:34:18 -0800620 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800621 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700622
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800623 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700624 const bool has_profiles = !profile_fds.empty();
625
626 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800627 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700628 return false;
629 }
630
Calin Juravle114f0812017-03-08 19:05:07 -0800631 unique_fd output_fd(open(out_file_name.c_str(),
632 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800634 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700635 return false;
636 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800637
Jeff Sharkey90aff262016-12-12 14:28:24 -0700638 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800639 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800640 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
641 if (apk_fd == -1) {
642 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
643 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700645 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800646 apk_fds.push_back(std::move(apk_fd));
647
Jeff Sharkey90aff262016-12-12 14:28:24 -0700648
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800649 RunProfman profman_dump;
650 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700651 pid_t pid = fork();
652 if (pid == 0) {
653 /* child -- drop privileges before continuing */
654 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800655 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 }
657 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700658 int return_code = wait_child(pid);
659 if (!WIFEXITED(return_code)) {
660 LOG(WARNING) << "profman failed for package " << pkgname << ": "
661 << return_code;
662 return false;
663 }
664 return true;
665}
666
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700667bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800668 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700669 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
670 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800671 package_name,
672 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700673 /*read_write*/ true,
674 /*secondary*/ false));
675 if (in_fd.get() < 0) {
676 PLOG(WARNING) << "Could not open profile " << system_profile;
677 return false;
678 }
679 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800680 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700681 return false;
682 }
683
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700684 // As a security measure we want to write the profile information with the reduced capabilities
685 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700686 pid_t pid = fork();
687 if (pid == 0) {
688 /* child -- drop privileges before continuing */
689 drop_capabilities(packageUid);
690
691 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
692 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800693 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700694 }
695 // This implies that the app owning this profile is running
696 // (and has acquired the lock).
697 //
698 // The app never acquires the lock for the reference profiles of primary apks.
699 // Only dex2oat from installd will do that. Since installd is single threaded
700 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800701 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700702 return false;
703 }
704
705 bool truncated = ftruncate(out_fd.get(), 0) == 0;
706 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800707 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700708 }
709
710 // Copy over data.
711 static constexpr size_t kBufferSize = 4 * 1024;
712 char buffer[kBufferSize];
713 while (true) {
714 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
715 if (bytes == 0) {
716 break;
717 }
718 write(out_fd.get(), buffer, bytes);
719 }
720 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800721 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700722 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700723 // Use _exit since we don't want to run the global destructors in the child.
724 // b/62597429
725 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700726 }
727 /* parent */
728 int return_code = wait_child(pid);
729 return return_code == 0;
730}
731
Jeff Sharkey90aff262016-12-12 14:28:24 -0700732static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
733 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
734 if (EndsWith(oat_path, ".dex")) {
735 std::string new_path = oat_path;
736 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800737 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700738 return new_path;
739 }
740
741 // An odex entry. Not that this may not be an extension, e.g., in the OTA
742 // case (where the base name will have an extension for the B artifact).
743 size_t odex_pos = oat_path.rfind(".odex");
744 if (odex_pos != std::string::npos) {
745 std::string new_path = oat_path;
746 new_path.replace(odex_pos, strlen(".odex"), new_ext);
747 CHECK_NE(new_path.find(new_ext), std::string::npos);
748 return new_path;
749 }
750
751 // Don't know how to handle this.
752 return "";
753}
754
755// Translate the given oat path to an art (app image) path. An empty string
756// denotes an error.
757static std::string create_image_filename(const std::string& oat_path) {
758 return replace_file_extension(oat_path, ".art");
759}
760
761// Translate the given oat path to a vdex path. An empty string denotes an error.
762static std::string create_vdex_filename(const std::string& oat_path) {
763 return replace_file_extension(oat_path, ".vdex");
764}
765
Jeff Sharkey90aff262016-12-12 14:28:24 -0700766static int open_output_file(const char* file_name, bool recreate, int permissions) {
767 int flags = O_RDWR | O_CREAT;
768 if (recreate) {
769 if (unlink(file_name) < 0) {
770 if (errno != ENOENT) {
771 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
772 }
773 }
774 flags |= O_EXCL;
775 }
776 return open(file_name, flags, permissions);
777}
778
Calin Juravle2289c0a2017-02-15 12:44:14 -0800779static bool set_permissions_and_ownership(
780 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
781 // Primary apks are owned by the system. Secondary dex files are owned by the app.
782 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783 if (fchmod(fd,
784 S_IRUSR|S_IWUSR|S_IRGRP |
785 (is_public ? S_IROTH : 0)) < 0) {
786 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
787 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800788 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789 ALOGE("installd cannot chown '%s' during dexopt\n", path);
790 return false;
791 }
792 return true;
793}
794
795static bool IsOutputDalvikCache(const char* oat_dir) {
796 // InstallerConnection.java (which invokes installd) transforms Java null arguments
797 // into '!'. Play it safe by handling it both.
798 // TODO: ensure we never get null.
799 // TODO: pass a flag instead of inferring if the output is dalvik cache.
800 return oat_dir == nullptr || oat_dir[0] == '!';
801}
802
Calin Juravled23dee72017-07-06 16:29:11 -0700803// Best-effort check whether we can fit the the path into our buffers.
804// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
805// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
806// extension to the cache path (5 bytes).
807// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
808static bool validate_dex_path_size(const std::string& dex_path) {
809 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
810 LOG(ERROR) << "dex_path too long: " << dex_path;
811 return false;
812 }
813 return true;
814}
815
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800817 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -0700818 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700819 return false;
820 }
821
822 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800823 // Oat dirs for secondary dex files are already validated.
824 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
826 return false;
827 }
828 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
829 return false;
830 }
831 } else {
832 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
833 return false;
834 }
835 }
836 return true;
837}
838
839// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
840// on destruction. It will also run the given cleanup (unless told not to) after closing.
841//
842// Usage example:
843//
Calin Juravle7a570e82017-01-14 16:23:30 -0800844// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700845// [name]() {
846// unlink(name.c_str());
847// });
848// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
849// wrapper if captured as a reference.
850//
851// if (file.get() == -1) {
852// // Error opening...
853// }
854//
855// ...
856// if (error) {
857// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
858// // and delete the file (after the fd is closed).
859// return -1;
860// }
861//
862// (Success case)
863// file.SetCleanup(false);
864// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
865// // (leaving the file around; after the fd is closed).
866//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867class Dex2oatFileWrapper {
868 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800869 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 }
871
Calin Juravle7a570e82017-01-14 16:23:30 -0800872 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
873 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
874
875 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
876 value_ = other.value_;
877 cleanup_ = other.cleanup_;
878 do_cleanup_ = other.do_cleanup_;
879 auto_close_ = other.auto_close_;
880 other.release();
881 }
882
883 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
884 value_ = other.value_;
885 cleanup_ = other.cleanup_;
886 do_cleanup_ = other.do_cleanup_;
887 auto_close_ = other.auto_close_;
888 other.release();
889 return *this;
890 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700891
892 ~Dex2oatFileWrapper() {
893 reset(-1);
894 }
895
896 int get() {
897 return value_;
898 }
899
900 void SetCleanup(bool cleanup) {
901 do_cleanup_ = cleanup;
902 }
903
904 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800905 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700906 close(value_);
907 }
908 if (do_cleanup_ && cleanup_ != nullptr) {
909 cleanup_();
910 }
911
912 value_ = new_value;
913 }
914
Calin Juravle7a570e82017-01-14 16:23:30 -0800915 void reset(int new_value, std::function<void ()> new_cleanup) {
916 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700917 close(value_);
918 }
919 if (do_cleanup_ && cleanup_ != nullptr) {
920 cleanup_();
921 }
922
923 value_ = new_value;
924 cleanup_ = new_cleanup;
925 }
926
Calin Juravle7a570e82017-01-14 16:23:30 -0800927 void DisableAutoClose() {
928 auto_close_ = false;
929 }
930
Jeff Sharkey90aff262016-12-12 14:28:24 -0700931 private:
Calin Juravle7a570e82017-01-14 16:23:30 -0800932 void release() {
933 value_ = -1;
934 do_cleanup_ = false;
935 cleanup_ = nullptr;
936 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -0800938 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700939 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -0800940 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700941};
942
Calin Juravle7a570e82017-01-14 16:23:30 -0800943// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700944Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
945 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100946
Calin Juravle7a570e82017-01-14 16:23:30 -0800947 const std::string image_path = create_image_filename(out_oat_path);
948 if (image_path.empty()) {
949 // Happens when the out_oat_path has an unknown extension.
950 return Dex2oatFileWrapper();
951 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100952
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -0700953 // In case there is a stale image, remove it now. Ignore any error.
954 unlink(image_path.c_str());
955
956 // Not enabled, exit.
957 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +0100958 return Dex2oatFileWrapper();
959 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700960 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
961 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800962 return Dex2oatFileWrapper();
963 }
964 // Recreate is true since we do not want to modify a mapped image. If the app is
965 // already running and we modify the image file, it can cause crashes (b/27493510).
966 Dex2oatFileWrapper wrapper_fd(
967 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
968 [image_path]() { unlink(image_path.c_str()); });
969 if (wrapper_fd.get() < 0) {
970 // Could not create application image file. Go on since we can compile without it.
971 LOG(ERROR) << "installd could not create '" << image_path
972 << "' for image file during dexopt";
973 // If we have a valid image file path but no image fd, explicitly erase the image file.
974 if (unlink(image_path.c_str()) < 0) {
975 if (errno != ENOENT) {
976 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
977 }
978 }
979 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -0800980 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800981 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
982 wrapper_fd.reset(-1);
983 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700984
Calin Juravle7a570e82017-01-14 16:23:30 -0800985 return wrapper_fd;
986}
987
988// Creates the dexopt swap file if necessary and return its fd.
989// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800990unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800991 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800992 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -0800993 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600994 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800995 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600996 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -0800997 if (swap_fd.get() < 0) {
998 // Could not create swap file. Optimistically go on and hope that we can compile
999 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001000 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001001 } else {
1002 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001003 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001004 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1005 }
1006 }
1007 return swap_fd;
1008}
1009
1010// Opens the reference profiles if needed.
1011// Note that the reference profile might not exist so it's OK if the fd will be -1.
Calin Juravle114f0812017-03-08 19:05:07 -08001012Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001013 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001014 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001015 // If we are not profile guided compilation, or we are compiling system server
1016 // do not bother to open the profiles; we won't be using them.
1017 if (!profile_guided || (pkgname[0] == '*')) {
1018 return Dex2oatFileWrapper();
1019 }
1020
1021 // If this is a secondary dex path which is public do not open the profile.
1022 // We cannot compile public secondary dex paths with profiles. That's because
1023 // it will expose how the dex files are used by their owner.
1024 //
1025 // Note that the PackageManager is responsible to set the is_public flag for
1026 // primary apks and we do not check it here. In some cases, e.g. when
1027 // compiling with a public profile from the .dm file the PackageManager will
1028 // set is_public toghether with the profile guided compilation.
1029 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001030 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001031 }
Calin Juravle114f0812017-03-08 19:05:07 -08001032
1033 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001034 std::string location;
1035 if (is_secondary_dex) {
1036 location = dex_path;
1037 } else {
1038 if (profile_name == nullptr) {
1039 // This path is taken for system server re-compilation lunched from ZygoteInit.
1040 return Dex2oatFileWrapper();
1041 } else {
1042 location = profile_name;
1043 }
1044 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001045 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1046 is_secondary_dex);
1047 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1048 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001049 };
1050 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001051}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001052
Calin Juravle7a570e82017-01-14 16:23:30 -08001053// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1054// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001055bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001056 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001057 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001058 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1059 CHECK(in_vdex_wrapper_fd != nullptr);
1060 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001061 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1062 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001063 char in_odex_path[PKG_PATH_MAX];
1064 int dexopt_action = abs(dexopt_needed);
1065 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001066 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001067
1068 // Infer the name of the output VDEX.
1069 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1070 if (out_vdex_path_str.empty()) {
1071 return false;
1072 }
1073
1074 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001075 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001076 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1077 const char* path = nullptr;
1078 if (is_odex_location) {
1079 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1080 path = in_odex_path;
1081 } else {
1082 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001083 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001084 }
1085 } else {
1086 path = out_oat_path;
1087 }
1088 in_vdex_path_str = create_vdex_filename(path);
1089 if (in_vdex_path_str.empty()) {
1090 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001091 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001092 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001093 // We can update in place when all these conditions are met:
1094 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1095 // on /system typically cannot be updated in place).
1096 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1097 // cannot be currently used by a running process.
1098 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1099 // different vdex files to operate.
1100 update_vdex_in_place =
1101 (in_vdex_path_str == out_vdex_path_str) &&
1102 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1103 !profile_guided;
1104 if (update_vdex_in_place) {
1105 // Open the file read-write to be able to update it.
1106 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1107 if (in_vdex_wrapper_fd->get() == -1) {
1108 // If we failed to open the file, we cannot update it in place.
1109 update_vdex_in_place = false;
1110 }
1111 } else {
1112 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1113 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001114 }
1115
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001116 // If we are updating the vdex in place, we do not need to recreate a vdex,
1117 // and can use the same existing one.
1118 if (update_vdex_in_place) {
1119 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1120 // have bogus stale vdex files.
1121 out_vdex_wrapper_fd->reset(
1122 in_vdex_wrapper_fd->get(),
1123 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1124 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1125 // wrapper).
1126 in_vdex_wrapper_fd->DisableAutoClose();
1127 } else {
1128 out_vdex_wrapper_fd->reset(
1129 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1130 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1131 if (out_vdex_wrapper_fd->get() < 0) {
1132 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1133 return false;
1134 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001136 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001137 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001138 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1139 return false;
1140 }
1141
1142 // If we got here we successfully opened the vdex files.
1143 return true;
1144}
1145
1146// Opens the output oat file for the given apk.
1147// If successful it stores the output path into out_oat_path and returns true.
1148Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001149 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1150 char* out_oat_path) {
1151 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001152 return Dex2oatFileWrapper();
1153 }
1154 const std::string out_oat_path_str(out_oat_path);
1155 Dex2oatFileWrapper wrapper_fd(
1156 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1157 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1158 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001159 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001160 } else if (!set_permissions_and_ownership(
1161 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001162 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1163 wrapper_fd.reset(-1);
1164 }
1165 return wrapper_fd;
1166}
1167
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001168// Creates RDONLY fds for oat and vdex files, if exist.
1169// Returns false if it fails to create oat out path for the given apk path.
1170// Note that the method returns true even if the files could not be opened.
1171bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1172 const std::string& oat_dir,
1173 const std::string& instruction_set,
1174 bool is_secondary_dex,
1175 unique_fd* oat_file_fd,
1176 unique_fd* vdex_file_fd) {
1177 char oat_path[PKG_PATH_MAX];
1178 if (!create_oat_out_path(apk_path.c_str(),
1179 instruction_set.c_str(),
1180 oat_dir.c_str(),
1181 is_secondary_dex,
1182 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001183 LOG(ERROR) << "Could not create oat out path for "
1184 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001185 return false;
1186 }
1187 oat_file_fd->reset(open(oat_path, O_RDONLY));
1188 if (oat_file_fd->get() < 0) {
1189 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1190 }
1191
1192 std::string vdex_filename = create_vdex_filename(oat_path);
1193 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1194 if (vdex_file_fd->get() < 0) {
1195 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1196 }
1197
1198 return true;
1199}
1200
Calin Juravle7a570e82017-01-14 16:23:30 -08001201// Updates the access times of out_oat_path based on those from apk_path.
1202void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1203 struct stat input_stat;
1204 memset(&input_stat, 0, sizeof(input_stat));
1205 if (stat(apk_path, &input_stat) != 0) {
1206 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1207 return;
1208 }
1209
1210 struct utimbuf ut;
1211 ut.actime = input_stat.st_atime;
1212 ut.modtime = input_stat.st_mtime;
1213 if (utime(out_oat_path, &ut) != 0) {
1214 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1215 }
1216}
1217
Calin Juravle80a21252017-01-17 14:43:25 -08001218// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001219// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1220// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1221// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001222class RunDexoptAnalyzer : public ExecVHelper {
1223 public:
1224 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001225 int vdex_fd,
1226 int oat_fd,
1227 int zip_fd,
1228 const std::string& instruction_set,
1229 const std::string& compiler_filter,
1230 bool profile_was_updated,
1231 bool downgrade,
1232 const char* class_loader_context,
1233 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001234 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001235
1236 // We always run the analyzer in the background job.
1237 const char* dexoptanalyzer_bin = select_execution_binary(
1238 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001239
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001240 std::string dex_file_arg = "--dex-file=" + dex_file;
1241 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1242 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1243 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1244 std::string isa_arg = "--isa=" + instruction_set;
1245 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1246 const char* assume_profile_changed = "--assume-profile-changed";
1247 const char* downgrade_flag = "--downgrade";
1248 std::string class_loader_context_arg = "--class-loader-context=";
1249 if (class_loader_context != nullptr) {
1250 class_loader_context_arg += class_loader_context;
1251 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001252 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1253 if (!class_loader_context_fds.empty()) {
1254 class_loader_context_fds_arg += class_loader_context_fds;
1255 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001256
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001257 // program name, dex file, isa, filter
1258 AddArg(dex_file_arg);
1259 AddArg(isa_arg);
1260 AddArg(compiler_filter_arg);
1261 if (oat_fd >= 0) {
1262 AddArg(oat_fd_arg);
1263 }
1264 if (vdex_fd >= 0) {
1265 AddArg(vdex_fd_arg);
1266 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001267 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001268 if (profile_was_updated) {
1269 AddArg(assume_profile_changed);
1270 }
1271 if (downgrade) {
1272 AddArg(downgrade_flag);
1273 }
1274 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001275 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001276 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001277 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001278 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001279 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001280
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001281 PrepareArgs(dexoptanalyzer_bin);
1282 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001283
1284 // Dexoptanalyzer mode which flattens the given class loader context and
1285 // prints a list of its dex files in that flattened order.
1286 RunDexoptAnalyzer(const char* class_loader_context) {
1287 CHECK(class_loader_context != nullptr);
1288
1289 // We always run the analyzer in the background job.
1290 const char* dexoptanalyzer_bin = select_execution_binary(
1291 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1292
1293 AddArg("--flatten-class-loader-context");
1294 AddArg(std::string("--class-loader-context=") + class_loader_context);
1295 PrepareArgs(dexoptanalyzer_bin);
1296 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001297};
Calin Juravle80a21252017-01-17 14:43:25 -08001298
1299// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001300static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001301 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001302 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001303 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001304 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001305 return false;
1306 }
Calin Juravle114f0812017-03-08 19:05:07 -08001307 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001308
Calin Juravle80a21252017-01-17 14:43:25 -08001309 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001310 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1311 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001312 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001313 return false;
1314 }
1315
1316 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001317 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001318
Calin Juravle7d765462017-09-04 15:57:10 -07001319 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001320 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001321 return false;
1322 }
1323
1324 return true;
1325}
1326
Calin Juravle7d765462017-09-04 15:57:10 -07001327// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1328// secondary dex files. This return codes are returned by the child process created for
1329// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001330
Andreas Gampe194fe422018-02-28 20:16:19 -08001331enum DexoptAnalyzerSkipCodes {
1332 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001333 // Specific errors are encoded in the name.
1334 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1335 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1336 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1337 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1338 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001339 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001340 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001341};
Calin Juravle7d765462017-09-04 15:57:10 -07001342
1343// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001344// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1345// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001346// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1347// of dexoptanalyzer.
1348static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001349 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001350 // The result values are defined in dexoptanalyzer.
1351 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001352 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001353 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001354 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001355 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001356 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001357 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001358 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001359 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001360 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1361 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001362 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1363 " Expected odex file status for secondary dex %s"
1364 " : dexoptanalyzer result=%d",
1365 dex_path.c_str(),
1366 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001367 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001368 }
1369
1370 // Use a second switch for enum switch-case analysis.
1371 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001372 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001373 // If the file does not exist there's no need for dexopt.
1374 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1375 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001376
1377 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1378 *error_msg = "Dexoptanalyzer path validation failed";
1379 return false;
1380 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1381 *error_msg = "Dexoptanalyzer open zip failed";
1382 return false;
1383 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1384 *error_msg = "Dexoptanalyzer dir preparation failed";
1385 return false;
1386 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1387 *error_msg = "Dexoptanalyzer open output failed";
1388 return false;
1389 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1390 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001391 return false;
1392 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001393
1394 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1395 dex_path.c_str(),
1396 result);
1397 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001398}
1399
Calin Juravle7d765462017-09-04 15:57:10 -07001400enum SecondaryDexAccess {
1401 kSecondaryDexAccessReadOk = 0,
1402 kSecondaryDexAccessDoesNotExist = 1,
1403 kSecondaryDexAccessPermissionError = 2,
1404 kSecondaryDexAccessIOError = 3
1405};
1406
1407static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1408 // Check if the path exists and can be read. If not, there's nothing to do.
1409 if (access(dex_path.c_str(), R_OK) == 0) {
1410 return kSecondaryDexAccessReadOk;
1411 } else {
1412 if (errno == ENOENT) {
1413 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1414 return kSecondaryDexAccessDoesNotExist;
1415 } else {
1416 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1417 return errno == EACCES
1418 ? kSecondaryDexAccessPermissionError
1419 : kSecondaryDexAccessIOError;
1420 }
1421 }
1422}
1423
1424static bool is_file_public(const std::string& filename) {
1425 struct stat file_stat;
1426 if (stat(filename.c_str(), &file_stat) == 0) {
1427 return (file_stat.st_mode & S_IROTH) != 0;
1428 }
1429 return false;
1430}
1431
1432// Create the oat file structure for the secondary dex 'dex_path' and assign
1433// the individual path component to the 'out_' parameters.
1434static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001435 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001436 size_t dirIndex = dex_path.rfind('/');
1437 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001438 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001439 return false;
1440 }
1441 // TODO(calin): we have similar computations in at lest 3 other places
1442 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1443 // using string append.
1444 std::string apk_dir = dex_path.substr(0, dirIndex);
1445 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1446 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1447
1448 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1449 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001450 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001451 return false;
1452 }
1453 return true;
1454}
1455
1456// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1457// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001458static bool validate_dexopt_storage_flags(int dexopt_flags,
1459 int* out_storage_flag,
1460 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001461 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1462 *out_storage_flag = FLAG_STORAGE_CE;
1463 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001464 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001465 return false;
1466 }
1467 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1468 *out_storage_flag = FLAG_STORAGE_DE;
1469 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001470 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001471 return false;
1472 }
1473 return true;
1474}
1475
David Brazdil4f6027a2019-03-19 11:44:21 +00001476static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1477 /* out */ std::vector<std::string>* context_dex_paths) {
1478 if (class_loader_context == nullptr) {
1479 return true;
1480 }
1481
1482 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1483
1484 // Pipe to get the hash result back from our child process.
1485 unique_fd pipe_read, pipe_write;
1486 if (!Pipe(&pipe_read, &pipe_write)) {
1487 PLOG(ERROR) << "Failed to create pipe";
1488 return false;
1489 }
1490
1491 pid_t pid = fork();
1492 if (pid == 0) {
1493 // child -- drop privileges before continuing.
1494 drop_capabilities(uid);
1495
1496 // Route stdout to `pipe_write`
1497 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1498 pipe_write.reset();
1499 pipe_read.reset();
1500
1501 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1502 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1503 }
1504
1505 /* parent */
1506 pipe_write.reset();
1507
1508 std::string str_dex_paths;
1509 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1510 PLOG(ERROR) << "Failed to read from pipe";
1511 return false;
1512 }
1513 pipe_read.reset();
1514
1515 int return_code = wait_child(pid);
1516 if (!WIFEXITED(return_code)) {
1517 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1518 return false;
1519 }
1520
1521 constexpr int kFlattenClassLoaderContextSuccess = 50;
1522 return_code = WEXITSTATUS(return_code);
1523 if (return_code != kFlattenClassLoaderContextSuccess) {
1524 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1525 return false;
1526 }
1527
1528 if (!str_dex_paths.empty()) {
1529 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1530 }
1531 return true;
1532}
1533
1534static int open_dex_paths(const std::vector<std::string>& dex_paths,
1535 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1536 for (const std::string& dex_path : dex_paths) {
1537 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1538 if (zip_fds->back().get() < 0) {
1539 *error_msg = StringPrintf(
1540 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1541 if (errno == ENOENT) {
1542 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1543 } else {
1544 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1545 }
1546 }
1547 }
1548 return 0;
1549}
1550
1551static std::string join_fds(const std::vector<unique_fd>& fds) {
1552 std::stringstream ss;
1553 bool is_first = true;
1554 for (const unique_fd& fd : fds) {
1555 if (is_first) {
1556 is_first = false;
1557 } else {
1558 ss << ":";
1559 }
1560 ss << fd.get();
1561 }
1562 return ss.str();
1563}
1564
Calin Juravlec9eab382017-01-25 01:17:17 -08001565// 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 -08001566// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1567// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001568// When returning true, the output parameters will be:
1569// - is_public_out: whether or not the oat file should not be made public
1570// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1571// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001572static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001573 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001574 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001575 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001576 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001577 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001578 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001579 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1580 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001581 return false;
1582 }
Calin Juravle7d765462017-09-04 15:57:10 -07001583 // Compute the oat dir as it's not easy to extract it from the child computation.
1584 char oat_path[PKG_PATH_MAX];
1585 char oat_dir[PKG_PATH_MAX];
1586 char oat_isa_dir[PKG_PATH_MAX];
1587 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001588 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1589 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001590 return false;
1591 }
Calin Juravle7d765462017-09-04 15:57:10 -07001592 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001593
Calin Juravle80a21252017-01-17 14:43:25 -08001594 pid_t pid = fork();
1595 if (pid == 0) {
1596 // child -- drop privileges before continuing.
1597 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001598
1599 // Validate the path structure.
1600 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1601 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001602 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001603 }
1604
1605 // Open the dex file.
1606 unique_fd zip_fd;
1607 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1608 if (zip_fd.get() < 0) {
1609 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001610 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001611 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001612 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001613 }
1614 }
1615
David Brazdil4f6027a2019-03-19 11:44:21 +00001616 // Open class loader context dex files.
1617 std::vector<unique_fd> context_zip_fds;
1618 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1619 if (open_dex_paths_rc != 0) {
1620 _exit(open_dex_paths_rc);
1621 }
1622
Calin Juravle7d765462017-09-04 15:57:10 -07001623 // Prepare the oat directories.
1624 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001625 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001626 }
1627
1628 // Open the vdex/oat files if any.
1629 unique_fd oat_file_fd;
1630 unique_fd vdex_file_fd;
1631 if (!maybe_open_oat_and_vdex_file(dex_path,
1632 *oat_dir_out,
1633 instruction_set,
1634 true /* is_secondary_dex */,
1635 &oat_file_fd,
1636 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001637 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001638 }
1639
1640 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001641 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1642 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001643
1644 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001645 // Note that we do not do it before the fork since opening the files is required to happen
1646 // after forking.
1647 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1648 vdex_file_fd.get(),
1649 oat_file_fd.get(),
1650 zip_fd.get(),
1651 instruction_set,
1652 compiler_filter, profile_was_updated,
1653 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001654 class_loader_context,
1655 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001656 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001657 }
1658
1659 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001660 int result = wait_child(pid);
1661 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001662 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1663 dex_path.c_str(),
1664 result);
1665 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001666 return false;
1667 }
1668 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001669 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001670 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1671 result,
1672 dexopt_needed_out,
1673 error_msg);
1674 if (!success) {
1675 LOG(ERROR) << *error_msg;
1676 }
Calin Juravle7d765462017-09-04 15:57:10 -07001677
1678 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1679
Calin Juravle80a21252017-01-17 14:43:25 -08001680 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001681 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1682 // makes the code simpler; force compilation is only needed during tests).
1683 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001684 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001685 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001686 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1687 }
1688
Calin Juravle7d765462017-09-04 15:57:10 -07001689 // Check if we should make the oat file public.
1690 // Note that if the dex file is not public the compiled code cannot be made public.
1691 // It is ok to check this flag outside in the parent process.
1692 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1693
Calin Juravle80a21252017-01-17 14:43:25 -08001694 return success;
1695}
1696
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001697static std::string format_dexopt_error(int status, const char* dex_path) {
1698 if (WIFEXITED(status)) {
1699 int int_code = WEXITSTATUS(status);
1700 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1701 if (code_name != nullptr) {
1702 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1703 }
1704 }
1705 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001706}
1707
Calin Juravlec9eab382017-01-25 01:17:17 -08001708int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001709 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001710 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001711 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001712 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001713 CHECK(pkgname != nullptr);
1714 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001715 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001716 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1717 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001718
Calin Juravled23dee72017-07-06 16:29:11 -07001719 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001720 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001721 return -1;
1722 }
1723
1724 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001725 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1726 class_loader_context);
1727 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001728 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001729 }
1730
Calin Juravleebc8a792017-04-04 20:21:05 -07001731 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001732 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1733 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1734 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001735 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001736 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001737 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001738 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001739 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001740 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001741
1742 // Check if we're dealing with a secondary dex file and if we need to compile it.
1743 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00001744 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08001745 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00001746 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1747 *error_msg = "Failed acquiring context dex paths";
1748 return -1; // We had an error, logged in the process method.
1749 }
1750
Calin Juravlec9eab382017-01-25 01:17:17 -08001751 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001752 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00001753 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001754 oat_dir = oat_dir_str.c_str();
1755 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1756 return 0; // Nothing to do, report success.
1757 }
1758 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001759 if (error_msg->empty()) { // TODO: Make this a CHECK.
1760 *error_msg = "Failed processing secondary.";
1761 }
Calin Juravle80a21252017-01-17 14:43:25 -08001762 return -1; // We had an error, logged in the process method.
1763 }
1764 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00001765 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001766 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001767 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1768 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1769 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001770
1771 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001772 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001773 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001774 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1775 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001776 return -1;
1777 }
1778
David Brazdil4f6027a2019-03-19 11:44:21 +00001779 // Open class loader context dex files.
1780 std::vector<unique_fd> context_input_fds;
1781 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1782 LOG(ERROR) << *error_msg;
1783 return -1;
1784 }
1785
Calin Juravle7a570e82017-01-14 16:23:30 -08001786 // Create the output OAT file.
1787 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001788 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001789 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001790 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001791 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001792 return -1;
1793 }
1794
1795 // Open vdex files.
1796 Dex2oatFileWrapper in_vdex_fd;
1797 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001798 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1799 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001800 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001801 return -1;
1802 }
1803
Calin Juravlecb556e32017-04-04 20:22:50 -07001804 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1805 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1806 // fully inherit their parent context).
1807 // Note that for primary apk the oat files are created before, in a separate installd
1808 // call which also does the restorecon. TODO(calin): unify the paths.
1809 if (is_secondary_dex) {
1810 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1811 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001812 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1813 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001814 return -1;
1815 }
1816 }
1817
Jeff Sharkey90aff262016-12-12 14:28:24 -07001818 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001819 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001820
Calin Juravle7a570e82017-01-14 16:23:30 -08001821 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001822 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001823 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001824
liulvping61907742018-08-21 09:36:52 +08001825 if (reference_profile_fd.get() == -1) {
1826 // We don't create an app image without reference profile since there is no speedup from
1827 // loading it in that case and instead will be a small overhead.
1828 generate_app_image = false;
1829 }
1830
1831 // Create the app image file if needed.
1832 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1833 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
1834
Calin Juravle62c5a372018-02-01 17:03:23 +00001835 unique_fd dex_metadata_fd;
1836 if (dex_metadata_path != nullptr) {
1837 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1838 if (dex_metadata_fd.get() < 0) {
1839 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1840 }
1841 }
1842
Victor Hsieh8948a862020-08-07 11:30:55 -07001843 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1844 RUNTIME_NATIVE_BOOT_NAMESPACE,
1845 ENABLE_JITZYGOTE_IMAGE,
1846 /*default_value=*/ "");
1847 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1848
Victor Hsiehe98e6512020-08-10 15:39:22 -07001849 // Decide whether to use dex2oat64.
1850 bool use_dex2oat64 = false;
1851 // Check whether the device even supports 64-bit ABIs.
1852 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1853 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1854 }
1855 const char* dex2oat_bin = select_execution_binary(
1856 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1857 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1858 background_job_compile);
1859
Victor Hsiehc9821f12020-08-07 11:32:29 -07001860 auto execv_helper = std::make_unique<ExecVHelper>();
1861
Andreas Gampe023b2242018-02-28 16:03:25 -08001862 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001863
Victor Hsiehc9821f12020-08-07 11:32:29 -07001864 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
1865 runner.Initialize(input_fd.get(),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001866 out_oat_fd.get(),
1867 in_vdex_fd.get(),
1868 out_vdex_fd.get(),
1869 image_fd.get(),
1870 dex_path,
1871 out_oat_path,
1872 swap_fd.get(),
1873 instruction_set,
1874 compiler_filter,
1875 debuggable,
1876 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07001877 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001878 reference_profile_fd.get(),
1879 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001880 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001881 target_sdk_version,
1882 enable_hidden_api_checks,
1883 generate_compact_dex,
1884 dex_metadata_fd.get(),
Victor Hsieh8948a862020-08-07 11:30:55 -07001885 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001886 compilation_reason);
1887
Jeff Sharkey90aff262016-12-12 14:28:24 -07001888 pid_t pid = fork();
1889 if (pid == 0) {
1890 /* child -- drop privileges before continuing */
1891 drop_capabilities(uid);
1892
Richard Uhler76cc0272016-12-08 10:46:35 +00001893 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001894 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001895 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001896 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001897 }
1898
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001899 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001900 } else {
1901 int res = wait_child(pid);
1902 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001903 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001904 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001905 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1906 << std::hex << std::setw(4) << res << ", process failed";
1907 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001908 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001909 }
1910 }
1911
Calin Juravlec9eab382017-01-25 01:17:17 -08001912 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001913
1914 // We've been successful, don't delete output.
1915 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001916 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001917 image_fd.SetCleanup(false);
1918 reference_profile_fd.SetCleanup(false);
1919
1920 return 0;
1921}
1922
Calin Juravlec9eab382017-01-25 01:17:17 -08001923// Try to remove the given directory. Log an error if the directory exists
1924// and is empty but could not be removed.
1925static bool rmdir_if_empty(const char* dir) {
1926 if (rmdir(dir) == 0) {
1927 return true;
1928 }
1929 if (errno == ENOENT || errno == ENOTEMPTY) {
1930 return true;
1931 }
1932 PLOG(ERROR) << "Failed to remove dir: " << dir;
1933 return false;
1934}
1935
1936// Try to unlink the given file. Log an error if the file exists and could not
1937// be unlinked.
1938static bool unlink_if_exists(const std::string& file) {
1939 if (unlink(file.c_str()) == 0) {
1940 return true;
1941 }
1942 if (errno == ENOENT) {
1943 return true;
1944
1945 }
1946 PLOG(ERROR) << "Could not unlink: " << file;
1947 return false;
1948}
1949
Calin Juravle7d765462017-09-04 15:57:10 -07001950enum ReconcileSecondaryDexResult {
1951 kReconcileSecondaryDexExists = 0,
1952 kReconcileSecondaryDexCleanedUp = 1,
1953 kReconcileSecondaryDexValidationError = 2,
1954 kReconcileSecondaryDexCleanUpError = 3,
1955 kReconcileSecondaryDexAccessIOError = 4,
1956};
Calin Juravlec9eab382017-01-25 01:17:17 -08001957
1958// Reconcile the secondary dex 'dex_path' and its generated oat files.
1959// Return true if all the parameters are valid and the secondary dex file was
1960// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1961// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1962// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1963// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1964// Return false if there were errors during processing. In this case
1965// out_secondary_dex_exists will be set to false.
1966bool reconcile_secondary_dex_file(const std::string& dex_path,
1967 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001968 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08001969 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001970 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001971 if (isas.size() == 0) {
1972 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1973 return false;
1974 }
1975
Calin Juravle7d765462017-09-04 15:57:10 -07001976 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1977 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1978 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001979 return false;
1980 }
1981
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001982 // As a security measure we want to unlink art artifacts with the reduced capabilities
1983 // of the package user id. So we fork and drop capabilities in the child.
1984 pid_t pid = fork();
1985 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001986 /* child -- drop privileges before continuing */
1987 drop_capabilities(uid);
1988
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001989 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07001990 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07001991 uid, storage_flag)) {
1992 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1993 _exit(kReconcileSecondaryDexValidationError);
1994 }
1995
1996 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1997 switch (access_check) {
1998 case kSecondaryDexAccessDoesNotExist:
1999 // File does not exist. Proceed with cleaning.
2000 break;
2001 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2002 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2003 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2004 default:
2005 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2006 _exit(kReconcileSecondaryDexValidationError);
2007 }
2008
2009 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002010 char oat_path[PKG_PATH_MAX];
2011 char oat_dir[PKG_PATH_MAX];
2012 char oat_isa_dir[PKG_PATH_MAX];
2013 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002014 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002015 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002016 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002017 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2018 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002019 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002020 }
Calin Juravle51314092017-05-18 15:33:05 -07002021
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002022 // Delete oat/vdex/art files.
2023 result = unlink_if_exists(oat_path) && result;
2024 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2025 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002026
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002027 // Delete profiles.
2028 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002029 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002030 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002031 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002032 result = unlink_if_exists(current_profile) && result;
2033 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002034
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002035 // We upgraded once the location of current profile for secondary dex files.
2036 // Check for any previous left-overs and remove them as well.
2037 std::string old_current_profile = dex_path + ".prof";
2038 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002039
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002040 // Try removing the directories as well, they might be empty.
2041 result = rmdir_if_empty(oat_isa_dir) && result;
2042 result = rmdir_if_empty(oat_dir) && result;
2043 }
Calin Juravle7d765462017-09-04 15:57:10 -07002044 if (!result) {
2045 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2046 }
2047 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002048 }
2049
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002050 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002051 if (!WIFEXITED(return_code)) {
2052 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2053 } else {
2054 return_code = WEXITSTATUS(return_code);
2055 }
2056
2057 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2058
2059 switch (return_code) {
2060 case kReconcileSecondaryDexCleanedUp:
2061 case kReconcileSecondaryDexValidationError:
2062 // If we couldn't validate assume the dex file does not exist.
2063 // This will purge the entry from the PM records.
2064 *out_secondary_dex_exists = false;
2065 return true;
2066 case kReconcileSecondaryDexExists:
2067 *out_secondary_dex_exists = true;
2068 return true;
2069 case kReconcileSecondaryDexAccessIOError:
2070 // We had an access IO error.
2071 // Return false so that we can try again.
2072 // The value of out_secondary_dex_exists does not matter in this case and by convention
2073 // is set to false.
2074 *out_secondary_dex_exists = false;
2075 return false;
2076 default:
2077 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2078 *out_secondary_dex_exists = false;
2079 return false;
2080 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002081}
2082
Alan Stokesa25d90c2017-10-16 10:56:00 +01002083// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2084// Returns true if all parameters are valid and the hash successfully computed and stored in
2085// out_secondary_dex_hash.
2086// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2087// the app.
2088// For any other errors (e.g. if any of the parameters are invalid) returns false.
2089bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002090 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002091 std::vector<uint8_t>* out_secondary_dex_hash) {
2092 out_secondary_dex_hash->clear();
2093
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002094 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002095
2096 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2097 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2098 << storage_flag;
2099 return false;
2100 }
2101
2102 // Pipe to get the hash result back from our child process.
2103 unique_fd pipe_read, pipe_write;
2104 if (!Pipe(&pipe_read, &pipe_write)) {
2105 PLOG(ERROR) << "Failed to create pipe";
2106 return false;
2107 }
2108
2109 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2110 // access data the app itself can access.
2111 pid_t pid = fork();
2112 if (pid == 0) {
2113 // child -- drop privileges before continuing
2114 drop_capabilities(uid);
2115 pipe_read.reset();
2116
2117 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2118 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002119 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002120 }
2121
2122 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2123 if (fd == -1) {
2124 if (errno == EACCES || errno == ENOENT) {
2125 // Not treated as an error.
2126 _exit(0);
2127 }
2128 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002129 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002130 }
2131
2132 SHA256_CTX ctx;
2133 SHA256_Init(&ctx);
2134
2135 std::vector<uint8_t> buffer(65536);
2136 while (true) {
2137 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2138 if (bytes_read == 0) {
2139 break;
2140 } else if (bytes_read == -1) {
2141 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002142 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002143 }
2144
2145 SHA256_Update(&ctx, buffer.data(), bytes_read);
2146 }
2147
2148 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2149 SHA256_Final(hash.data(), &ctx);
2150 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002151 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002152 }
2153
2154 _exit(0);
2155 }
2156
2157 // parent
2158 pipe_write.reset();
2159
2160 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2161 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2162 out_secondary_dex_hash->clear();
2163 }
2164 return wait_child(pid) == 0;
2165}
2166
Jeff Sharkey90aff262016-12-12 14:28:24 -07002167// Helper for move_ab, so that we can have common failure-case cleanup.
2168static bool unlink_and_rename(const char* from, const char* to) {
2169 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2170 // return a failure.
2171 struct stat s;
2172 if (stat(to, &s) == 0) {
2173 if (!S_ISREG(s.st_mode)) {
2174 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2175 return false;
2176 }
2177 if (unlink(to) != 0) {
2178 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2179 return false;
2180 }
2181 } else {
2182 // This may be a permission problem. We could investigate the error code, but we'll just
2183 // let the rename failure do the work for us.
2184 }
2185
2186 // Try to rename "to" to "from."
2187 if (rename(from, to) != 0) {
2188 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2189 return false;
2190 }
2191 return true;
2192}
2193
2194// Move/rename a B artifact (from) to an A artifact (to).
2195static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2196 // Check whether B exists.
2197 {
2198 struct stat s;
2199 if (stat(b_path.c_str(), &s) != 0) {
2200 // Silently ignore for now. The service calling this isn't smart enough to understand
2201 // lack of artifacts at the moment.
2202 return false;
2203 }
2204 if (!S_ISREG(s.st_mode)) {
2205 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2206 // Try to unlink, but swallow errors.
2207 unlink(b_path.c_str());
2208 return false;
2209 }
2210 }
2211
2212 // Rename B to A.
2213 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2214 // Delete the b_path so we don't try again (or fail earlier).
2215 if (unlink(b_path.c_str()) != 0) {
2216 PLOG(ERROR) << "Could not unlink " << b_path;
2217 }
2218
2219 return false;
2220 }
2221
2222 return true;
2223}
2224
2225bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2226 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002227 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2228 if (slot_suffix.empty()) {
2229 return false;
2230 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002231
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002232 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2233 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2234 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002235 }
2236
2237 // Validate other inputs.
2238 if (validate_apk_path(apk_path) != 0) {
2239 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2240 return false;
2241 }
2242 if (validate_apk_path(oat_dir) != 0) {
2243 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2244 return false;
2245 }
2246
2247 char a_path[PKG_PATH_MAX];
2248 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2249 return false;
2250 }
2251 const std::string a_vdex_path = create_vdex_filename(a_path);
2252 const std::string a_image_path = create_image_filename(a_path);
2253
2254 // B path = A path + slot suffix.
2255 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2256 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2257 const std::string b_image_path = StringPrintf("%s.%s",
2258 a_image_path.c_str(),
2259 slot_suffix.c_str());
2260
2261 bool success = true;
2262 if (move_ab_path(b_path, a_path)) {
2263 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2264 // Note: we can live without an app image. As such, ignore failure to move the image file.
2265 // If we decide to require the app image, or the app image being moved correctly,
2266 // then change accordingly.
2267 constexpr bool kIgnoreAppImageFailure = true;
2268
2269 if (!a_image_path.empty()) {
2270 if (!move_ab_path(b_image_path, a_image_path)) {
2271 unlink(a_image_path.c_str());
2272 if (!kIgnoreAppImageFailure) {
2273 success = false;
2274 }
2275 }
2276 }
2277 } else {
2278 // Cleanup: delete B image, ignore errors.
2279 unlink(b_image_path.c_str());
2280 success = false;
2281 }
2282 } else {
2283 // Cleanup: delete B image, ignore errors.
2284 unlink(b_vdex_path.c_str());
2285 unlink(b_image_path.c_str());
2286 success = false;
2287 }
2288 return success;
2289}
2290
2291bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2292 // Delete the oat/odex file.
2293 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002294 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002295 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002296 return false;
2297 }
2298
2299 // In case of a permission failure report the issue. Otherwise just print a warning.
2300 auto unlink_and_check = [](const char* path) -> bool {
2301 int result = unlink(path);
2302 if (result != 0) {
2303 if (errno == EACCES || errno == EPERM) {
2304 PLOG(ERROR) << "Could not unlink " << path;
2305 return false;
2306 }
2307 PLOG(WARNING) << "Could not unlink " << path;
2308 }
2309 return true;
2310 };
2311
2312 // Delete the oat/odex file.
2313 bool return_value_oat = unlink_and_check(out_path);
2314
2315 // Derive and delete the app image.
2316 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2317
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002318 // Derive and delete the vdex file.
2319 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2320
Jeff Sharkey90aff262016-12-12 14:28:24 -07002321 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002322 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002323}
2324
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002325static bool is_absolute_path(const std::string& path) {
2326 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2327 LOG(ERROR) << "Invalid absolute path " << path;
2328 return false;
2329 } else {
2330 return true;
2331 }
2332}
2333
2334static bool is_valid_instruction_set(const std::string& instruction_set) {
2335 // TODO: add explicit whitelisting of instruction sets
2336 if (instruction_set.find('/') != std::string::npos) {
2337 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2338 return false;
2339 } else {
2340 return true;
2341 }
2342}
2343
2344bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2345 const char *apk_path, const char *instruction_set) {
2346 std::string oat_dir_ = oat_dir;
2347 std::string apk_path_ = apk_path;
2348 std::string instruction_set_ = instruction_set;
2349
2350 if (!is_absolute_path(oat_dir_)) return false;
2351 if (!is_absolute_path(apk_path_)) return false;
2352 if (!is_valid_instruction_set(instruction_set_)) return false;
2353
2354 std::string::size_type end = apk_path_.rfind('.');
2355 std::string::size_type start = apk_path_.rfind('/', end);
2356 if (end == std::string::npos || start == std::string::npos) {
2357 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2358 return false;
2359 }
2360
2361 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2362 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2363 const char* res = res_.c_str();
2364 if (strlen(res) >= PKG_PATH_MAX) {
2365 LOG(ERROR) << "Result too large";
2366 return false;
2367 } else {
2368 strlcpy(path, res, PKG_PATH_MAX);
2369 return true;
2370 }
2371}
2372
2373bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2374 const char *instruction_set) {
2375 std::string apk_path_ = apk_path;
2376 std::string instruction_set_ = instruction_set;
2377
2378 if (!is_absolute_path(apk_path_)) return false;
2379 if (!is_valid_instruction_set(instruction_set_)) return false;
2380
2381 std::string::size_type end = apk_path_.rfind('.');
2382 std::string::size_type start = apk_path_.rfind('/', end);
2383 if (end == std::string::npos || start == std::string::npos) {
2384 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2385 return false;
2386 }
2387
2388 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2389 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2390}
2391
2392bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2393 const char *instruction_set) {
2394 std::string src_ = src;
2395 std::string instruction_set_ = instruction_set;
2396
2397 if (!is_absolute_path(src_)) return false;
2398 if (!is_valid_instruction_set(instruction_set_)) return false;
2399
2400 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2401 if (*it == '/') {
2402 *it = '@';
2403 }
2404 }
2405
2406 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2407 + DALVIK_CACHE_POSTFIX;
2408 const char* res = res_.c_str();
2409 if (strlen(res) >= PKG_PATH_MAX) {
2410 LOG(ERROR) << "Result too large";
2411 return false;
2412 } else {
2413 strlcpy(path, res, PKG_PATH_MAX);
2414 return true;
2415 }
2416}
2417
Calin Juravle59f7ab82018-04-27 17:50:23 -07002418bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2419 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002420 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2421 for (const std::string& elem : classpaths_elems) {
2422 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2423 if (fd < 0) {
2424 PLOG(ERROR) << "Could not open classpath elem " << elem;
2425 return false;
2426 } else {
2427 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002428 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002429 }
2430 }
2431 return true;
2432}
2433
2434static bool create_app_profile_snapshot(int32_t app_id,
2435 const std::string& package_name,
2436 const std::string& profile_name,
2437 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002438 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2439
Calin Juravle824a64d2018-01-18 20:23:17 -08002440 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002441 if (snapshot_fd < 0) {
2442 return false;
2443 }
2444
2445 std::vector<unique_fd> profiles_fd;
2446 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002447 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2448 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002449 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2450 return false;
2451 }
2452
2453 profiles_fd.push_back(std::move(reference_profile_fd));
2454
Calin Juravle0d0a4922018-01-23 19:54:11 -08002455 // Open the class paths elements. These will be used to filter out profile data that does
2456 // not belong to the classpath during merge.
2457 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002458 std::vector<std::string> dex_locations;
2459 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002460 return false;
2461 }
2462
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002463 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002464 // This is specifically a snapshot for an app, so don't use boot image profiles.
2465 args.SetupMerge(profiles_fd,
2466 snapshot_fd,
2467 apk_fds,
2468 dex_locations,
2469 /* for_snapshot= */ true,
2470 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002471 pid_t pid = fork();
2472 if (pid == 0) {
2473 /* child -- drop privileges before continuing */
2474 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002475 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002476 }
2477
2478 /* parent */
2479 int return_code = wait_child(pid);
2480 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002481 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002482 return false;
2483 }
2484
Calin Juravle78728f32019-11-08 17:55:46 -08002485 // Verify that profman finished successfully.
2486 int profman_code = WEXITSTATUS(return_code);
2487 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2488 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2489 << ":" << profman_code;
2490 return false;
2491 }
Calin Juravle29591732017-11-20 17:46:19 -08002492 return true;
2493}
2494
Calin Juravle0d0a4922018-01-23 19:54:11 -08002495static bool create_boot_image_profile_snapshot(const std::string& package_name,
2496 const std::string& profile_name,
2497 const std::string& classpath) {
2498 // The reference profile directory for the android package might not be prepared. Do it now.
2499 const std::string ref_profile_dir =
2500 create_primary_reference_profile_package_dir_path(package_name);
2501 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2502 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2503 return false;
2504 }
2505
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002506 // Return false for empty class path since it may otherwise return true below if profiles is
2507 // empty.
2508 if (classpath.empty()) {
2509 PLOG(ERROR) << "Class path is empty";
2510 return false;
2511 }
2512
Calin Juravle0d0a4922018-01-23 19:54:11 -08002513 // Open and create the snapshot profile.
2514 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2515
2516 // Collect all non empty profiles.
2517 // The collection will traverse all applications profiles and find the non empty files.
2518 // This has the potential of inspecting a large number of files and directories (depending
2519 // on the number of applications and users). So there is a slight increase in the chance
2520 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2521 // fail the snapshot and aggregate whatever profile we could open.
2522 //
2523 // The profile snapshot is a best effort based on available data it's ok if some data
2524 // from some apps is missing. It will be counter productive for the snapshot to fail
2525 // because we could not open or read some of the files.
2526 std::vector<std::string> profiles;
2527 if (!collect_profiles(&profiles)) {
2528 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2529 }
2530
2531 // If we have no profiles return early.
2532 if (profiles.empty()) {
2533 return true;
2534 }
2535
2536 // Open the classpath elements. These will be used to filter out profile data that does
2537 // not belong to the classpath during merge.
2538 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002539 std::vector<std::string> dex_locations;
2540 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002541 return false;
2542 }
2543
2544 // If we could not open any files from the classpath return an error.
2545 if (apk_fds.empty()) {
2546 LOG(ERROR) << "Could not open any of the classpath elements.";
2547 return false;
2548 }
2549
2550 // Aggregate the profiles in batches of kAggregationBatchSize.
2551 // We do this to avoid opening a huge a amount of files.
2552 static constexpr size_t kAggregationBatchSize = 10;
2553
Calin Juravle0d0a4922018-01-23 19:54:11 -08002554 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002555 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002556 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2557 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2558 if (fd.get() >= 0) {
2559 profiles_fd.push_back(std::move(fd));
2560 }
2561 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002562
2563 // We aggregate (read & write) into the same fd multiple times in a row.
2564 // We need to reset the cursor every time to ensure we read the whole file every time.
2565 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2566 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2567 return false;
2568 }
2569
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002570 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002571 args.SetupMerge(profiles_fd,
2572 snapshot_fd,
2573 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002574 dex_locations,
2575 /*for_snapshot=*/true,
2576 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002577 pid_t pid = fork();
2578 if (pid == 0) {
2579 /* child -- drop privileges before continuing */
2580 drop_capabilities(AID_SYSTEM);
2581
Calin Juravle59f7ab82018-04-27 17:50:23 -07002582 // The introduction of new access flags into boot jars causes them to
2583 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002584 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002585 }
2586
2587 /* parent */
2588 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002589
Calin Juravle0d0a4922018-01-23 19:54:11 -08002590 if (!WIFEXITED(return_code)) {
2591 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2592 return false;
2593 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002594
2595 // Verify that profman finished successfully.
2596 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002597 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2598 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2599 << ":" << profman_code;
2600 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002601 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002602 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002603
Calin Juravle0d0a4922018-01-23 19:54:11 -08002604 return true;
2605}
2606
2607bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2608 const std::string& profile_name, const std::string& classpath) {
2609 if (app_id == -1) {
2610 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2611 } else {
2612 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2613 }
2614}
2615
Calin Juravlec3b049e2018-01-18 22:32:58 -08002616bool prepare_app_profile(const std::string& package_name,
2617 userid_t user_id,
2618 appid_t app_id,
2619 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002620 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002621 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002622 // Prepare the current profile.
2623 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2624 /*is_secondary_dex*/ false);
2625 uid_t uid = multiuser_get_uid(user_id, app_id);
2626 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2627 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2628 return false;
2629 }
2630
2631 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002632 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002633 return true;
2634 }
2635
2636 // We have a dex metdata. Merge the profile into the reference profile.
2637 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2638 /*read_write*/ true, /*is_secondary_dex*/ false);
2639 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2640 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002641 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2642 if (apk_fd < 0) {
2643 PLOG(ERROR) << "Could not open code path " << code_path;
2644 return false;
2645 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002646
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002647 RunProfman args;
2648 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2649 std::move(ref_profile_fd),
2650 std::move(apk_fd),
2651 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002652 pid_t pid = fork();
2653 if (pid == 0) {
2654 /* child -- drop privileges before continuing */
2655 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2656 drop_capabilities(app_shared_gid);
2657
Calin Juravlef63d4792018-01-30 17:43:34 +00002658 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002659 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002660 }
2661
2662 /* parent */
2663 int return_code = wait_child(pid);
2664 if (!WIFEXITED(return_code)) {
2665 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2666 return false;
2667 }
2668 return true;
2669}
2670
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002671} // namespace installd
2672} // namespace android