blob: 5cf5b0581231e780917bd31f1e99ff595afbdbd8 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000048#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080052#include "dexopt_return_codes.h"
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"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070056#include "utils.h"
57
Victor Hsieh76f19ba2020-08-10 14:37:26 -070058using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070059using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070060using android::base::GetBoolProperty;
61using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000062using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010063using android::base::ReadFully;
64using android::base::StringPrintf;
65using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080066using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067
68namespace android {
69namespace installd {
70
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070071// Should minidebug info be included in compiled artifacts? Even if this value is
72// "true," usage might still be conditional to other constraints, e.g., system
73// property overrides.
74static constexpr bool kEnableMinidebugInfo = true;
75
76static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
77static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
78static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080079static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070080
Andreas Gampefa2dadd2018-02-28 19:52:47 -080081
Calin Juravle114f0812017-03-08 19:05:07 -080082// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
83struct FreeDelete {
84 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
85 void operator()(const void* ptr) const {
86 free(const_cast<void*>(ptr));
87 }
88};
89
90// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
91template <typename T>
92using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
93
Calin Juravle1a0af3b2017-03-09 14:33:33 -080094static unique_fd invalid_unique_fd() {
95 return unique_fd(-1);
96}
97
Andreas Gampe6a9cf722017-07-24 16:49:10 -070098static bool is_debug_runtime() {
99 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
100}
101
David Sehra3b5ab62017-10-25 14:27:29 -0700102static bool is_debuggable_build() {
103 return android::base::GetBoolProperty("ro.debuggable", false);
104}
105
Jeff Sharkey90aff262016-12-12 14:28:24 -0700106static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800107 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700108 if (ufd.get() < 0) {
109 if (errno != ENOENT) {
110 PLOG(WARNING) << "Could not open profile " << profile;
111 return false;
112 } else {
113 // Nothing to clear. That's ok.
114 return true;
115 }
116 }
117
118 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
119 if (errno != EWOULDBLOCK) {
120 PLOG(WARNING) << "Error locking profile " << profile;
121 }
122 // This implies that the app owning this profile is running
123 // (and has acquired the lock).
124 //
125 // If we can't acquire the lock bail out since clearing is useless anyway
126 // (the app will write again to the profile).
127 //
128 // Note:
129 // This does not impact the this is not an issue for the profiling correctness.
130 // In case this is needed because of an app upgrade, profiles will still be
131 // eventually cleared by the app itself due to checksum mismatch.
132 // If this is needed because profman advised, then keeping the data around
133 // until the next run is again not an issue.
134 //
135 // If the app attempts to acquire a lock while we've held one here,
136 // it will simply skip the current write cycle.
137 return false;
138 }
139
140 bool truncated = ftruncate(ufd.get(), 0) == 0;
141 if (!truncated) {
142 PLOG(WARNING) << "Could not truncate " << profile;
143 }
144 if (flock(ufd.get(), LOCK_UN) != 0) {
145 PLOG(WARNING) << "Error unlocking profile " << profile;
146 }
147 return truncated;
148}
149
Calin Juravle114f0812017-03-08 19:05:07 -0800150// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800151// The location is the profile name for primary apks or the dex path for secondary dex files.
152static bool clear_reference_profile(const std::string& package_name, const std::string& location,
153 bool is_secondary_dex) {
154 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700155}
156
Calin Juravle114f0812017-03-08 19:05:07 -0800157// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800158// The location is the profile name for primary apks or the dex path for secondary dex files.
159static bool clear_current_profile(const std::string& package_name, const std::string& location,
160 userid_t user, bool is_secondary_dex) {
161 return clear_profile(create_current_profile_path(user, package_name, location,
162 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700163}
164
Calin Juravle114f0812017-03-08 19:05:07 -0800165// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800166// The location is the profile name for primary apks or the dex path for secondary dex files.
167bool clear_primary_reference_profile(const std::string& package_name,
168 const std::string& location) {
169 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800170}
171
172// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800173// The location is the profile name for primary apks or the dex path for secondary dex files.
174bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700175 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800176 // 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 -0700177 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
178 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800179 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700180 }
181 return success;
182}
183
Calin Juravle114f0812017-03-08 19:05:07 -0800184// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800185bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
186 userid_t user) {
187 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800188}
189
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700190static std::vector<std::string> SplitBySpaces(const std::string& str) {
191 if (str.empty()) {
192 return {};
193 }
194 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700195}
196
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800197// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
198// need to be performed between the fork and exec.
199class ExecVHelper {
200 public:
201 // Store a placeholder for the binary name.
202 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800203
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800204 void PrepareArgs(const std::string& bin) {
205 CHECK(!args_.empty());
206 CHECK(args_[0].empty());
207 args_[0] = bin;
208 // Write char* into array.
209 for (const std::string& arg : args_) {
210 argv_.push_back(arg.c_str());
211 }
212 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800213 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800214
215 [[ noreturn ]]
216 void Exec(int exit_code) {
217 execv(argv_[0], (char * const *)&argv_[0]);
218 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
219 exit(exit_code);
220 }
221
222 // Add an arg if it's not empty.
223 void AddArg(const std::string& arg) {
224 if (!arg.empty()) {
225 args_.push_back(arg);
226 }
227 }
228
229 // Add a runtime arg if it's not empty.
230 void AddRuntimeArg(const std::string& arg) {
231 if (!arg.empty()) {
232 args_.push_back("--runtime-arg");
233 args_.push_back(arg);
234 }
235 }
236
237 protected:
238 // Holder arrays for backing arg storage.
239 std::vector<std::string> args_;
240
241 // Argument poiners.
242 std::vector<const char*> argv_;
243};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700244
245static std::string MapPropertyToArg(const std::string& property,
246 const std::string& format,
247 const std::string& default_value = "") {
248 std::string prop = GetProperty(property, default_value);
249 if (!prop.empty()) {
250 return StringPrintf(format.c_str(), prop.c_str());
251 }
252 return "";
253}
254
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700255static std::string MapPropertyToArgWithBackup(const std::string& property,
256 const std::string& backupProperty,
257 const std::string& format,
258 const std::string& default_value = "") {
259 std::string value = GetProperty(property, default_value);
260 if (!value.empty()) {
261 return StringPrintf(format.c_str(), value.c_str());
262 }
263 return MapPropertyToArg(backupProperty, format, default_value);
264}
265
Calin Juravlef74a7372019-02-28 20:29:41 -0800266// Determines which binary we should use for execution (the debug or non-debug version).
267// e.g. dex2oatd vs dex2oat
268static const char* select_execution_binary(const char* binary, const char* debug_binary,
269 bool background_job_compile) {
270 return select_execution_binary(
271 binary,
272 debug_binary,
273 background_job_compile,
274 is_debug_runtime(),
275 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
276 is_debuggable_build());
277}
278
279// Determines which binary we should use for execution (the debug or non-debug version).
280// e.g. dex2oatd vs dex2oat
281// This is convenient method which is much easier to test because it doesn't read
282// system properties.
283const char* select_execution_binary(
284 const char* binary,
285 const char* debug_binary,
286 bool background_job_compile,
287 bool is_debug_runtime,
288 bool is_release,
289 bool is_debuggable_build) {
290 // Do not use debug binaries for release candidates (to give more soak time).
291 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
292
293 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
294 // the file is present (it may not be on images with very little space available).
295 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
296
297 return useDebug ? debug_binary : binary;
298}
299
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000300// Namespace for Android Runtime flags applied during boot time.
301static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
302// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000303static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
304// Location of the JIT Zygote image.
305static const char* kJitZygoteImage =
306 "boot.art:/nonx/boot-framework.art!/system/etc/boot-image.prof";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000307
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700308// Phenotype property name for enabling profiling the boot class path.
309static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
310
Calin Juravlef85ddb92020-05-01 14:05:40 -0700311static bool IsBootClassPathProfilingEnable() {
312 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
313 profile_boot_class_path =
314 server_configurable_flags::GetServerConfigurableFlag(
315 RUNTIME_NATIVE_BOOT_NAMESPACE,
316 PROFILE_BOOT_CLASS_PATH,
317 /*default_value=*/ profile_boot_class_path);
318 return profile_boot_class_path == "true";
319}
320
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800321class RunDex2Oat : public ExecVHelper {
322 public:
323 RunDex2Oat(int zip_fd,
324 int oat_fd,
325 int input_vdex_fd,
326 int output_vdex_fd,
327 int image_fd,
328 const char* input_file_name,
329 const char* output_file_name,
330 int swap_fd,
331 const char* instruction_set,
332 const char* compiler_filter,
333 bool debuggable,
334 bool post_bootcomplete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700335 bool for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800336 bool background_job_compile,
337 int profile_fd,
338 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000339 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800340 int target_sdk_version,
341 bool enable_hidden_api_checks,
342 bool generate_compact_dex,
343 int dex_metadata_fd,
Victor Hsieh8948a862020-08-07 11:30:55 -0700344 bool use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800345 const char* compilation_reason) {
346 // Get the relative path to the input file.
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700347 std::string input_basename = Basename(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
350 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700351
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700352 std::string threads_format = "-j%s";
353 std::string dex2oat_threads_arg = post_bootcomplete
354 ? (for_restore
355 ? MapPropertyToArgWithBackup(
356 "dalvik.vm.restore-dex2oat-threads",
357 "dalvik.vm.dex2oat-threads",
358 threads_format)
359 : MapPropertyToArg("dalvik.vm.dex2oat-threads", threads_format))
360 : MapPropertyToArg("dalvik.vm.boot-dex2oat-threads", threads_format);
361 std::string cpu_set_format = "--cpu-set=%s";
362 std::string dex2oat_cpu_set_arg = post_bootcomplete
363 ? (for_restore
364 ? MapPropertyToArgWithBackup(
365 "dalvik.vm.restore-dex2oat-cpu-set",
366 "dalvik.vm.dex2oat-cpu-set",
367 cpu_set_format)
368 : MapPropertyToArg("dalvik.vm.dex2oat-cpu-set", cpu_set_format))
369 : MapPropertyToArg("dalvik.vm.boot-dex2oat-cpu-set", cpu_set_format);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700370
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000371 std::string bootclasspath;
372 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
373 if (dex2oat_bootclasspath != nullptr) {
374 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
375 }
376 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
377 // BOOTCLASSPATH.
378
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800379 const std::string dex2oat_isa_features_key =
380 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
381 std::string instruction_set_features_arg =
382 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700383
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800384 const std::string dex2oat_isa_variant_key =
385 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
386 std::string instruction_set_variant_arg =
387 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700388
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800389 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700390
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800391 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
392 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
393 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700394
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800395 // If we are booting without the real /data, don't spend time compiling.
396 std::string vold_decrypt = GetProperty("vold.decrypt", "");
397 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
398 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700399
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100400 std::string updatable_bcp_packages =
401 MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
402 "--updatable-bcp-packages-file=%s");
403 if (updatable_bcp_packages.empty()) {
404 // Make dex2oat fail by providing non-existent file name.
405 updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
406 }
407
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800408 std::string resolve_startup_string_arg =
409 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
410 "--resolve-startup-const-strings=%s");
411 if (resolve_startup_string_arg.empty()) {
412 // If empty, fall back to system property.
413 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800414 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
415 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800416 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800417
418 const std::string image_block_size_arg =
419 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
420 "--max-image-block-size=%s");
421
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800422 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700423
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800424 std::string image_format_arg;
425 if (image_fd >= 0) {
426 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000427 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000428
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800429 std::string dex2oat_large_app_threshold_arg =
430 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000431
Calin Juravlef74a7372019-02-28 20:29:41 -0800432
David Sehr6df89a62020-04-15 20:43:48 -0700433
434 // Decide whether to use dex2oat64.
435 bool use_dex2oat64 = false;
436 // Check whether the device even supports 64-bit ABIs.
437 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
438 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
439 }
Calin Juravlef74a7372019-02-28 20:29:41 -0800440 const char* dex2oat_bin = select_execution_binary(
David Sehr6df89a62020-04-15 20:43:48 -0700441 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
442 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
443 background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000444
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800445 bool generate_minidebug_info = kEnableMinidebugInfo &&
446 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000447
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000448 std::string boot_image;
Victor Hsieh8948a862020-08-07 11:30:55 -0700449 if (use_jitzygote_image) {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000450 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000451 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000452 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000453 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000454
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800455 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
456 // use arraysize instead.
457 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700458 std::string zip_location_arg = StringPrintf("--zip-location=%s", input_basename.c_str());
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800459 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
460 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
461 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
462 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
463 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
464 std::string dex2oat_compiler_filter_arg;
465 std::string dex2oat_swap_fd;
466 std::string dex2oat_image_fd;
467 std::string target_sdk_version_arg;
468 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000469 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800470 }
471 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000472 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800473 if (class_loader_context != nullptr) {
474 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
475 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000476 if (!class_loader_context_fds.empty()) {
477 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
478 class_loader_context_fds.c_str());
479 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800480 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000481
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800482 if (swap_fd >= 0) {
483 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
484 }
485 if (image_fd >= 0) {
486 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
487 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000488
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800489 // Compute compiler filter.
490 bool have_dex2oat_relocation_skip_flag = false;
491 if (skip_compilation) {
492 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
493 have_dex2oat_relocation_skip_flag = true;
494 } else if (compiler_filter != nullptr) {
495 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
496 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000497
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800498 if (dex2oat_compiler_filter_arg.empty()) {
499 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
500 "--compiler-filter=%s");
501 }
502
503 // Check whether all apps should be compiled debuggable.
504 if (!debuggable) {
505 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
506 }
507 std::string profile_arg;
508 if (profile_fd != -1) {
509 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
510 }
511
512 // Get the directory of the apk to pass as a base classpath directory.
513 std::string base_dir;
514 std::string apk_dir(input_file_name);
515 unsigned long dir_index = apk_dir.rfind('/');
516 bool has_base_dir = dir_index != std::string::npos;
517 if (has_base_dir) {
518 apk_dir = apk_dir.substr(0, dir_index);
519 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
520 }
521
522 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
523
524 std::string compilation_reason_arg = compilation_reason == nullptr
525 ? ""
526 : std::string("--compilation-reason=") + compilation_reason;
527
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700528 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, input_basename.c_str(), output_file_name);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800529
530 // Disable cdex if update input vdex is true since this combination of options is not
531 // supported.
532 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
533
534 AddArg(zip_fd_arg);
535 AddArg(zip_location_arg);
536 AddArg(input_vdex_fd_arg);
537 AddArg(output_vdex_fd_arg);
538 AddArg(oat_fd_arg);
539 AddArg(oat_location_arg);
540 AddArg(instruction_set_arg);
541
542 AddArg(instruction_set_variant_arg);
543 AddArg(instruction_set_features_arg);
544
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000545 AddArg(boot_image);
546
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000547 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800548 AddRuntimeArg(dex2oat_Xms_arg);
549 AddRuntimeArg(dex2oat_Xmx_arg);
550
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100551 AddArg(updatable_bcp_packages);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800552 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800553 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800554 AddArg(dex2oat_compiler_filter_arg);
555 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000556 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800557 AddArg(dex2oat_swap_fd);
558 AddArg(dex2oat_image_fd);
559
560 if (generate_debug_info) {
561 AddArg("--generate-debug-info");
562 }
563 if (debuggable) {
564 AddArg("--debuggable");
565 }
566 AddArg(image_format_arg);
567 AddArg(dex2oat_large_app_threshold_arg);
568
569 if (have_dex2oat_relocation_skip_flag) {
570 AddRuntimeArg(dex2oat_norelocation);
571 }
572 AddArg(profile_arg);
573 AddArg(base_dir);
574 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000575 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800576 if (generate_minidebug_info) {
577 AddArg(kMinidebugDex2oatFlag);
578 }
579 if (disable_cdex) {
580 AddArg(kDisableCompactDexFlag);
581 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000582 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800583 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100584 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800585 }
586
587 if (dex_metadata_fd > -1) {
588 AddArg(dex_metadata_fd_arg);
589 }
590
591 AddArg(compilation_reason_arg);
592
593 // Do not add args after dex2oat_flags, they should override others for debugging.
594 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
595
596 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000597 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800598};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700599
600/*
601 * Whether dexopt should use a swap file when compiling an APK.
602 *
603 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
604 * itself, anyways).
605 *
606 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
607 *
608 * Otherwise, return true if this is a low-mem device.
609 *
610 * Otherwise, return default value.
611 */
612static bool kAlwaysProvideSwapFile = false;
613static bool kDefaultProvideSwapFile = true;
614
615static bool ShouldUseSwapFileForDexopt() {
616 if (kAlwaysProvideSwapFile) {
617 return true;
618 }
619
620 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700621 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
622 if (!dex2oat_prop_buf.empty()) {
623 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700624 }
625
626 // Shortcut for default value. This is an implementation optimization for the process sketched
627 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
628 // as low-mem is never returning false. The compiler will optimize this away if it can.
629 if (kDefaultProvideSwapFile) {
630 return true;
631 }
632
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700633 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700634 return true;
635 }
636
637 // Default value must be false here.
638 return kDefaultProvideSwapFile;
639}
640
Richard Uhler76cc0272016-12-08 10:46:35 +0000641static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700642 if (set_to_bg) {
643 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800644 PLOG(ERROR) << "set_sched_policy failed";
645 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646 }
647 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800648 PLOG(ERROR) << "setpriority failed";
649 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700650 }
651 }
652}
653
Calin Juravle29591732017-11-20 17:46:19 -0800654static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
655 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800656 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800657 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800658 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800659 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800660 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 }
Calin Juravle114f0812017-03-08 19:05:07 -0800662 // Profiles should belong to the app; make sure of that by giving ownership to
663 // the app uid. If we cannot do that, there's no point in returning the fd
664 // since dex2oat/profman will fail with SElinux denials.
665 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000666 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800667 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800668 }
Calin Juravle29591732017-11-20 17:46:19 -0800669 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800670}
671
Calin Juravle29591732017-11-20 17:46:19 -0800672static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800673 // Do not follow symlinks when opening a profile:
674 // - primary profiles should not contain symlinks in their paths
675 // - secondary dex paths should have been already resolved and validated
676 flags |= O_NOFOLLOW;
677
Calin Juravle29591732017-11-20 17:46:19 -0800678 // Check if we need to create the profile
679 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
680 unique_fd fd;
681 if ((flags & O_CREAT) != 0) {
682 fd = create_profile(uid, profile, flags);
683 } else {
684 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
685 }
686
Calin Juravle114f0812017-03-08 19:05:07 -0800687 if (fd.get() < 0) {
688 if (errno != ENOENT) {
689 // Profiles might be missing for various reasons. For example, in a
690 // multi-user environment, the profile directory for one user can be created
691 // after we start a merge. In this case the current profile for that user
692 // will not be found.
693 // Also, the secondary dex profiles might be deleted by the app at any time,
694 // so we can't we need to prepare if they are missing.
695 PLOG(ERROR) << "Failed to open profile " << profile;
696 }
697 return invalid_unique_fd();
698 }
699
Jeff Sharkey90aff262016-12-12 14:28:24 -0700700 return fd;
701}
702
Calin Juravle824a64d2018-01-18 20:23:17 -0800703static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
704 const std::string& location, bool is_secondary_dex) {
705 std::string profile = create_current_profile_path(user, package_name, location,
706 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800707 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800708}
709
Calin Juravle824a64d2018-01-18 20:23:17 -0800710static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
711 const std::string& location, bool read_write, bool is_secondary_dex) {
712 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800713 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
714}
715
716static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800717 const std::string& location) {
718 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800719 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800720}
721
Calin Juravle824a64d2018-01-18 20:23:17 -0800722static void open_profile_files(uid_t uid, const std::string& package_name,
723 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800724 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700725 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800726 *reference_profile_fd = open_reference_profile(uid, package_name, location,
727 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700728
Calin Juravle114f0812017-03-08 19:05:07 -0800729 // For secondary dex files, we don't really need the user but we use it for sanity checks.
730 // Note: the user owning the dex file should be the current user.
731 std::vector<userid_t> users;
732 if (is_secondary_dex){
733 users.push_back(multiuser_get_user_id(uid));
734 } else {
735 users = get_known_users(/*volume_uuid*/ nullptr);
736 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700737 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800738 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
739 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700740 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800741 if (profile_fd.get() >= 0) {
742 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700743 }
744 }
745}
746
Calin Juravle76561322019-11-14 09:08:52 -0800747static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
748static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
749static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
750static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
751static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
752static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
753static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700754
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800755class RunProfman : public ExecVHelper {
756 public:
757 void SetupArgs(const std::vector<unique_fd>& profile_fds,
758 const unique_fd& reference_profile_fd,
759 const std::vector<unique_fd>& apk_fds,
760 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800761 bool copy_and_update,
762 bool for_snapshot,
763 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800764
765 // TODO(calin): Assume for now we run in the bg compile job (which is in
766 // most of the invocation). With the current data flow, is not very easy or
767 // clean to discover this in RunProfman (it will require quite a messy refactoring).
768 const char* profman_bin = select_execution_binary(
769 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700770
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800771 if (copy_and_update) {
772 CHECK_EQ(1u, profile_fds.size());
773 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000774 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800775 if (reference_profile_fd != -1) {
776 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000777 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800778
779 for (const unique_fd& fd : profile_fds) {
780 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
781 }
782
783 for (const unique_fd& fd : apk_fds) {
784 AddArg("--apk-fd=" + std::to_string(fd.get()));
785 }
786
787 for (const std::string& dex_location : dex_locations) {
788 AddArg("--dex-location=" + dex_location);
789 }
790
791 if (copy_and_update) {
792 AddArg("--copy-and-update-profile-key");
793 }
794
Calin Juravle78728f32019-11-08 17:55:46 -0800795 if (for_snapshot) {
796 AddArg("--force-merge");
797 }
798
799 if (for_boot_image) {
800 AddArg("--boot-image-merge");
801 }
802
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800803 // Do not add after dex2oat_flags, they should override others for debugging.
804 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800805 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800807 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
808 const unique_fd& reference_profile_fd,
809 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800810 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
811 bool for_snapshot = false,
812 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800813 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800814 reference_profile_fd,
815 apk_fds,
816 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800817 /*copy_and_update=*/ false,
818 for_snapshot,
819 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800820 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800822 void SetupCopyAndUpdate(unique_fd&& profile_fd,
823 unique_fd&& reference_profile_fd,
824 unique_fd&& apk_fd,
825 const std::string& dex_location) {
826 // The fds need to stay open longer than the scope of the function, so put them into a local
827 // variable vector.
828 profiles_fd_.push_back(std::move(profile_fd));
829 apk_fds_.push_back(std::move(apk_fd));
830 reference_profile_fd_ = std::move(reference_profile_fd);
831 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800832 SetupArgs(profiles_fd_,
833 reference_profile_fd_,
834 apk_fds_,
835 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800836 /*copy_and_update=*/true,
837 /*for_snapshot*/false,
838 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800839 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000840
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800841 void SetupDump(const std::vector<unique_fd>& profiles_fd,
842 const unique_fd& reference_profile_fd,
843 const std::vector<std::string>& dex_locations,
844 const std::vector<unique_fd>& apk_fds,
845 const unique_fd& output_fd) {
846 AddArg("--dump-only");
847 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800848 SetupArgs(profiles_fd,
849 reference_profile_fd,
850 apk_fds,
851 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800852 /*copy_and_update=*/false,
853 /*for_snapshot*/false,
854 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800855 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000856
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800857 void Exec() {
858 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
859 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000860
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800861 private:
862 unique_fd reference_profile_fd_;
863 std::vector<unique_fd> profiles_fd_;
864 std::vector<unique_fd> apk_fds_;
865};
Mathieu Chartier31636522018-11-09 23:53:07 +0000866
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800867
Calin Juravlef63d4792018-01-30 17:43:34 +0000868
Jeff Sharkey90aff262016-12-12 14:28:24 -0700869// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800870// The location is the package name for primary apks or the dex path for secondary dex files.
871// Returns true if there is enough information in the current profiles that makes it
872// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873// If the return value is true all the current profiles would have been merged into
874// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800875static bool analyze_profiles(uid_t uid, const std::string& package_name,
876 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800877 std::vector<unique_fd> profiles_fd;
878 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800879 open_profile_files(uid, package_name, location, is_secondary_dex,
880 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800881 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 // Skip profile guided compilation because no profiles were found.
883 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 return false;
885 }
886
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800887 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700888 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
889 const std::vector<std::string>& dex_locations = std::vector<std::string>();
890 profman_merge.SetupMerge(
891 profiles_fd,
892 reference_profile_fd,
893 apk_fds,
894 dex_locations,
895 /* for_snapshot= */ false,
896 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700897 pid_t pid = fork();
898 if (pid == 0) {
899 /* child -- drop privileges before continuing */
900 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800901 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 }
903 /* parent */
904 int return_code = wait_child(pid);
905 bool need_to_compile = false;
906 bool should_clear_current_profiles = false;
907 bool should_clear_reference_profile = false;
908 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800909 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910 } else {
911 return_code = WEXITSTATUS(return_code);
912 switch (return_code) {
913 case PROFMAN_BIN_RETURN_CODE_COMPILE:
914 need_to_compile = true;
915 should_clear_current_profiles = true;
916 should_clear_reference_profile = false;
917 break;
918 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
919 need_to_compile = false;
920 should_clear_current_profiles = false;
921 should_clear_reference_profile = false;
922 break;
923 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800924 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700925 need_to_compile = false;
926 should_clear_current_profiles = true;
927 should_clear_reference_profile = true;
928 break;
929 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
930 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
931 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800932 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 need_to_compile = false;
934 should_clear_current_profiles = false;
935 should_clear_reference_profile = false;
936 break;
Calin Juravle76561322019-11-14 09:08:52 -0800937 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
938 need_to_compile = false;
939 should_clear_current_profiles = true;
940 should_clear_reference_profile = true;
941 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700942 default:
943 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800944 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800945 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700946 need_to_compile = false;
947 should_clear_current_profiles = true;
948 should_clear_reference_profile = true;
949 break;
950 }
951 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800952
Jeff Sharkey90aff262016-12-12 14:28:24 -0700953 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800954 if (is_secondary_dex) {
955 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800956 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
957 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800958 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800959 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800960 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700961 }
962 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800963 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964 }
965 return need_to_compile;
966}
967
Calin Juravle114f0812017-03-08 19:05:07 -0800968// Decides if profile guided compilation is needed or not based on existing profiles.
969// The analysis is done for the primary apks of the given package.
970// Returns true if there is enough information in the current profiles that makes it
971// worth to recompile the package.
972// If the return value is true all the current profiles would have been merged into
973// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800974bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
975 const std::string& profile_name) {
976 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800977}
978
Calin Juravle408cd4a2018-01-20 23:34:18 -0800979bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
980 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800981 std::vector<unique_fd> profile_fds;
982 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800983 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
984 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700985
Calin Juravle408cd4a2018-01-20 23:34:18 -0800986 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800987 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800989 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700990 const bool has_profiles = !profile_fds.empty();
991
992 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800993 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700994 return false;
995 }
996
Calin Juravle114f0812017-03-08 19:05:07 -0800997 unique_fd output_fd(open(out_file_name.c_str(),
998 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700999 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -08001000 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001001 return false;
1002 }
Calin Juravle408cd4a2018-01-20 23:34:18 -08001003
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001005 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -08001006 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
1007 if (apk_fd == -1) {
1008 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
1009 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001010 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -07001011 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -08001012 apk_fds.push_back(std::move(apk_fd));
1013
Jeff Sharkey90aff262016-12-12 14:28:24 -07001014
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001015 RunProfman profman_dump;
1016 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001017 pid_t pid = fork();
1018 if (pid == 0) {
1019 /* child -- drop privileges before continuing */
1020 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001021 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001022 }
1023 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001024 int return_code = wait_child(pid);
1025 if (!WIFEXITED(return_code)) {
1026 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1027 << return_code;
1028 return false;
1029 }
1030 return true;
1031}
1032
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001033bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001034 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001035 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1036 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001037 package_name,
1038 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001039 /*read_write*/ true,
1040 /*secondary*/ false));
1041 if (in_fd.get() < 0) {
1042 PLOG(WARNING) << "Could not open profile " << system_profile;
1043 return false;
1044 }
1045 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001046 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001047 return false;
1048 }
1049
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001050 // As a security measure we want to write the profile information with the reduced capabilities
1051 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001052 pid_t pid = fork();
1053 if (pid == 0) {
1054 /* child -- drop privileges before continuing */
1055 drop_capabilities(packageUid);
1056
1057 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1058 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001059 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001060 }
1061 // This implies that the app owning this profile is running
1062 // (and has acquired the lock).
1063 //
1064 // The app never acquires the lock for the reference profiles of primary apks.
1065 // Only dex2oat from installd will do that. Since installd is single threaded
1066 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001067 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001068 return false;
1069 }
1070
1071 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1072 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001073 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001074 }
1075
1076 // Copy over data.
1077 static constexpr size_t kBufferSize = 4 * 1024;
1078 char buffer[kBufferSize];
1079 while (true) {
1080 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1081 if (bytes == 0) {
1082 break;
1083 }
1084 write(out_fd.get(), buffer, bytes);
1085 }
1086 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001087 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001088 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001089 // Use _exit since we don't want to run the global destructors in the child.
1090 // b/62597429
1091 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001092 }
1093 /* parent */
1094 int return_code = wait_child(pid);
1095 return return_code == 0;
1096}
1097
Jeff Sharkey90aff262016-12-12 14:28:24 -07001098static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1099 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1100 if (EndsWith(oat_path, ".dex")) {
1101 std::string new_path = oat_path;
1102 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001103 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104 return new_path;
1105 }
1106
1107 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1108 // case (where the base name will have an extension for the B artifact).
1109 size_t odex_pos = oat_path.rfind(".odex");
1110 if (odex_pos != std::string::npos) {
1111 std::string new_path = oat_path;
1112 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1113 CHECK_NE(new_path.find(new_ext), std::string::npos);
1114 return new_path;
1115 }
1116
1117 // Don't know how to handle this.
1118 return "";
1119}
1120
1121// Translate the given oat path to an art (app image) path. An empty string
1122// denotes an error.
1123static std::string create_image_filename(const std::string& oat_path) {
1124 return replace_file_extension(oat_path, ".art");
1125}
1126
1127// Translate the given oat path to a vdex path. An empty string denotes an error.
1128static std::string create_vdex_filename(const std::string& oat_path) {
1129 return replace_file_extension(oat_path, ".vdex");
1130}
1131
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132static int open_output_file(const char* file_name, bool recreate, int permissions) {
1133 int flags = O_RDWR | O_CREAT;
1134 if (recreate) {
1135 if (unlink(file_name) < 0) {
1136 if (errno != ENOENT) {
1137 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1138 }
1139 }
1140 flags |= O_EXCL;
1141 }
1142 return open(file_name, flags, permissions);
1143}
1144
Calin Juravle2289c0a2017-02-15 12:44:14 -08001145static bool set_permissions_and_ownership(
1146 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1147 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1148 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001149 if (fchmod(fd,
1150 S_IRUSR|S_IWUSR|S_IRGRP |
1151 (is_public ? S_IROTH : 0)) < 0) {
1152 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1153 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001154 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001155 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1156 return false;
1157 }
1158 return true;
1159}
1160
1161static bool IsOutputDalvikCache(const char* oat_dir) {
1162 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1163 // into '!'. Play it safe by handling it both.
1164 // TODO: ensure we never get null.
1165 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1166 return oat_dir == nullptr || oat_dir[0] == '!';
1167}
1168
Calin Juravled23dee72017-07-06 16:29:11 -07001169// Best-effort check whether we can fit the the path into our buffers.
1170// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1171// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1172// extension to the cache path (5 bytes).
1173// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1174static bool validate_dex_path_size(const std::string& dex_path) {
1175 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1176 LOG(ERROR) << "dex_path too long: " << dex_path;
1177 return false;
1178 }
1179 return true;
1180}
1181
Jeff Sharkey90aff262016-12-12 14:28:24 -07001182static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001183 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001184 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001185 return false;
1186 }
1187
1188 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001189 // Oat dirs for secondary dex files are already validated.
1190 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001191 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1192 return false;
1193 }
1194 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1195 return false;
1196 }
1197 } else {
1198 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1199 return false;
1200 }
1201 }
1202 return true;
1203}
1204
1205// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1206// on destruction. It will also run the given cleanup (unless told not to) after closing.
1207//
1208// Usage example:
1209//
Calin Juravle7a570e82017-01-14 16:23:30 -08001210// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001211// [name]() {
1212// unlink(name.c_str());
1213// });
1214// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1215// wrapper if captured as a reference.
1216//
1217// if (file.get() == -1) {
1218// // Error opening...
1219// }
1220//
1221// ...
1222// if (error) {
1223// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1224// // and delete the file (after the fd is closed).
1225// return -1;
1226// }
1227//
1228// (Success case)
1229// file.SetCleanup(false);
1230// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1231// // (leaving the file around; after the fd is closed).
1232//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001233class Dex2oatFileWrapper {
1234 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001235 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001236 }
1237
Calin Juravle7a570e82017-01-14 16:23:30 -08001238 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1239 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1240
1241 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1242 value_ = other.value_;
1243 cleanup_ = other.cleanup_;
1244 do_cleanup_ = other.do_cleanup_;
1245 auto_close_ = other.auto_close_;
1246 other.release();
1247 }
1248
1249 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1250 value_ = other.value_;
1251 cleanup_ = other.cleanup_;
1252 do_cleanup_ = other.do_cleanup_;
1253 auto_close_ = other.auto_close_;
1254 other.release();
1255 return *this;
1256 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001257
1258 ~Dex2oatFileWrapper() {
1259 reset(-1);
1260 }
1261
1262 int get() {
1263 return value_;
1264 }
1265
1266 void SetCleanup(bool cleanup) {
1267 do_cleanup_ = cleanup;
1268 }
1269
1270 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001271 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001272 close(value_);
1273 }
1274 if (do_cleanup_ && cleanup_ != nullptr) {
1275 cleanup_();
1276 }
1277
1278 value_ = new_value;
1279 }
1280
Calin Juravle7a570e82017-01-14 16:23:30 -08001281 void reset(int new_value, std::function<void ()> new_cleanup) {
1282 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001283 close(value_);
1284 }
1285 if (do_cleanup_ && cleanup_ != nullptr) {
1286 cleanup_();
1287 }
1288
1289 value_ = new_value;
1290 cleanup_ = new_cleanup;
1291 }
1292
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 void DisableAutoClose() {
1294 auto_close_ = false;
1295 }
1296
Jeff Sharkey90aff262016-12-12 14:28:24 -07001297 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001298 void release() {
1299 value_ = -1;
1300 do_cleanup_ = false;
1301 cleanup_ = nullptr;
1302 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001303 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001304 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001305 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001306 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001307};
1308
Calin Juravle7a570e82017-01-14 16:23:30 -08001309// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001310Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1311 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001312
Calin Juravle7a570e82017-01-14 16:23:30 -08001313 const std::string image_path = create_image_filename(out_oat_path);
1314 if (image_path.empty()) {
1315 // Happens when the out_oat_path has an unknown extension.
1316 return Dex2oatFileWrapper();
1317 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001318
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001319 // In case there is a stale image, remove it now. Ignore any error.
1320 unlink(image_path.c_str());
1321
1322 // Not enabled, exit.
1323 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001324 return Dex2oatFileWrapper();
1325 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001326 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1327 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001328 return Dex2oatFileWrapper();
1329 }
1330 // Recreate is true since we do not want to modify a mapped image. If the app is
1331 // already running and we modify the image file, it can cause crashes (b/27493510).
1332 Dex2oatFileWrapper wrapper_fd(
1333 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1334 [image_path]() { unlink(image_path.c_str()); });
1335 if (wrapper_fd.get() < 0) {
1336 // Could not create application image file. Go on since we can compile without it.
1337 LOG(ERROR) << "installd could not create '" << image_path
1338 << "' for image file during dexopt";
1339 // If we have a valid image file path but no image fd, explicitly erase the image file.
1340 if (unlink(image_path.c_str()) < 0) {
1341 if (errno != ENOENT) {
1342 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1343 }
1344 }
1345 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001346 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001347 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1348 wrapper_fd.reset(-1);
1349 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001350
Calin Juravle7a570e82017-01-14 16:23:30 -08001351 return wrapper_fd;
1352}
1353
1354// Creates the dexopt swap file if necessary and return its fd.
1355// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001356unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001357 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001358 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001359 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001360 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001361 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001362 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001363 if (swap_fd.get() < 0) {
1364 // Could not create swap file. Optimistically go on and hope that we can compile
1365 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001366 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001367 } else {
1368 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001369 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001370 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1371 }
1372 }
1373 return swap_fd;
1374}
1375
1376// Opens the reference profiles if needed.
1377// 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 -08001378Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001379 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001380 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001381 // If we are not profile guided compilation, or we are compiling system server
1382 // do not bother to open the profiles; we won't be using them.
1383 if (!profile_guided || (pkgname[0] == '*')) {
1384 return Dex2oatFileWrapper();
1385 }
1386
1387 // If this is a secondary dex path which is public do not open the profile.
1388 // We cannot compile public secondary dex paths with profiles. That's because
1389 // it will expose how the dex files are used by their owner.
1390 //
1391 // Note that the PackageManager is responsible to set the is_public flag for
1392 // primary apks and we do not check it here. In some cases, e.g. when
1393 // compiling with a public profile from the .dm file the PackageManager will
1394 // set is_public toghether with the profile guided compilation.
1395 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001396 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001397 }
Calin Juravle114f0812017-03-08 19:05:07 -08001398
1399 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001400 std::string location;
1401 if (is_secondary_dex) {
1402 location = dex_path;
1403 } else {
1404 if (profile_name == nullptr) {
1405 // This path is taken for system server re-compilation lunched from ZygoteInit.
1406 return Dex2oatFileWrapper();
1407 } else {
1408 location = profile_name;
1409 }
1410 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001411 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1412 is_secondary_dex);
1413 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1414 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001415 };
1416 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001417}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001418
Calin Juravle7a570e82017-01-14 16:23:30 -08001419// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1420// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001421bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001422 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001423 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001424 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1425 CHECK(in_vdex_wrapper_fd != nullptr);
1426 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001427 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1428 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001429 char in_odex_path[PKG_PATH_MAX];
1430 int dexopt_action = abs(dexopt_needed);
1431 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001432 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001433
1434 // Infer the name of the output VDEX.
1435 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1436 if (out_vdex_path_str.empty()) {
1437 return false;
1438 }
1439
1440 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001441 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001442 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1443 const char* path = nullptr;
1444 if (is_odex_location) {
1445 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1446 path = in_odex_path;
1447 } else {
1448 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001449 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001450 }
1451 } else {
1452 path = out_oat_path;
1453 }
1454 in_vdex_path_str = create_vdex_filename(path);
1455 if (in_vdex_path_str.empty()) {
1456 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001457 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001458 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001459 // We can update in place when all these conditions are met:
1460 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1461 // on /system typically cannot be updated in place).
1462 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1463 // cannot be currently used by a running process.
1464 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1465 // different vdex files to operate.
1466 update_vdex_in_place =
1467 (in_vdex_path_str == out_vdex_path_str) &&
1468 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1469 !profile_guided;
1470 if (update_vdex_in_place) {
1471 // Open the file read-write to be able to update it.
1472 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1473 if (in_vdex_wrapper_fd->get() == -1) {
1474 // If we failed to open the file, we cannot update it in place.
1475 update_vdex_in_place = false;
1476 }
1477 } else {
1478 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1479 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001480 }
1481
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001482 // If we are updating the vdex in place, we do not need to recreate a vdex,
1483 // and can use the same existing one.
1484 if (update_vdex_in_place) {
1485 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1486 // have bogus stale vdex files.
1487 out_vdex_wrapper_fd->reset(
1488 in_vdex_wrapper_fd->get(),
1489 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1490 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1491 // wrapper).
1492 in_vdex_wrapper_fd->DisableAutoClose();
1493 } else {
1494 out_vdex_wrapper_fd->reset(
1495 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1496 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1497 if (out_vdex_wrapper_fd->get() < 0) {
1498 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1499 return false;
1500 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001501 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001502 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001503 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001504 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1505 return false;
1506 }
1507
1508 // If we got here we successfully opened the vdex files.
1509 return true;
1510}
1511
1512// Opens the output oat file for the given apk.
1513// If successful it stores the output path into out_oat_path and returns true.
1514Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001515 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1516 char* out_oat_path) {
1517 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001518 return Dex2oatFileWrapper();
1519 }
1520 const std::string out_oat_path_str(out_oat_path);
1521 Dex2oatFileWrapper wrapper_fd(
1522 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1523 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1524 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001525 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001526 } else if (!set_permissions_and_ownership(
1527 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001528 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1529 wrapper_fd.reset(-1);
1530 }
1531 return wrapper_fd;
1532}
1533
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001534// Creates RDONLY fds for oat and vdex files, if exist.
1535// Returns false if it fails to create oat out path for the given apk path.
1536// Note that the method returns true even if the files could not be opened.
1537bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1538 const std::string& oat_dir,
1539 const std::string& instruction_set,
1540 bool is_secondary_dex,
1541 unique_fd* oat_file_fd,
1542 unique_fd* vdex_file_fd) {
1543 char oat_path[PKG_PATH_MAX];
1544 if (!create_oat_out_path(apk_path.c_str(),
1545 instruction_set.c_str(),
1546 oat_dir.c_str(),
1547 is_secondary_dex,
1548 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001549 LOG(ERROR) << "Could not create oat out path for "
1550 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001551 return false;
1552 }
1553 oat_file_fd->reset(open(oat_path, O_RDONLY));
1554 if (oat_file_fd->get() < 0) {
1555 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1556 }
1557
1558 std::string vdex_filename = create_vdex_filename(oat_path);
1559 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1560 if (vdex_file_fd->get() < 0) {
1561 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1562 }
1563
1564 return true;
1565}
1566
Calin Juravle7a570e82017-01-14 16:23:30 -08001567// Updates the access times of out_oat_path based on those from apk_path.
1568void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1569 struct stat input_stat;
1570 memset(&input_stat, 0, sizeof(input_stat));
1571 if (stat(apk_path, &input_stat) != 0) {
1572 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1573 return;
1574 }
1575
1576 struct utimbuf ut;
1577 ut.actime = input_stat.st_atime;
1578 ut.modtime = input_stat.st_mtime;
1579 if (utime(out_oat_path, &ut) != 0) {
1580 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1581 }
1582}
1583
Calin Juravle80a21252017-01-17 14:43:25 -08001584// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001585// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1586// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1587// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001588class RunDexoptAnalyzer : public ExecVHelper {
1589 public:
1590 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001591 int vdex_fd,
1592 int oat_fd,
1593 int zip_fd,
1594 const std::string& instruction_set,
1595 const std::string& compiler_filter,
1596 bool profile_was_updated,
1597 bool downgrade,
1598 const char* class_loader_context,
1599 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001600 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001601
1602 // We always run the analyzer in the background job.
1603 const char* dexoptanalyzer_bin = select_execution_binary(
1604 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001605
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001606 std::string dex_file_arg = "--dex-file=" + dex_file;
1607 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1608 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1609 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1610 std::string isa_arg = "--isa=" + instruction_set;
1611 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1612 const char* assume_profile_changed = "--assume-profile-changed";
1613 const char* downgrade_flag = "--downgrade";
1614 std::string class_loader_context_arg = "--class-loader-context=";
1615 if (class_loader_context != nullptr) {
1616 class_loader_context_arg += class_loader_context;
1617 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001618 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1619 if (!class_loader_context_fds.empty()) {
1620 class_loader_context_fds_arg += class_loader_context_fds;
1621 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001622
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001623 // program name, dex file, isa, filter
1624 AddArg(dex_file_arg);
1625 AddArg(isa_arg);
1626 AddArg(compiler_filter_arg);
1627 if (oat_fd >= 0) {
1628 AddArg(oat_fd_arg);
1629 }
1630 if (vdex_fd >= 0) {
1631 AddArg(vdex_fd_arg);
1632 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001633 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001634 if (profile_was_updated) {
1635 AddArg(assume_profile_changed);
1636 }
1637 if (downgrade) {
1638 AddArg(downgrade_flag);
1639 }
1640 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001641 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001642 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001643 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001644 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001645 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001646
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001647 PrepareArgs(dexoptanalyzer_bin);
1648 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001649
1650 // Dexoptanalyzer mode which flattens the given class loader context and
1651 // prints a list of its dex files in that flattened order.
1652 RunDexoptAnalyzer(const char* class_loader_context) {
1653 CHECK(class_loader_context != nullptr);
1654
1655 // We always run the analyzer in the background job.
1656 const char* dexoptanalyzer_bin = select_execution_binary(
1657 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1658
1659 AddArg("--flatten-class-loader-context");
1660 AddArg(std::string("--class-loader-context=") + class_loader_context);
1661 PrepareArgs(dexoptanalyzer_bin);
1662 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001663};
Calin Juravle80a21252017-01-17 14:43:25 -08001664
1665// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001666static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001667 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001668 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001669 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001670 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001671 return false;
1672 }
Calin Juravle114f0812017-03-08 19:05:07 -08001673 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001674
Calin Juravle80a21252017-01-17 14:43:25 -08001675 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001676 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1677 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001678 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001679 return false;
1680 }
1681
1682 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001683 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001684
Calin Juravle7d765462017-09-04 15:57:10 -07001685 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001686 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001687 return false;
1688 }
1689
1690 return true;
1691}
1692
Calin Juravle7d765462017-09-04 15:57:10 -07001693// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1694// secondary dex files. This return codes are returned by the child process created for
1695// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001696
Andreas Gampe194fe422018-02-28 20:16:19 -08001697enum DexoptAnalyzerSkipCodes {
1698 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001699 // Specific errors are encoded in the name.
1700 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1701 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1702 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1703 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1704 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001705 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001706 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001707};
Calin Juravle7d765462017-09-04 15:57:10 -07001708
1709// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001710// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1711// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001712// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1713// of dexoptanalyzer.
1714static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001715 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001716 // The result values are defined in dexoptanalyzer.
1717 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001718 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001719 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001720 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001721 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001722 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001723 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001724 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001725 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001726 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1727 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001728 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1729 " Expected odex file status for secondary dex %s"
1730 " : dexoptanalyzer result=%d",
1731 dex_path.c_str(),
1732 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001733 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001734 }
1735
1736 // Use a second switch for enum switch-case analysis.
1737 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001738 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001739 // If the file does not exist there's no need for dexopt.
1740 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1741 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001742
1743 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1744 *error_msg = "Dexoptanalyzer path validation failed";
1745 return false;
1746 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1747 *error_msg = "Dexoptanalyzer open zip failed";
1748 return false;
1749 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1750 *error_msg = "Dexoptanalyzer dir preparation failed";
1751 return false;
1752 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1753 *error_msg = "Dexoptanalyzer open output failed";
1754 return false;
1755 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1756 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001757 return false;
1758 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001759
1760 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1761 dex_path.c_str(),
1762 result);
1763 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001764}
1765
Calin Juravle7d765462017-09-04 15:57:10 -07001766enum SecondaryDexAccess {
1767 kSecondaryDexAccessReadOk = 0,
1768 kSecondaryDexAccessDoesNotExist = 1,
1769 kSecondaryDexAccessPermissionError = 2,
1770 kSecondaryDexAccessIOError = 3
1771};
1772
1773static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1774 // Check if the path exists and can be read. If not, there's nothing to do.
1775 if (access(dex_path.c_str(), R_OK) == 0) {
1776 return kSecondaryDexAccessReadOk;
1777 } else {
1778 if (errno == ENOENT) {
1779 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1780 return kSecondaryDexAccessDoesNotExist;
1781 } else {
1782 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1783 return errno == EACCES
1784 ? kSecondaryDexAccessPermissionError
1785 : kSecondaryDexAccessIOError;
1786 }
1787 }
1788}
1789
1790static bool is_file_public(const std::string& filename) {
1791 struct stat file_stat;
1792 if (stat(filename.c_str(), &file_stat) == 0) {
1793 return (file_stat.st_mode & S_IROTH) != 0;
1794 }
1795 return false;
1796}
1797
1798// Create the oat file structure for the secondary dex 'dex_path' and assign
1799// the individual path component to the 'out_' parameters.
1800static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001801 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001802 size_t dirIndex = dex_path.rfind('/');
1803 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001804 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001805 return false;
1806 }
1807 // TODO(calin): we have similar computations in at lest 3 other places
1808 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1809 // using string append.
1810 std::string apk_dir = dex_path.substr(0, dirIndex);
1811 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1812 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1813
1814 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1815 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001816 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001817 return false;
1818 }
1819 return true;
1820}
1821
1822// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1823// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001824static bool validate_dexopt_storage_flags(int dexopt_flags,
1825 int* out_storage_flag,
1826 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001827 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1828 *out_storage_flag = FLAG_STORAGE_CE;
1829 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001830 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001831 return false;
1832 }
1833 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1834 *out_storage_flag = FLAG_STORAGE_DE;
1835 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001836 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001837 return false;
1838 }
1839 return true;
1840}
1841
David Brazdil4f6027a2019-03-19 11:44:21 +00001842static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1843 /* out */ std::vector<std::string>* context_dex_paths) {
1844 if (class_loader_context == nullptr) {
1845 return true;
1846 }
1847
1848 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1849
1850 // Pipe to get the hash result back from our child process.
1851 unique_fd pipe_read, pipe_write;
1852 if (!Pipe(&pipe_read, &pipe_write)) {
1853 PLOG(ERROR) << "Failed to create pipe";
1854 return false;
1855 }
1856
1857 pid_t pid = fork();
1858 if (pid == 0) {
1859 // child -- drop privileges before continuing.
1860 drop_capabilities(uid);
1861
1862 // Route stdout to `pipe_write`
1863 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1864 pipe_write.reset();
1865 pipe_read.reset();
1866
1867 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1868 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1869 }
1870
1871 /* parent */
1872 pipe_write.reset();
1873
1874 std::string str_dex_paths;
1875 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1876 PLOG(ERROR) << "Failed to read from pipe";
1877 return false;
1878 }
1879 pipe_read.reset();
1880
1881 int return_code = wait_child(pid);
1882 if (!WIFEXITED(return_code)) {
1883 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1884 return false;
1885 }
1886
1887 constexpr int kFlattenClassLoaderContextSuccess = 50;
1888 return_code = WEXITSTATUS(return_code);
1889 if (return_code != kFlattenClassLoaderContextSuccess) {
1890 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1891 return false;
1892 }
1893
1894 if (!str_dex_paths.empty()) {
1895 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1896 }
1897 return true;
1898}
1899
1900static int open_dex_paths(const std::vector<std::string>& dex_paths,
1901 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1902 for (const std::string& dex_path : dex_paths) {
1903 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1904 if (zip_fds->back().get() < 0) {
1905 *error_msg = StringPrintf(
1906 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1907 if (errno == ENOENT) {
1908 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1909 } else {
1910 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1911 }
1912 }
1913 }
1914 return 0;
1915}
1916
1917static std::string join_fds(const std::vector<unique_fd>& fds) {
1918 std::stringstream ss;
1919 bool is_first = true;
1920 for (const unique_fd& fd : fds) {
1921 if (is_first) {
1922 is_first = false;
1923 } else {
1924 ss << ":";
1925 }
1926 ss << fd.get();
1927 }
1928 return ss.str();
1929}
1930
Calin Juravlec9eab382017-01-25 01:17:17 -08001931// 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 -08001932// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1933// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001934// When returning true, the output parameters will be:
1935// - is_public_out: whether or not the oat file should not be made public
1936// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1937// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001938static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001939 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001940 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001941 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001942 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001943 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001944 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001945 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1946 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001947 return false;
1948 }
Calin Juravle7d765462017-09-04 15:57:10 -07001949 // Compute the oat dir as it's not easy to extract it from the child computation.
1950 char oat_path[PKG_PATH_MAX];
1951 char oat_dir[PKG_PATH_MAX];
1952 char oat_isa_dir[PKG_PATH_MAX];
1953 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001954 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1955 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001956 return false;
1957 }
Calin Juravle7d765462017-09-04 15:57:10 -07001958 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001959
Calin Juravle80a21252017-01-17 14:43:25 -08001960 pid_t pid = fork();
1961 if (pid == 0) {
1962 // child -- drop privileges before continuing.
1963 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001964
1965 // Validate the path structure.
1966 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1967 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001968 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001969 }
1970
1971 // Open the dex file.
1972 unique_fd zip_fd;
1973 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1974 if (zip_fd.get() < 0) {
1975 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001976 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001977 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001978 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001979 }
1980 }
1981
David Brazdil4f6027a2019-03-19 11:44:21 +00001982 // Open class loader context dex files.
1983 std::vector<unique_fd> context_zip_fds;
1984 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1985 if (open_dex_paths_rc != 0) {
1986 _exit(open_dex_paths_rc);
1987 }
1988
Calin Juravle7d765462017-09-04 15:57:10 -07001989 // Prepare the oat directories.
1990 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001991 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001992 }
1993
1994 // Open the vdex/oat files if any.
1995 unique_fd oat_file_fd;
1996 unique_fd vdex_file_fd;
1997 if (!maybe_open_oat_and_vdex_file(dex_path,
1998 *oat_dir_out,
1999 instruction_set,
2000 true /* is_secondary_dex */,
2001 &oat_file_fd,
2002 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002003 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07002004 }
2005
2006 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08002007 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
2008 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07002009
2010 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002011 // Note that we do not do it before the fork since opening the files is required to happen
2012 // after forking.
2013 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
2014 vdex_file_fd.get(),
2015 oat_file_fd.get(),
2016 zip_fd.get(),
2017 instruction_set,
2018 compiler_filter, profile_was_updated,
2019 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00002020 class_loader_context,
2021 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002022 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08002023 }
2024
2025 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08002026 int result = wait_child(pid);
2027 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002028 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2029 dex_path.c_str(),
2030 result);
2031 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002032 return false;
2033 }
2034 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002035 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002036 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2037 result,
2038 dexopt_needed_out,
2039 error_msg);
2040 if (!success) {
2041 LOG(ERROR) << *error_msg;
2042 }
Calin Juravle7d765462017-09-04 15:57:10 -07002043
2044 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2045
Calin Juravle80a21252017-01-17 14:43:25 -08002046 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002047 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2048 // makes the code simpler; force compilation is only needed during tests).
2049 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002050 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002051 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002052 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2053 }
2054
Calin Juravle7d765462017-09-04 15:57:10 -07002055 // Check if we should make the oat file public.
2056 // Note that if the dex file is not public the compiled code cannot be made public.
2057 // It is ok to check this flag outside in the parent process.
2058 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2059
Calin Juravle80a21252017-01-17 14:43:25 -08002060 return success;
2061}
2062
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002063static std::string format_dexopt_error(int status, const char* dex_path) {
2064 if (WIFEXITED(status)) {
2065 int int_code = WEXITSTATUS(status);
2066 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2067 if (code_name != nullptr) {
2068 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2069 }
2070 }
2071 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002072}
2073
Calin Juravlec9eab382017-01-25 01:17:17 -08002074int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002075 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002076 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002077 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002078 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002079 CHECK(pkgname != nullptr);
2080 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002081 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002082 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2083 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002084
Calin Juravled23dee72017-07-06 16:29:11 -07002085 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002086 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002087 return -1;
2088 }
2089
2090 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002091 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2092 class_loader_context);
2093 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002094 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002095 }
2096
Calin Juravleebc8a792017-04-04 20:21:05 -07002097 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002098 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2099 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2100 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002101 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002102 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002103 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002104 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002105 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002106 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002107
2108 // Check if we're dealing with a secondary dex file and if we need to compile it.
2109 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002110 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002111 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002112 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2113 *error_msg = "Failed acquiring context dex paths";
2114 return -1; // We had an error, logged in the process method.
2115 }
2116
Calin Juravlec9eab382017-01-25 01:17:17 -08002117 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002118 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002119 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002120 oat_dir = oat_dir_str.c_str();
2121 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2122 return 0; // Nothing to do, report success.
2123 }
2124 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002125 if (error_msg->empty()) { // TODO: Make this a CHECK.
2126 *error_msg = "Failed processing secondary.";
2127 }
Calin Juravle80a21252017-01-17 14:43:25 -08002128 return -1; // We had an error, logged in the process method.
2129 }
2130 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002131 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002132 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002133 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2134 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2135 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002136
2137 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002138 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002139 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002140 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2141 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002142 return -1;
2143 }
2144
David Brazdil4f6027a2019-03-19 11:44:21 +00002145 // Open class loader context dex files.
2146 std::vector<unique_fd> context_input_fds;
2147 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2148 LOG(ERROR) << *error_msg;
2149 return -1;
2150 }
2151
Calin Juravle7a570e82017-01-14 16:23:30 -08002152 // Create the output OAT file.
2153 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002154 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002155 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002156 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002157 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002158 return -1;
2159 }
2160
2161 // Open vdex files.
2162 Dex2oatFileWrapper in_vdex_fd;
2163 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002164 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2165 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002166 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002167 return -1;
2168 }
2169
Calin Juravlecb556e32017-04-04 20:22:50 -07002170 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2171 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2172 // fully inherit their parent context).
2173 // Note that for primary apk the oat files are created before, in a separate installd
2174 // call which also does the restorecon. TODO(calin): unify the paths.
2175 if (is_secondary_dex) {
2176 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2177 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002178 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2179 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002180 return -1;
2181 }
2182 }
2183
Jeff Sharkey90aff262016-12-12 14:28:24 -07002184 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002185 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002186
Calin Juravle7a570e82017-01-14 16:23:30 -08002187 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002188 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002189 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002190
liulvping61907742018-08-21 09:36:52 +08002191 if (reference_profile_fd.get() == -1) {
2192 // We don't create an app image without reference profile since there is no speedup from
2193 // loading it in that case and instead will be a small overhead.
2194 generate_app_image = false;
2195 }
2196
2197 // Create the app image file if needed.
2198 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2199 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2200
Calin Juravle62c5a372018-02-01 17:03:23 +00002201 unique_fd dex_metadata_fd;
2202 if (dex_metadata_path != nullptr) {
2203 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2204 if (dex_metadata_fd.get() < 0) {
2205 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2206 }
2207 }
2208
Victor Hsieh8948a862020-08-07 11:30:55 -07002209 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
2210 RUNTIME_NATIVE_BOOT_NAMESPACE,
2211 ENABLE_JITZYGOTE_IMAGE,
2212 /*default_value=*/ "");
2213 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
2214
Andreas Gampe023b2242018-02-28 16:03:25 -08002215 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002216
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002217 RunDex2Oat runner(input_fd.get(),
2218 out_oat_fd.get(),
2219 in_vdex_fd.get(),
2220 out_vdex_fd.get(),
2221 image_fd.get(),
2222 dex_path,
2223 out_oat_path,
2224 swap_fd.get(),
2225 instruction_set,
2226 compiler_filter,
2227 debuggable,
2228 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002229 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002230 background_job_compile,
2231 reference_profile_fd.get(),
2232 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002233 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002234 target_sdk_version,
2235 enable_hidden_api_checks,
2236 generate_compact_dex,
2237 dex_metadata_fd.get(),
Victor Hsieh8948a862020-08-07 11:30:55 -07002238 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002239 compilation_reason);
2240
Jeff Sharkey90aff262016-12-12 14:28:24 -07002241 pid_t pid = fork();
2242 if (pid == 0) {
2243 /* child -- drop privileges before continuing */
2244 drop_capabilities(uid);
2245
Richard Uhler76cc0272016-12-08 10:46:35 +00002246 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002247 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002248 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002249 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002250 }
2251
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002252 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002253 } else {
2254 int res = wait_child(pid);
2255 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002256 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002257 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002258 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2259 << std::hex << std::setw(4) << res << ", process failed";
2260 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002261 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002262 }
2263 }
2264
Calin Juravlec9eab382017-01-25 01:17:17 -08002265 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002266
2267 // We've been successful, don't delete output.
2268 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002269 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002270 image_fd.SetCleanup(false);
2271 reference_profile_fd.SetCleanup(false);
2272
2273 return 0;
2274}
2275
Calin Juravlec9eab382017-01-25 01:17:17 -08002276// Try to remove the given directory. Log an error if the directory exists
2277// and is empty but could not be removed.
2278static bool rmdir_if_empty(const char* dir) {
2279 if (rmdir(dir) == 0) {
2280 return true;
2281 }
2282 if (errno == ENOENT || errno == ENOTEMPTY) {
2283 return true;
2284 }
2285 PLOG(ERROR) << "Failed to remove dir: " << dir;
2286 return false;
2287}
2288
2289// Try to unlink the given file. Log an error if the file exists and could not
2290// be unlinked.
2291static bool unlink_if_exists(const std::string& file) {
2292 if (unlink(file.c_str()) == 0) {
2293 return true;
2294 }
2295 if (errno == ENOENT) {
2296 return true;
2297
2298 }
2299 PLOG(ERROR) << "Could not unlink: " << file;
2300 return false;
2301}
2302
Calin Juravle7d765462017-09-04 15:57:10 -07002303enum ReconcileSecondaryDexResult {
2304 kReconcileSecondaryDexExists = 0,
2305 kReconcileSecondaryDexCleanedUp = 1,
2306 kReconcileSecondaryDexValidationError = 2,
2307 kReconcileSecondaryDexCleanUpError = 3,
2308 kReconcileSecondaryDexAccessIOError = 4,
2309};
Calin Juravlec9eab382017-01-25 01:17:17 -08002310
2311// Reconcile the secondary dex 'dex_path' and its generated oat files.
2312// Return true if all the parameters are valid and the secondary dex file was
2313// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2314// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2315// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2316// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2317// Return false if there were errors during processing. In this case
2318// out_secondary_dex_exists will be set to false.
2319bool reconcile_secondary_dex_file(const std::string& dex_path,
2320 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002321 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002322 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002323 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002324 if (isas.size() == 0) {
2325 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2326 return false;
2327 }
2328
Calin Juravle7d765462017-09-04 15:57:10 -07002329 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2330 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2331 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002332 return false;
2333 }
2334
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002335 // As a security measure we want to unlink art artifacts with the reduced capabilities
2336 // of the package user id. So we fork and drop capabilities in the child.
2337 pid_t pid = fork();
2338 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002339 /* child -- drop privileges before continuing */
2340 drop_capabilities(uid);
2341
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002342 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002343 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002344 uid, storage_flag)) {
2345 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2346 _exit(kReconcileSecondaryDexValidationError);
2347 }
2348
2349 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2350 switch (access_check) {
2351 case kSecondaryDexAccessDoesNotExist:
2352 // File does not exist. Proceed with cleaning.
2353 break;
2354 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2355 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2356 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2357 default:
2358 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2359 _exit(kReconcileSecondaryDexValidationError);
2360 }
2361
2362 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002363 char oat_path[PKG_PATH_MAX];
2364 char oat_dir[PKG_PATH_MAX];
2365 char oat_isa_dir[PKG_PATH_MAX];
2366 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002367 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002368 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002369 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002370 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2371 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002372 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002373 }
Calin Juravle51314092017-05-18 15:33:05 -07002374
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002375 // Delete oat/vdex/art files.
2376 result = unlink_if_exists(oat_path) && result;
2377 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2378 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002379
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002380 // Delete profiles.
2381 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002382 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002383 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002384 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002385 result = unlink_if_exists(current_profile) && result;
2386 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002387
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002388 // We upgraded once the location of current profile for secondary dex files.
2389 // Check for any previous left-overs and remove them as well.
2390 std::string old_current_profile = dex_path + ".prof";
2391 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002392
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002393 // Try removing the directories as well, they might be empty.
2394 result = rmdir_if_empty(oat_isa_dir) && result;
2395 result = rmdir_if_empty(oat_dir) && result;
2396 }
Calin Juravle7d765462017-09-04 15:57:10 -07002397 if (!result) {
2398 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2399 }
2400 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002401 }
2402
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002403 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002404 if (!WIFEXITED(return_code)) {
2405 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2406 } else {
2407 return_code = WEXITSTATUS(return_code);
2408 }
2409
2410 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2411
2412 switch (return_code) {
2413 case kReconcileSecondaryDexCleanedUp:
2414 case kReconcileSecondaryDexValidationError:
2415 // If we couldn't validate assume the dex file does not exist.
2416 // This will purge the entry from the PM records.
2417 *out_secondary_dex_exists = false;
2418 return true;
2419 case kReconcileSecondaryDexExists:
2420 *out_secondary_dex_exists = true;
2421 return true;
2422 case kReconcileSecondaryDexAccessIOError:
2423 // We had an access IO error.
2424 // Return false so that we can try again.
2425 // The value of out_secondary_dex_exists does not matter in this case and by convention
2426 // is set to false.
2427 *out_secondary_dex_exists = false;
2428 return false;
2429 default:
2430 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2431 *out_secondary_dex_exists = false;
2432 return false;
2433 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002434}
2435
Alan Stokesa25d90c2017-10-16 10:56:00 +01002436// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2437// Returns true if all parameters are valid and the hash successfully computed and stored in
2438// out_secondary_dex_hash.
2439// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2440// the app.
2441// For any other errors (e.g. if any of the parameters are invalid) returns false.
2442bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002443 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002444 std::vector<uint8_t>* out_secondary_dex_hash) {
2445 out_secondary_dex_hash->clear();
2446
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002447 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002448
2449 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2450 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2451 << storage_flag;
2452 return false;
2453 }
2454
2455 // Pipe to get the hash result back from our child process.
2456 unique_fd pipe_read, pipe_write;
2457 if (!Pipe(&pipe_read, &pipe_write)) {
2458 PLOG(ERROR) << "Failed to create pipe";
2459 return false;
2460 }
2461
2462 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2463 // access data the app itself can access.
2464 pid_t pid = fork();
2465 if (pid == 0) {
2466 // child -- drop privileges before continuing
2467 drop_capabilities(uid);
2468 pipe_read.reset();
2469
2470 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2471 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002472 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002473 }
2474
2475 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2476 if (fd == -1) {
2477 if (errno == EACCES || errno == ENOENT) {
2478 // Not treated as an error.
2479 _exit(0);
2480 }
2481 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002482 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002483 }
2484
2485 SHA256_CTX ctx;
2486 SHA256_Init(&ctx);
2487
2488 std::vector<uint8_t> buffer(65536);
2489 while (true) {
2490 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2491 if (bytes_read == 0) {
2492 break;
2493 } else if (bytes_read == -1) {
2494 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002495 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002496 }
2497
2498 SHA256_Update(&ctx, buffer.data(), bytes_read);
2499 }
2500
2501 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2502 SHA256_Final(hash.data(), &ctx);
2503 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002504 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002505 }
2506
2507 _exit(0);
2508 }
2509
2510 // parent
2511 pipe_write.reset();
2512
2513 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2514 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2515 out_secondary_dex_hash->clear();
2516 }
2517 return wait_child(pid) == 0;
2518}
2519
Jeff Sharkey90aff262016-12-12 14:28:24 -07002520// Helper for move_ab, so that we can have common failure-case cleanup.
2521static bool unlink_and_rename(const char* from, const char* to) {
2522 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2523 // return a failure.
2524 struct stat s;
2525 if (stat(to, &s) == 0) {
2526 if (!S_ISREG(s.st_mode)) {
2527 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2528 return false;
2529 }
2530 if (unlink(to) != 0) {
2531 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2532 return false;
2533 }
2534 } else {
2535 // This may be a permission problem. We could investigate the error code, but we'll just
2536 // let the rename failure do the work for us.
2537 }
2538
2539 // Try to rename "to" to "from."
2540 if (rename(from, to) != 0) {
2541 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2542 return false;
2543 }
2544 return true;
2545}
2546
2547// Move/rename a B artifact (from) to an A artifact (to).
2548static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2549 // Check whether B exists.
2550 {
2551 struct stat s;
2552 if (stat(b_path.c_str(), &s) != 0) {
2553 // Silently ignore for now. The service calling this isn't smart enough to understand
2554 // lack of artifacts at the moment.
2555 return false;
2556 }
2557 if (!S_ISREG(s.st_mode)) {
2558 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2559 // Try to unlink, but swallow errors.
2560 unlink(b_path.c_str());
2561 return false;
2562 }
2563 }
2564
2565 // Rename B to A.
2566 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2567 // Delete the b_path so we don't try again (or fail earlier).
2568 if (unlink(b_path.c_str()) != 0) {
2569 PLOG(ERROR) << "Could not unlink " << b_path;
2570 }
2571
2572 return false;
2573 }
2574
2575 return true;
2576}
2577
2578bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2579 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002580 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2581 if (slot_suffix.empty()) {
2582 return false;
2583 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002584
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002585 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2586 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2587 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002588 }
2589
2590 // Validate other inputs.
2591 if (validate_apk_path(apk_path) != 0) {
2592 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2593 return false;
2594 }
2595 if (validate_apk_path(oat_dir) != 0) {
2596 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2597 return false;
2598 }
2599
2600 char a_path[PKG_PATH_MAX];
2601 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2602 return false;
2603 }
2604 const std::string a_vdex_path = create_vdex_filename(a_path);
2605 const std::string a_image_path = create_image_filename(a_path);
2606
2607 // B path = A path + slot suffix.
2608 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2609 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2610 const std::string b_image_path = StringPrintf("%s.%s",
2611 a_image_path.c_str(),
2612 slot_suffix.c_str());
2613
2614 bool success = true;
2615 if (move_ab_path(b_path, a_path)) {
2616 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2617 // Note: we can live without an app image. As such, ignore failure to move the image file.
2618 // If we decide to require the app image, or the app image being moved correctly,
2619 // then change accordingly.
2620 constexpr bool kIgnoreAppImageFailure = true;
2621
2622 if (!a_image_path.empty()) {
2623 if (!move_ab_path(b_image_path, a_image_path)) {
2624 unlink(a_image_path.c_str());
2625 if (!kIgnoreAppImageFailure) {
2626 success = false;
2627 }
2628 }
2629 }
2630 } else {
2631 // Cleanup: delete B image, ignore errors.
2632 unlink(b_image_path.c_str());
2633 success = false;
2634 }
2635 } else {
2636 // Cleanup: delete B image, ignore errors.
2637 unlink(b_vdex_path.c_str());
2638 unlink(b_image_path.c_str());
2639 success = false;
2640 }
2641 return success;
2642}
2643
2644bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2645 // Delete the oat/odex file.
2646 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002647 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002648 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002649 return false;
2650 }
2651
2652 // In case of a permission failure report the issue. Otherwise just print a warning.
2653 auto unlink_and_check = [](const char* path) -> bool {
2654 int result = unlink(path);
2655 if (result != 0) {
2656 if (errno == EACCES || errno == EPERM) {
2657 PLOG(ERROR) << "Could not unlink " << path;
2658 return false;
2659 }
2660 PLOG(WARNING) << "Could not unlink " << path;
2661 }
2662 return true;
2663 };
2664
2665 // Delete the oat/odex file.
2666 bool return_value_oat = unlink_and_check(out_path);
2667
2668 // Derive and delete the app image.
2669 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2670
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002671 // Derive and delete the vdex file.
2672 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2673
Jeff Sharkey90aff262016-12-12 14:28:24 -07002674 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002675 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002676}
2677
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002678static bool is_absolute_path(const std::string& path) {
2679 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2680 LOG(ERROR) << "Invalid absolute path " << path;
2681 return false;
2682 } else {
2683 return true;
2684 }
2685}
2686
2687static bool is_valid_instruction_set(const std::string& instruction_set) {
2688 // TODO: add explicit whitelisting of instruction sets
2689 if (instruction_set.find('/') != std::string::npos) {
2690 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2691 return false;
2692 } else {
2693 return true;
2694 }
2695}
2696
2697bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2698 const char *apk_path, const char *instruction_set) {
2699 std::string oat_dir_ = oat_dir;
2700 std::string apk_path_ = apk_path;
2701 std::string instruction_set_ = instruction_set;
2702
2703 if (!is_absolute_path(oat_dir_)) return false;
2704 if (!is_absolute_path(apk_path_)) return false;
2705 if (!is_valid_instruction_set(instruction_set_)) return false;
2706
2707 std::string::size_type end = apk_path_.rfind('.');
2708 std::string::size_type start = apk_path_.rfind('/', end);
2709 if (end == std::string::npos || start == std::string::npos) {
2710 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2711 return false;
2712 }
2713
2714 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2715 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2716 const char* res = res_.c_str();
2717 if (strlen(res) >= PKG_PATH_MAX) {
2718 LOG(ERROR) << "Result too large";
2719 return false;
2720 } else {
2721 strlcpy(path, res, PKG_PATH_MAX);
2722 return true;
2723 }
2724}
2725
2726bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2727 const char *instruction_set) {
2728 std::string apk_path_ = apk_path;
2729 std::string instruction_set_ = instruction_set;
2730
2731 if (!is_absolute_path(apk_path_)) return false;
2732 if (!is_valid_instruction_set(instruction_set_)) return false;
2733
2734 std::string::size_type end = apk_path_.rfind('.');
2735 std::string::size_type start = apk_path_.rfind('/', end);
2736 if (end == std::string::npos || start == std::string::npos) {
2737 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2738 return false;
2739 }
2740
2741 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2742 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2743}
2744
2745bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2746 const char *instruction_set) {
2747 std::string src_ = src;
2748 std::string instruction_set_ = instruction_set;
2749
2750 if (!is_absolute_path(src_)) return false;
2751 if (!is_valid_instruction_set(instruction_set_)) return false;
2752
2753 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2754 if (*it == '/') {
2755 *it = '@';
2756 }
2757 }
2758
2759 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2760 + DALVIK_CACHE_POSTFIX;
2761 const char* res = res_.c_str();
2762 if (strlen(res) >= PKG_PATH_MAX) {
2763 LOG(ERROR) << "Result too large";
2764 return false;
2765 } else {
2766 strlcpy(path, res, PKG_PATH_MAX);
2767 return true;
2768 }
2769}
2770
Calin Juravle59f7ab82018-04-27 17:50:23 -07002771bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2772 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002773 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2774 for (const std::string& elem : classpaths_elems) {
2775 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2776 if (fd < 0) {
2777 PLOG(ERROR) << "Could not open classpath elem " << elem;
2778 return false;
2779 } else {
2780 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002781 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002782 }
2783 }
2784 return true;
2785}
2786
2787static bool create_app_profile_snapshot(int32_t app_id,
2788 const std::string& package_name,
2789 const std::string& profile_name,
2790 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002791 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2792
Calin Juravle824a64d2018-01-18 20:23:17 -08002793 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002794 if (snapshot_fd < 0) {
2795 return false;
2796 }
2797
2798 std::vector<unique_fd> profiles_fd;
2799 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002800 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2801 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002802 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2803 return false;
2804 }
2805
2806 profiles_fd.push_back(std::move(reference_profile_fd));
2807
Calin Juravle0d0a4922018-01-23 19:54:11 -08002808 // Open the class paths elements. These will be used to filter out profile data that does
2809 // not belong to the classpath during merge.
2810 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002811 std::vector<std::string> dex_locations;
2812 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002813 return false;
2814 }
2815
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002816 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002817 // This is specifically a snapshot for an app, so don't use boot image profiles.
2818 args.SetupMerge(profiles_fd,
2819 snapshot_fd,
2820 apk_fds,
2821 dex_locations,
2822 /* for_snapshot= */ true,
2823 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002824 pid_t pid = fork();
2825 if (pid == 0) {
2826 /* child -- drop privileges before continuing */
2827 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002828 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002829 }
2830
2831 /* parent */
2832 int return_code = wait_child(pid);
2833 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002834 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002835 return false;
2836 }
2837
Calin Juravle78728f32019-11-08 17:55:46 -08002838 // Verify that profman finished successfully.
2839 int profman_code = WEXITSTATUS(return_code);
2840 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2841 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2842 << ":" << profman_code;
2843 return false;
2844 }
Calin Juravle29591732017-11-20 17:46:19 -08002845 return true;
2846}
2847
Calin Juravle0d0a4922018-01-23 19:54:11 -08002848static bool create_boot_image_profile_snapshot(const std::string& package_name,
2849 const std::string& profile_name,
2850 const std::string& classpath) {
2851 // The reference profile directory for the android package might not be prepared. Do it now.
2852 const std::string ref_profile_dir =
2853 create_primary_reference_profile_package_dir_path(package_name);
2854 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2855 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2856 return false;
2857 }
2858
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002859 // Return false for empty class path since it may otherwise return true below if profiles is
2860 // empty.
2861 if (classpath.empty()) {
2862 PLOG(ERROR) << "Class path is empty";
2863 return false;
2864 }
2865
Calin Juravle0d0a4922018-01-23 19:54:11 -08002866 // Open and create the snapshot profile.
2867 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2868
2869 // Collect all non empty profiles.
2870 // The collection will traverse all applications profiles and find the non empty files.
2871 // This has the potential of inspecting a large number of files and directories (depending
2872 // on the number of applications and users). So there is a slight increase in the chance
2873 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2874 // fail the snapshot and aggregate whatever profile we could open.
2875 //
2876 // The profile snapshot is a best effort based on available data it's ok if some data
2877 // from some apps is missing. It will be counter productive for the snapshot to fail
2878 // because we could not open or read some of the files.
2879 std::vector<std::string> profiles;
2880 if (!collect_profiles(&profiles)) {
2881 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2882 }
2883
2884 // If we have no profiles return early.
2885 if (profiles.empty()) {
2886 return true;
2887 }
2888
2889 // Open the classpath elements. These will be used to filter out profile data that does
2890 // not belong to the classpath during merge.
2891 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002892 std::vector<std::string> dex_locations;
2893 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002894 return false;
2895 }
2896
2897 // If we could not open any files from the classpath return an error.
2898 if (apk_fds.empty()) {
2899 LOG(ERROR) << "Could not open any of the classpath elements.";
2900 return false;
2901 }
2902
2903 // Aggregate the profiles in batches of kAggregationBatchSize.
2904 // We do this to avoid opening a huge a amount of files.
2905 static constexpr size_t kAggregationBatchSize = 10;
2906
Calin Juravle0d0a4922018-01-23 19:54:11 -08002907 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002908 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002909 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2910 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2911 if (fd.get() >= 0) {
2912 profiles_fd.push_back(std::move(fd));
2913 }
2914 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002915
2916 // We aggregate (read & write) into the same fd multiple times in a row.
2917 // We need to reset the cursor every time to ensure we read the whole file every time.
2918 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2919 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2920 return false;
2921 }
2922
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002923 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002924 args.SetupMerge(profiles_fd,
2925 snapshot_fd,
2926 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002927 dex_locations,
2928 /*for_snapshot=*/true,
2929 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002930 pid_t pid = fork();
2931 if (pid == 0) {
2932 /* child -- drop privileges before continuing */
2933 drop_capabilities(AID_SYSTEM);
2934
Calin Juravle59f7ab82018-04-27 17:50:23 -07002935 // The introduction of new access flags into boot jars causes them to
2936 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002937 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002938 }
2939
2940 /* parent */
2941 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002942
Calin Juravle0d0a4922018-01-23 19:54:11 -08002943 if (!WIFEXITED(return_code)) {
2944 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2945 return false;
2946 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002947
2948 // Verify that profman finished successfully.
2949 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002950 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2951 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2952 << ":" << profman_code;
2953 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002954 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002955 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002956
Calin Juravle0d0a4922018-01-23 19:54:11 -08002957 return true;
2958}
2959
2960bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2961 const std::string& profile_name, const std::string& classpath) {
2962 if (app_id == -1) {
2963 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2964 } else {
2965 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2966 }
2967}
2968
Calin Juravlec3b049e2018-01-18 22:32:58 -08002969bool prepare_app_profile(const std::string& package_name,
2970 userid_t user_id,
2971 appid_t app_id,
2972 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002973 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002974 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002975 // Prepare the current profile.
2976 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2977 /*is_secondary_dex*/ false);
2978 uid_t uid = multiuser_get_uid(user_id, app_id);
2979 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2980 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2981 return false;
2982 }
2983
2984 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002985 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002986 return true;
2987 }
2988
2989 // We have a dex metdata. Merge the profile into the reference profile.
2990 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2991 /*read_write*/ true, /*is_secondary_dex*/ false);
2992 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2993 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002994 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2995 if (apk_fd < 0) {
2996 PLOG(ERROR) << "Could not open code path " << code_path;
2997 return false;
2998 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002999
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003000 RunProfman args;
3001 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
3002 std::move(ref_profile_fd),
3003 std::move(apk_fd),
3004 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08003005 pid_t pid = fork();
3006 if (pid == 0) {
3007 /* child -- drop privileges before continuing */
3008 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
3009 drop_capabilities(app_shared_gid);
3010
Calin Juravlef63d4792018-01-30 17:43:34 +00003011 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003012 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08003013 }
3014
3015 /* parent */
3016 int return_code = wait_child(pid);
3017 if (!WIFEXITED(return_code)) {
3018 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
3019 return false;
3020 }
3021 return true;
3022}
3023
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003024} // namespace installd
3025} // namespace android