blob: ebb8f0f90e2ebdcd4a98f13bdcafc2666cfd1f3f [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
Jeff Sharkey90aff262016-12-12 14:28:24 -070058using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070059using android::base::GetBoolProperty;
60using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000061using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010062using android::base::ReadFully;
63using android::base::StringPrintf;
64using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080065using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066
67namespace android {
68namespace installd {
69
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070070// Should minidebug info be included in compiled artifacts? Even if this value is
71// "true," usage might still be conditional to other constraints, e.g., system
72// property overrides.
73static constexpr bool kEnableMinidebugInfo = true;
74
75static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
76static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
77static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080078static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070079
Andreas Gampefa2dadd2018-02-28 19:52:47 -080080
Calin Juravle114f0812017-03-08 19:05:07 -080081// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
82struct FreeDelete {
83 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
84 void operator()(const void* ptr) const {
85 free(const_cast<void*>(ptr));
86 }
87};
88
89// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
90template <typename T>
91using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
92
Calin Juravle1a0af3b2017-03-09 14:33:33 -080093static unique_fd invalid_unique_fd() {
94 return unique_fd(-1);
95}
96
Andreas Gampe6a9cf722017-07-24 16:49:10 -070097static bool is_debug_runtime() {
98 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
99}
100
David Sehra3b5ab62017-10-25 14:27:29 -0700101static bool is_debuggable_build() {
102 return android::base::GetBoolProperty("ro.debuggable", false);
103}
104
Jeff Sharkey90aff262016-12-12 14:28:24 -0700105static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800106 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700107 if (ufd.get() < 0) {
108 if (errno != ENOENT) {
109 PLOG(WARNING) << "Could not open profile " << profile;
110 return false;
111 } else {
112 // Nothing to clear. That's ok.
113 return true;
114 }
115 }
116
117 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
118 if (errno != EWOULDBLOCK) {
119 PLOG(WARNING) << "Error locking profile " << profile;
120 }
121 // This implies that the app owning this profile is running
122 // (and has acquired the lock).
123 //
124 // If we can't acquire the lock bail out since clearing is useless anyway
125 // (the app will write again to the profile).
126 //
127 // Note:
128 // This does not impact the this is not an issue for the profiling correctness.
129 // In case this is needed because of an app upgrade, profiles will still be
130 // eventually cleared by the app itself due to checksum mismatch.
131 // If this is needed because profman advised, then keeping the data around
132 // until the next run is again not an issue.
133 //
134 // If the app attempts to acquire a lock while we've held one here,
135 // it will simply skip the current write cycle.
136 return false;
137 }
138
139 bool truncated = ftruncate(ufd.get(), 0) == 0;
140 if (!truncated) {
141 PLOG(WARNING) << "Could not truncate " << profile;
142 }
143 if (flock(ufd.get(), LOCK_UN) != 0) {
144 PLOG(WARNING) << "Error unlocking profile " << profile;
145 }
146 return truncated;
147}
148
Calin Juravle114f0812017-03-08 19:05:07 -0800149// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800150// The location is the profile name for primary apks or the dex path for secondary dex files.
151static bool clear_reference_profile(const std::string& package_name, const std::string& location,
152 bool is_secondary_dex) {
153 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154}
155
Calin Juravle114f0812017-03-08 19:05:07 -0800156// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800157// The location is the profile name for primary apks or the dex path for secondary dex files.
158static bool clear_current_profile(const std::string& package_name, const std::string& location,
159 userid_t user, bool is_secondary_dex) {
160 return clear_profile(create_current_profile_path(user, package_name, location,
161 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700162}
163
Calin Juravle114f0812017-03-08 19:05:07 -0800164// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800165// The location is the profile name for primary apks or the dex path for secondary dex files.
166bool clear_primary_reference_profile(const std::string& package_name,
167 const std::string& location) {
168 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800169}
170
171// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800172// The location is the profile name for primary apks or the dex path for secondary dex files.
173bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800175 // 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 -0700176 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
177 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800178 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700179 }
180 return success;
181}
182
Calin Juravle114f0812017-03-08 19:05:07 -0800183// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800184bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
185 userid_t user) {
186 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800187}
188
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700189static std::vector<std::string> SplitBySpaces(const std::string& str) {
190 if (str.empty()) {
191 return {};
192 }
193 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700194}
195
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700196static const char* get_location_from_path(const char* path) {
197 static constexpr char kLocationSeparator = '/';
198 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700199 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700200 return path;
201 } else {
202 // Skip the separator character.
203 return location + 1;
204 }
205}
206
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800207// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
208// need to be performed between the fork and exec.
209class ExecVHelper {
210 public:
211 // Store a placeholder for the binary name.
212 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800213
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800214 void PrepareArgs(const std::string& bin) {
215 CHECK(!args_.empty());
216 CHECK(args_[0].empty());
217 args_[0] = bin;
218 // Write char* into array.
219 for (const std::string& arg : args_) {
220 argv_.push_back(arg.c_str());
221 }
222 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800223 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800224
225 [[ noreturn ]]
226 void Exec(int exit_code) {
227 execv(argv_[0], (char * const *)&argv_[0]);
228 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
229 exit(exit_code);
230 }
231
232 // Add an arg if it's not empty.
233 void AddArg(const std::string& arg) {
234 if (!arg.empty()) {
235 args_.push_back(arg);
236 }
237 }
238
239 // Add a runtime arg if it's not empty.
240 void AddRuntimeArg(const std::string& arg) {
241 if (!arg.empty()) {
242 args_.push_back("--runtime-arg");
243 args_.push_back(arg);
244 }
245 }
246
247 protected:
248 // Holder arrays for backing arg storage.
249 std::vector<std::string> args_;
250
251 // Argument poiners.
252 std::vector<const char*> argv_;
253};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700254
255static std::string MapPropertyToArg(const std::string& property,
256 const std::string& format,
257 const std::string& default_value = "") {
258 std::string prop = GetProperty(property, default_value);
259 if (!prop.empty()) {
260 return StringPrintf(format.c_str(), prop.c_str());
261 }
262 return "";
263}
264
Calin Juravlef74a7372019-02-28 20:29:41 -0800265// Determines which binary we should use for execution (the debug or non-debug version).
266// e.g. dex2oatd vs dex2oat
267static const char* select_execution_binary(const char* binary, const char* debug_binary,
268 bool background_job_compile) {
269 return select_execution_binary(
270 binary,
271 debug_binary,
272 background_job_compile,
273 is_debug_runtime(),
274 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
275 is_debuggable_build());
276}
277
278// Determines which binary we should use for execution (the debug or non-debug version).
279// e.g. dex2oatd vs dex2oat
280// This is convenient method which is much easier to test because it doesn't read
281// system properties.
282const char* select_execution_binary(
283 const char* binary,
284 const char* debug_binary,
285 bool background_job_compile,
286 bool is_debug_runtime,
287 bool is_release,
288 bool is_debuggable_build) {
289 // Do not use debug binaries for release candidates (to give more soak time).
290 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
291
292 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
293 // the file is present (it may not be on images with very little space available).
294 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
295
296 return useDebug ? debug_binary : binary;
297}
298
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000299// Namespace for Android Runtime flags applied during boot time.
300static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
301// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000302static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
303// Location of the JIT Zygote image.
304static const char* kJitZygoteImage =
305 "boot.art:/nonx/boot-framework.art!/system/etc/boot-image.prof";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000306
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700307// Phenotype property name for enabling profiling the boot class path.
308static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
309
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800310class RunDex2Oat : public ExecVHelper {
311 public:
312 RunDex2Oat(int zip_fd,
313 int oat_fd,
314 int input_vdex_fd,
315 int output_vdex_fd,
316 int image_fd,
317 const char* input_file_name,
318 const char* output_file_name,
319 int swap_fd,
320 const char* instruction_set,
321 const char* compiler_filter,
322 bool debuggable,
323 bool post_bootcomplete,
324 bool background_job_compile,
325 int profile_fd,
326 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000327 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800328 int target_sdk_version,
329 bool enable_hidden_api_checks,
330 bool generate_compact_dex,
331 int dex_metadata_fd,
332 const char* compilation_reason) {
333 // Get the relative path to the input file.
334 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700335
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800336 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
337 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700338
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800339 const char* threads_property = post_bootcomplete
340 ? "dalvik.vm.dex2oat-threads"
341 : "dalvik.vm.boot-dex2oat-threads";
342 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Orion Hodson45837462019-11-14 18:20:17 +0000343 const char* cpu_set_property = post_bootcomplete
344 ? "dalvik.vm.dex2oat-cpu-set"
345 : "dalvik.vm.boot-dex2oat-cpu-set";
346 std::string dex2oat_cpu_set_arg = MapPropertyToArg(cpu_set_property, "--cpu-set=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700347
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000348 std::string bootclasspath;
349 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
350 if (dex2oat_bootclasspath != nullptr) {
351 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
352 }
353 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
354 // BOOTCLASSPATH.
355
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800356 const std::string dex2oat_isa_features_key =
357 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
358 std::string instruction_set_features_arg =
359 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700360
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800361 const std::string dex2oat_isa_variant_key =
362 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
363 std::string instruction_set_variant_arg =
364 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700365
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800366 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700367
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800368 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
369 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
370 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700371
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800372 // If we are booting without the real /data, don't spend time compiling.
373 std::string vold_decrypt = GetProperty("vold.decrypt", "");
374 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
375 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700376
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800377 std::string resolve_startup_string_arg =
378 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
379 "--resolve-startup-const-strings=%s");
380 if (resolve_startup_string_arg.empty()) {
381 // If empty, fall back to system property.
382 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800383 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
384 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800385 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800386
387 const std::string image_block_size_arg =
388 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
389 "--max-image-block-size=%s");
390
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800391 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700392
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800393 std::string image_format_arg;
394 if (image_fd >= 0) {
395 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000396 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000397
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800398 std::string dex2oat_large_app_threshold_arg =
399 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000400
Calin Juravlef74a7372019-02-28 20:29:41 -0800401
402 const char* dex2oat_bin = select_execution_binary(
403 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000404
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800405 bool generate_minidebug_info = kEnableMinidebugInfo &&
406 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000407
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000408 std::string boot_image;
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000409 std::string use_jitzygote_image =
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000410 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000411 ENABLE_JITZYGOTE_IMAGE,
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000412 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700413
414 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
415 profile_boot_class_path =
416 server_configurable_flags::GetServerConfigurableFlag(
417 RUNTIME_NATIVE_BOOT_NAMESPACE,
418 PROFILE_BOOT_CLASS_PATH,
419 /*default_value=*/ profile_boot_class_path);
420
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000421 if (use_jitzygote_image == "true" || profile_boot_class_path == "true") {
422 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000423 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000424 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000425 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000426
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800427 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
428 // use arraysize instead.
429 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
430 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
431 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
432 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
433 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
434 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
435 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
436 std::string dex2oat_compiler_filter_arg;
437 std::string dex2oat_swap_fd;
438 std::string dex2oat_image_fd;
439 std::string target_sdk_version_arg;
440 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000441 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800442 }
443 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000444 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800445 if (class_loader_context != nullptr) {
446 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
447 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000448 if (!class_loader_context_fds.empty()) {
449 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
450 class_loader_context_fds.c_str());
451 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800452 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000453
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800454 if (swap_fd >= 0) {
455 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
456 }
457 if (image_fd >= 0) {
458 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
459 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000460
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800461 // Compute compiler filter.
462 bool have_dex2oat_relocation_skip_flag = false;
463 if (skip_compilation) {
464 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
465 have_dex2oat_relocation_skip_flag = true;
466 } else if (compiler_filter != nullptr) {
467 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
468 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000469
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800470 if (dex2oat_compiler_filter_arg.empty()) {
471 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
472 "--compiler-filter=%s");
473 }
474
475 // Check whether all apps should be compiled debuggable.
476 if (!debuggable) {
477 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
478 }
479 std::string profile_arg;
480 if (profile_fd != -1) {
481 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
482 }
483
484 // Get the directory of the apk to pass as a base classpath directory.
485 std::string base_dir;
486 std::string apk_dir(input_file_name);
487 unsigned long dir_index = apk_dir.rfind('/');
488 bool has_base_dir = dir_index != std::string::npos;
489 if (has_base_dir) {
490 apk_dir = apk_dir.substr(0, dir_index);
491 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
492 }
493
494 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
495
496 std::string compilation_reason_arg = compilation_reason == nullptr
497 ? ""
498 : std::string("--compilation-reason=") + compilation_reason;
499
500 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
501
502 // Disable cdex if update input vdex is true since this combination of options is not
503 // supported.
504 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
505
506 AddArg(zip_fd_arg);
507 AddArg(zip_location_arg);
508 AddArg(input_vdex_fd_arg);
509 AddArg(output_vdex_fd_arg);
510 AddArg(oat_fd_arg);
511 AddArg(oat_location_arg);
512 AddArg(instruction_set_arg);
513
514 AddArg(instruction_set_variant_arg);
515 AddArg(instruction_set_features_arg);
516
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000517 AddArg(boot_image);
518
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000519 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800520 AddRuntimeArg(dex2oat_Xms_arg);
521 AddRuntimeArg(dex2oat_Xmx_arg);
522
523 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800524 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800525 AddArg(dex2oat_compiler_filter_arg);
526 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000527 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800528 AddArg(dex2oat_swap_fd);
529 AddArg(dex2oat_image_fd);
530
531 if (generate_debug_info) {
532 AddArg("--generate-debug-info");
533 }
534 if (debuggable) {
535 AddArg("--debuggable");
536 }
537 AddArg(image_format_arg);
538 AddArg(dex2oat_large_app_threshold_arg);
539
540 if (have_dex2oat_relocation_skip_flag) {
541 AddRuntimeArg(dex2oat_norelocation);
542 }
543 AddArg(profile_arg);
544 AddArg(base_dir);
545 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000546 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800547 if (generate_minidebug_info) {
548 AddArg(kMinidebugDex2oatFlag);
549 }
550 if (disable_cdex) {
551 AddArg(kDisableCompactDexFlag);
552 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000553 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800554 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100555 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800556 }
557
558 if (dex_metadata_fd > -1) {
559 AddArg(dex_metadata_fd_arg);
560 }
561
562 AddArg(compilation_reason_arg);
563
564 // Do not add args after dex2oat_flags, they should override others for debugging.
565 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
566
567 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000568 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800569};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700570
571/*
572 * Whether dexopt should use a swap file when compiling an APK.
573 *
574 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
575 * itself, anyways).
576 *
577 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
578 *
579 * Otherwise, return true if this is a low-mem device.
580 *
581 * Otherwise, return default value.
582 */
583static bool kAlwaysProvideSwapFile = false;
584static bool kDefaultProvideSwapFile = true;
585
586static bool ShouldUseSwapFileForDexopt() {
587 if (kAlwaysProvideSwapFile) {
588 return true;
589 }
590
591 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700592 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
593 if (!dex2oat_prop_buf.empty()) {
594 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700595 }
596
597 // Shortcut for default value. This is an implementation optimization for the process sketched
598 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
599 // as low-mem is never returning false. The compiler will optimize this away if it can.
600 if (kDefaultProvideSwapFile) {
601 return true;
602 }
603
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700604 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605 return true;
606 }
607
608 // Default value must be false here.
609 return kDefaultProvideSwapFile;
610}
611
Richard Uhler76cc0272016-12-08 10:46:35 +0000612static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700613 if (set_to_bg) {
614 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800615 PLOG(ERROR) << "set_sched_policy failed";
616 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 }
618 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800619 PLOG(ERROR) << "setpriority failed";
620 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700621 }
622 }
623}
624
Calin Juravle29591732017-11-20 17:46:19 -0800625static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
626 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800627 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800628 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800629 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800630 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800631 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700632 }
Calin Juravle114f0812017-03-08 19:05:07 -0800633 // Profiles should belong to the app; make sure of that by giving ownership to
634 // the app uid. If we cannot do that, there's no point in returning the fd
635 // since dex2oat/profman will fail with SElinux denials.
636 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000637 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800638 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800639 }
Calin Juravle29591732017-11-20 17:46:19 -0800640 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800641}
642
Calin Juravle29591732017-11-20 17:46:19 -0800643static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800644 // Do not follow symlinks when opening a profile:
645 // - primary profiles should not contain symlinks in their paths
646 // - secondary dex paths should have been already resolved and validated
647 flags |= O_NOFOLLOW;
648
Calin Juravle29591732017-11-20 17:46:19 -0800649 // Check if we need to create the profile
650 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
651 unique_fd fd;
652 if ((flags & O_CREAT) != 0) {
653 fd = create_profile(uid, profile, flags);
654 } else {
655 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
656 }
657
Calin Juravle114f0812017-03-08 19:05:07 -0800658 if (fd.get() < 0) {
659 if (errno != ENOENT) {
660 // Profiles might be missing for various reasons. For example, in a
661 // multi-user environment, the profile directory for one user can be created
662 // after we start a merge. In this case the current profile for that user
663 // will not be found.
664 // Also, the secondary dex profiles might be deleted by the app at any time,
665 // so we can't we need to prepare if they are missing.
666 PLOG(ERROR) << "Failed to open profile " << profile;
667 }
668 return invalid_unique_fd();
669 }
670
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 return fd;
672}
673
Calin Juravle824a64d2018-01-18 20:23:17 -0800674static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
675 const std::string& location, bool is_secondary_dex) {
676 std::string profile = create_current_profile_path(user, package_name, location,
677 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800678 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800679}
680
Calin Juravle824a64d2018-01-18 20:23:17 -0800681static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
682 const std::string& location, bool read_write, bool is_secondary_dex) {
683 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800684 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
685}
686
687static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800688 const std::string& location) {
689 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800690 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800691}
692
Calin Juravle824a64d2018-01-18 20:23:17 -0800693static void open_profile_files(uid_t uid, const std::string& package_name,
694 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800695 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700696 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800697 *reference_profile_fd = open_reference_profile(uid, package_name, location,
698 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700699
Calin Juravle114f0812017-03-08 19:05:07 -0800700 // For secondary dex files, we don't really need the user but we use it for sanity checks.
701 // Note: the user owning the dex file should be the current user.
702 std::vector<userid_t> users;
703 if (is_secondary_dex){
704 users.push_back(multiuser_get_user_id(uid));
705 } else {
706 users = get_known_users(/*volume_uuid*/ nullptr);
707 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700708 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800709 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
710 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800712 if (profile_fd.get() >= 0) {
713 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700714 }
715 }
716}
717
Calin Juravle76561322019-11-14 09:08:52 -0800718static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
719static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
720static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
721static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
722static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
723static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
724static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700725
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800726class RunProfman : public ExecVHelper {
727 public:
728 void SetupArgs(const std::vector<unique_fd>& profile_fds,
729 const unique_fd& reference_profile_fd,
730 const std::vector<unique_fd>& apk_fds,
731 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800732 bool copy_and_update,
733 bool for_snapshot,
734 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800735
736 // TODO(calin): Assume for now we run in the bg compile job (which is in
737 // most of the invocation). With the current data flow, is not very easy or
738 // clean to discover this in RunProfman (it will require quite a messy refactoring).
739 const char* profman_bin = select_execution_binary(
740 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700741
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800742 if (copy_and_update) {
743 CHECK_EQ(1u, profile_fds.size());
744 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000745 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800746 if (reference_profile_fd != -1) {
747 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000748 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800749
750 for (const unique_fd& fd : profile_fds) {
751 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
752 }
753
754 for (const unique_fd& fd : apk_fds) {
755 AddArg("--apk-fd=" + std::to_string(fd.get()));
756 }
757
758 for (const std::string& dex_location : dex_locations) {
759 AddArg("--dex-location=" + dex_location);
760 }
761
762 if (copy_and_update) {
763 AddArg("--copy-and-update-profile-key");
764 }
765
Calin Juravle78728f32019-11-08 17:55:46 -0800766 if (for_snapshot) {
767 AddArg("--force-merge");
768 }
769
770 if (for_boot_image) {
771 AddArg("--boot-image-merge");
772 }
773
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800774 // Do not add after dex2oat_flags, they should override others for debugging.
775 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800776 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700777
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800778 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
779 const unique_fd& reference_profile_fd,
780 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800781 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
782 bool for_snapshot = false,
783 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800784 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800785 reference_profile_fd,
786 apk_fds,
787 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800788 /*copy_and_update=*/ false,
789 for_snapshot,
790 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800791 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800793 void SetupCopyAndUpdate(unique_fd&& profile_fd,
794 unique_fd&& reference_profile_fd,
795 unique_fd&& apk_fd,
796 const std::string& dex_location) {
797 // The fds need to stay open longer than the scope of the function, so put them into a local
798 // variable vector.
799 profiles_fd_.push_back(std::move(profile_fd));
800 apk_fds_.push_back(std::move(apk_fd));
801 reference_profile_fd_ = std::move(reference_profile_fd);
802 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800803 SetupArgs(profiles_fd_,
804 reference_profile_fd_,
805 apk_fds_,
806 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800807 /*copy_and_update=*/true,
808 /*for_snapshot*/false,
809 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800810 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000811
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800812 void SetupDump(const std::vector<unique_fd>& profiles_fd,
813 const unique_fd& reference_profile_fd,
814 const std::vector<std::string>& dex_locations,
815 const std::vector<unique_fd>& apk_fds,
816 const unique_fd& output_fd) {
817 AddArg("--dump-only");
818 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800819 SetupArgs(profiles_fd,
820 reference_profile_fd,
821 apk_fds,
822 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800823 /*copy_and_update=*/false,
824 /*for_snapshot*/false,
825 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800826 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000827
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800828 void Exec() {
829 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
830 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000831
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800832 private:
833 unique_fd reference_profile_fd_;
834 std::vector<unique_fd> profiles_fd_;
835 std::vector<unique_fd> apk_fds_;
836};
Mathieu Chartier31636522018-11-09 23:53:07 +0000837
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800838
Calin Juravlef63d4792018-01-30 17:43:34 +0000839
Jeff Sharkey90aff262016-12-12 14:28:24 -0700840// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800841// The location is the package name for primary apks or the dex path for secondary dex files.
842// Returns true if there is enough information in the current profiles that makes it
843// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700844// If the return value is true all the current profiles would have been merged into
845// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800846static bool analyze_profiles(uid_t uid, const std::string& package_name,
847 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800848 std::vector<unique_fd> profiles_fd;
849 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800850 open_profile_files(uid, package_name, location, is_secondary_dex,
851 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800852 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 // Skip profile guided compilation because no profiles were found.
854 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700855 return false;
856 }
857
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800858 RunProfman profman_merge;
859 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700860 pid_t pid = fork();
861 if (pid == 0) {
862 /* child -- drop privileges before continuing */
863 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800864 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865 }
866 /* parent */
867 int return_code = wait_child(pid);
868 bool need_to_compile = false;
869 bool should_clear_current_profiles = false;
870 bool should_clear_reference_profile = false;
871 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800872 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873 } else {
874 return_code = WEXITSTATUS(return_code);
875 switch (return_code) {
876 case PROFMAN_BIN_RETURN_CODE_COMPILE:
877 need_to_compile = true;
878 should_clear_current_profiles = true;
879 should_clear_reference_profile = false;
880 break;
881 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
882 need_to_compile = false;
883 should_clear_current_profiles = false;
884 should_clear_reference_profile = false;
885 break;
886 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800887 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 need_to_compile = false;
889 should_clear_current_profiles = true;
890 should_clear_reference_profile = true;
891 break;
892 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
893 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
894 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800895 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 need_to_compile = false;
897 should_clear_current_profiles = false;
898 should_clear_reference_profile = false;
899 break;
Calin Juravle76561322019-11-14 09:08:52 -0800900 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
901 need_to_compile = false;
902 should_clear_current_profiles = true;
903 should_clear_reference_profile = true;
904 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700905 default:
906 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800907 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800908 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700909 need_to_compile = false;
910 should_clear_current_profiles = true;
911 should_clear_reference_profile = true;
912 break;
913 }
914 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800915
Jeff Sharkey90aff262016-12-12 14:28:24 -0700916 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800917 if (is_secondary_dex) {
918 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800919 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
920 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800921 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800922 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800923 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700924 }
925 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800926 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700927 }
928 return need_to_compile;
929}
930
Calin Juravle114f0812017-03-08 19:05:07 -0800931// Decides if profile guided compilation is needed or not based on existing profiles.
932// The analysis is done for the primary apks of the given package.
933// Returns true if there is enough information in the current profiles that makes it
934// worth to recompile the package.
935// If the return value is true all the current profiles would have been merged into
936// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800937bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
938 const std::string& profile_name) {
939 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800940}
941
Calin Juravle408cd4a2018-01-20 23:34:18 -0800942bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
943 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800944 std::vector<unique_fd> profile_fds;
945 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800946 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
947 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700948
Calin Juravle408cd4a2018-01-20 23:34:18 -0800949 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800950 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700951
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800952 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700953 const bool has_profiles = !profile_fds.empty();
954
955 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800956 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700957 return false;
958 }
959
Calin Juravle114f0812017-03-08 19:05:07 -0800960 unique_fd output_fd(open(out_file_name.c_str(),
961 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700962 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800963 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964 return false;
965 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800966
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800968 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800969 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
970 if (apk_fd == -1) {
971 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
972 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800974 dex_locations.push_back(get_location_from_path(code_path.c_str()));
975 apk_fds.push_back(std::move(apk_fd));
976
Jeff Sharkey90aff262016-12-12 14:28:24 -0700977
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800978 RunProfman profman_dump;
979 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700980 pid_t pid = fork();
981 if (pid == 0) {
982 /* child -- drop privileges before continuing */
983 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800984 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700985 }
986 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700987 int return_code = wait_child(pid);
988 if (!WIFEXITED(return_code)) {
989 LOG(WARNING) << "profman failed for package " << pkgname << ": "
990 << return_code;
991 return false;
992 }
993 return true;
994}
995
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700996bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800997 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700998 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
999 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001000 package_name,
1001 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001002 /*read_write*/ true,
1003 /*secondary*/ false));
1004 if (in_fd.get() < 0) {
1005 PLOG(WARNING) << "Could not open profile " << system_profile;
1006 return false;
1007 }
1008 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001009 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001010 return false;
1011 }
1012
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001013 // As a security measure we want to write the profile information with the reduced capabilities
1014 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001015 pid_t pid = fork();
1016 if (pid == 0) {
1017 /* child -- drop privileges before continuing */
1018 drop_capabilities(packageUid);
1019
1020 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1021 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001022 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001023 }
1024 // This implies that the app owning this profile is running
1025 // (and has acquired the lock).
1026 //
1027 // The app never acquires the lock for the reference profiles of primary apks.
1028 // Only dex2oat from installd will do that. Since installd is single threaded
1029 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001030 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001031 return false;
1032 }
1033
1034 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1035 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001036 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001037 }
1038
1039 // Copy over data.
1040 static constexpr size_t kBufferSize = 4 * 1024;
1041 char buffer[kBufferSize];
1042 while (true) {
1043 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1044 if (bytes == 0) {
1045 break;
1046 }
1047 write(out_fd.get(), buffer, bytes);
1048 }
1049 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001050 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001051 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001052 // Use _exit since we don't want to run the global destructors in the child.
1053 // b/62597429
1054 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001055 }
1056 /* parent */
1057 int return_code = wait_child(pid);
1058 return return_code == 0;
1059}
1060
Jeff Sharkey90aff262016-12-12 14:28:24 -07001061static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1062 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1063 if (EndsWith(oat_path, ".dex")) {
1064 std::string new_path = oat_path;
1065 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001066 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001067 return new_path;
1068 }
1069
1070 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1071 // case (where the base name will have an extension for the B artifact).
1072 size_t odex_pos = oat_path.rfind(".odex");
1073 if (odex_pos != std::string::npos) {
1074 std::string new_path = oat_path;
1075 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1076 CHECK_NE(new_path.find(new_ext), std::string::npos);
1077 return new_path;
1078 }
1079
1080 // Don't know how to handle this.
1081 return "";
1082}
1083
1084// Translate the given oat path to an art (app image) path. An empty string
1085// denotes an error.
1086static std::string create_image_filename(const std::string& oat_path) {
1087 return replace_file_extension(oat_path, ".art");
1088}
1089
1090// Translate the given oat path to a vdex path. An empty string denotes an error.
1091static std::string create_vdex_filename(const std::string& oat_path) {
1092 return replace_file_extension(oat_path, ".vdex");
1093}
1094
Jeff Sharkey90aff262016-12-12 14:28:24 -07001095static int open_output_file(const char* file_name, bool recreate, int permissions) {
1096 int flags = O_RDWR | O_CREAT;
1097 if (recreate) {
1098 if (unlink(file_name) < 0) {
1099 if (errno != ENOENT) {
1100 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1101 }
1102 }
1103 flags |= O_EXCL;
1104 }
1105 return open(file_name, flags, permissions);
1106}
1107
Calin Juravle2289c0a2017-02-15 12:44:14 -08001108static bool set_permissions_and_ownership(
1109 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1110 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1111 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001112 if (fchmod(fd,
1113 S_IRUSR|S_IWUSR|S_IRGRP |
1114 (is_public ? S_IROTH : 0)) < 0) {
1115 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1116 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001117 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1119 return false;
1120 }
1121 return true;
1122}
1123
1124static bool IsOutputDalvikCache(const char* oat_dir) {
1125 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1126 // into '!'. Play it safe by handling it both.
1127 // TODO: ensure we never get null.
1128 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1129 return oat_dir == nullptr || oat_dir[0] == '!';
1130}
1131
Calin Juravled23dee72017-07-06 16:29:11 -07001132// Best-effort check whether we can fit the the path into our buffers.
1133// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1134// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1135// extension to the cache path (5 bytes).
1136// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1137static bool validate_dex_path_size(const std::string& dex_path) {
1138 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1139 LOG(ERROR) << "dex_path too long: " << dex_path;
1140 return false;
1141 }
1142 return true;
1143}
1144
Jeff Sharkey90aff262016-12-12 14:28:24 -07001145static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001146 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001147 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001148 return false;
1149 }
1150
1151 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001152 // Oat dirs for secondary dex files are already validated.
1153 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001154 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1155 return false;
1156 }
1157 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1158 return false;
1159 }
1160 } else {
1161 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1162 return false;
1163 }
1164 }
1165 return true;
1166}
1167
1168// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1169// on destruction. It will also run the given cleanup (unless told not to) after closing.
1170//
1171// Usage example:
1172//
Calin Juravle7a570e82017-01-14 16:23:30 -08001173// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001174// [name]() {
1175// unlink(name.c_str());
1176// });
1177// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1178// wrapper if captured as a reference.
1179//
1180// if (file.get() == -1) {
1181// // Error opening...
1182// }
1183//
1184// ...
1185// if (error) {
1186// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1187// // and delete the file (after the fd is closed).
1188// return -1;
1189// }
1190//
1191// (Success case)
1192// file.SetCleanup(false);
1193// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1194// // (leaving the file around; after the fd is closed).
1195//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001196class Dex2oatFileWrapper {
1197 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001198 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001199 }
1200
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1202 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1203
1204 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1205 value_ = other.value_;
1206 cleanup_ = other.cleanup_;
1207 do_cleanup_ = other.do_cleanup_;
1208 auto_close_ = other.auto_close_;
1209 other.release();
1210 }
1211
1212 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1213 value_ = other.value_;
1214 cleanup_ = other.cleanup_;
1215 do_cleanup_ = other.do_cleanup_;
1216 auto_close_ = other.auto_close_;
1217 other.release();
1218 return *this;
1219 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001220
1221 ~Dex2oatFileWrapper() {
1222 reset(-1);
1223 }
1224
1225 int get() {
1226 return value_;
1227 }
1228
1229 void SetCleanup(bool cleanup) {
1230 do_cleanup_ = cleanup;
1231 }
1232
1233 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001234 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001235 close(value_);
1236 }
1237 if (do_cleanup_ && cleanup_ != nullptr) {
1238 cleanup_();
1239 }
1240
1241 value_ = new_value;
1242 }
1243
Calin Juravle7a570e82017-01-14 16:23:30 -08001244 void reset(int new_value, std::function<void ()> new_cleanup) {
1245 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001246 close(value_);
1247 }
1248 if (do_cleanup_ && cleanup_ != nullptr) {
1249 cleanup_();
1250 }
1251
1252 value_ = new_value;
1253 cleanup_ = new_cleanup;
1254 }
1255
Calin Juravle7a570e82017-01-14 16:23:30 -08001256 void DisableAutoClose() {
1257 auto_close_ = false;
1258 }
1259
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001261 void release() {
1262 value_ = -1;
1263 do_cleanup_ = false;
1264 cleanup_ = nullptr;
1265 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001266 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001267 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001268 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001269 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001270};
1271
Calin Juravle7a570e82017-01-14 16:23:30 -08001272// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001273Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1274 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001275
1276 // We don't create an image for secondary dex files.
1277 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001278 return Dex2oatFileWrapper();
1279 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001280
Calin Juravle7a570e82017-01-14 16:23:30 -08001281 const std::string image_path = create_image_filename(out_oat_path);
1282 if (image_path.empty()) {
1283 // Happens when the out_oat_path has an unknown extension.
1284 return Dex2oatFileWrapper();
1285 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001286
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001287 // In case there is a stale image, remove it now. Ignore any error.
1288 unlink(image_path.c_str());
1289
1290 // Not enabled, exit.
1291 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001292 return Dex2oatFileWrapper();
1293 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001294 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1295 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 return Dex2oatFileWrapper();
1297 }
1298 // Recreate is true since we do not want to modify a mapped image. If the app is
1299 // already running and we modify the image file, it can cause crashes (b/27493510).
1300 Dex2oatFileWrapper wrapper_fd(
1301 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1302 [image_path]() { unlink(image_path.c_str()); });
1303 if (wrapper_fd.get() < 0) {
1304 // Could not create application image file. Go on since we can compile without it.
1305 LOG(ERROR) << "installd could not create '" << image_path
1306 << "' for image file during dexopt";
1307 // If we have a valid image file path but no image fd, explicitly erase the image file.
1308 if (unlink(image_path.c_str()) < 0) {
1309 if (errno != ENOENT) {
1310 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1311 }
1312 }
1313 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001314 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001315 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1316 wrapper_fd.reset(-1);
1317 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001318
Calin Juravle7a570e82017-01-14 16:23:30 -08001319 return wrapper_fd;
1320}
1321
1322// Creates the dexopt swap file if necessary and return its fd.
1323// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001324unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001325 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001326 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001327 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001328 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001329 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001330 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001331 if (swap_fd.get() < 0) {
1332 // Could not create swap file. Optimistically go on and hope that we can compile
1333 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001334 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001335 } else {
1336 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001337 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001338 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1339 }
1340 }
1341 return swap_fd;
1342}
1343
1344// Opens the reference profiles if needed.
1345// 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 -08001346Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001347 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001348 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001349 // If we are not profile guided compilation, or we are compiling system server
1350 // do not bother to open the profiles; we won't be using them.
1351 if (!profile_guided || (pkgname[0] == '*')) {
1352 return Dex2oatFileWrapper();
1353 }
1354
1355 // If this is a secondary dex path which is public do not open the profile.
1356 // We cannot compile public secondary dex paths with profiles. That's because
1357 // it will expose how the dex files are used by their owner.
1358 //
1359 // Note that the PackageManager is responsible to set the is_public flag for
1360 // primary apks and we do not check it here. In some cases, e.g. when
1361 // compiling with a public profile from the .dm file the PackageManager will
1362 // set is_public toghether with the profile guided compilation.
1363 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001364 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001365 }
Calin Juravle114f0812017-03-08 19:05:07 -08001366
1367 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001368 std::string location;
1369 if (is_secondary_dex) {
1370 location = dex_path;
1371 } else {
1372 if (profile_name == nullptr) {
1373 // This path is taken for system server re-compilation lunched from ZygoteInit.
1374 return Dex2oatFileWrapper();
1375 } else {
1376 location = profile_name;
1377 }
1378 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001379 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1380 is_secondary_dex);
1381 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1382 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001383 };
1384 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001385}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001386
Calin Juravle7a570e82017-01-14 16:23:30 -08001387// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1388// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001389bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001390 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001391 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001392 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1393 CHECK(in_vdex_wrapper_fd != nullptr);
1394 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001395 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1396 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001397 char in_odex_path[PKG_PATH_MAX];
1398 int dexopt_action = abs(dexopt_needed);
1399 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001400 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001401
1402 // Infer the name of the output VDEX.
1403 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1404 if (out_vdex_path_str.empty()) {
1405 return false;
1406 }
1407
1408 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001409 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001410 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1411 const char* path = nullptr;
1412 if (is_odex_location) {
1413 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1414 path = in_odex_path;
1415 } else {
1416 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001417 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001418 }
1419 } else {
1420 path = out_oat_path;
1421 }
1422 in_vdex_path_str = create_vdex_filename(path);
1423 if (in_vdex_path_str.empty()) {
1424 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001425 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001426 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001427 // We can update in place when all these conditions are met:
1428 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1429 // on /system typically cannot be updated in place).
1430 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1431 // cannot be currently used by a running process.
1432 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1433 // different vdex files to operate.
1434 update_vdex_in_place =
1435 (in_vdex_path_str == out_vdex_path_str) &&
1436 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1437 !profile_guided;
1438 if (update_vdex_in_place) {
1439 // Open the file read-write to be able to update it.
1440 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1441 if (in_vdex_wrapper_fd->get() == -1) {
1442 // If we failed to open the file, we cannot update it in place.
1443 update_vdex_in_place = false;
1444 }
1445 } else {
1446 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1447 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001448 }
1449
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001450 // If we are updating the vdex in place, we do not need to recreate a vdex,
1451 // and can use the same existing one.
1452 if (update_vdex_in_place) {
1453 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1454 // have bogus stale vdex files.
1455 out_vdex_wrapper_fd->reset(
1456 in_vdex_wrapper_fd->get(),
1457 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1458 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1459 // wrapper).
1460 in_vdex_wrapper_fd->DisableAutoClose();
1461 } else {
1462 out_vdex_wrapper_fd->reset(
1463 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1464 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1465 if (out_vdex_wrapper_fd->get() < 0) {
1466 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1467 return false;
1468 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001469 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001470 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001471 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001472 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1473 return false;
1474 }
1475
1476 // If we got here we successfully opened the vdex files.
1477 return true;
1478}
1479
1480// Opens the output oat file for the given apk.
1481// If successful it stores the output path into out_oat_path and returns true.
1482Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001483 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1484 char* out_oat_path) {
1485 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001486 return Dex2oatFileWrapper();
1487 }
1488 const std::string out_oat_path_str(out_oat_path);
1489 Dex2oatFileWrapper wrapper_fd(
1490 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1491 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1492 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001493 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001494 } else if (!set_permissions_and_ownership(
1495 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001496 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1497 wrapper_fd.reset(-1);
1498 }
1499 return wrapper_fd;
1500}
1501
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001502// Creates RDONLY fds for oat and vdex files, if exist.
1503// Returns false if it fails to create oat out path for the given apk path.
1504// Note that the method returns true even if the files could not be opened.
1505bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1506 const std::string& oat_dir,
1507 const std::string& instruction_set,
1508 bool is_secondary_dex,
1509 unique_fd* oat_file_fd,
1510 unique_fd* vdex_file_fd) {
1511 char oat_path[PKG_PATH_MAX];
1512 if (!create_oat_out_path(apk_path.c_str(),
1513 instruction_set.c_str(),
1514 oat_dir.c_str(),
1515 is_secondary_dex,
1516 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001517 LOG(ERROR) << "Could not create oat out path for "
1518 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001519 return false;
1520 }
1521 oat_file_fd->reset(open(oat_path, O_RDONLY));
1522 if (oat_file_fd->get() < 0) {
1523 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1524 }
1525
1526 std::string vdex_filename = create_vdex_filename(oat_path);
1527 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1528 if (vdex_file_fd->get() < 0) {
1529 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1530 }
1531
1532 return true;
1533}
1534
Calin Juravle7a570e82017-01-14 16:23:30 -08001535// Updates the access times of out_oat_path based on those from apk_path.
1536void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1537 struct stat input_stat;
1538 memset(&input_stat, 0, sizeof(input_stat));
1539 if (stat(apk_path, &input_stat) != 0) {
1540 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1541 return;
1542 }
1543
1544 struct utimbuf ut;
1545 ut.actime = input_stat.st_atime;
1546 ut.modtime = input_stat.st_mtime;
1547 if (utime(out_oat_path, &ut) != 0) {
1548 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1549 }
1550}
1551
Calin Juravle80a21252017-01-17 14:43:25 -08001552// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001553// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1554// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1555// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001556class RunDexoptAnalyzer : public ExecVHelper {
1557 public:
1558 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001559 int vdex_fd,
1560 int oat_fd,
1561 int zip_fd,
1562 const std::string& instruction_set,
1563 const std::string& compiler_filter,
1564 bool profile_was_updated,
1565 bool downgrade,
1566 const char* class_loader_context,
1567 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001568 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001569
1570 // We always run the analyzer in the background job.
1571 const char* dexoptanalyzer_bin = select_execution_binary(
1572 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001573
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001574 std::string dex_file_arg = "--dex-file=" + dex_file;
1575 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1576 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1577 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1578 std::string isa_arg = "--isa=" + instruction_set;
1579 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1580 const char* assume_profile_changed = "--assume-profile-changed";
1581 const char* downgrade_flag = "--downgrade";
1582 std::string class_loader_context_arg = "--class-loader-context=";
1583 if (class_loader_context != nullptr) {
1584 class_loader_context_arg += class_loader_context;
1585 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001586 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1587 if (!class_loader_context_fds.empty()) {
1588 class_loader_context_fds_arg += class_loader_context_fds;
1589 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001590
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001591 // program name, dex file, isa, filter
1592 AddArg(dex_file_arg);
1593 AddArg(isa_arg);
1594 AddArg(compiler_filter_arg);
1595 if (oat_fd >= 0) {
1596 AddArg(oat_fd_arg);
1597 }
1598 if (vdex_fd >= 0) {
1599 AddArg(vdex_fd_arg);
1600 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001601 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001602 if (profile_was_updated) {
1603 AddArg(assume_profile_changed);
1604 }
1605 if (downgrade) {
1606 AddArg(downgrade_flag);
1607 }
1608 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001609 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001610 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001611 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001612 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001613 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001614
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001615 PrepareArgs(dexoptanalyzer_bin);
1616 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001617
1618 // Dexoptanalyzer mode which flattens the given class loader context and
1619 // prints a list of its dex files in that flattened order.
1620 RunDexoptAnalyzer(const char* class_loader_context) {
1621 CHECK(class_loader_context != nullptr);
1622
1623 // We always run the analyzer in the background job.
1624 const char* dexoptanalyzer_bin = select_execution_binary(
1625 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1626
1627 AddArg("--flatten-class-loader-context");
1628 AddArg(std::string("--class-loader-context=") + class_loader_context);
1629 PrepareArgs(dexoptanalyzer_bin);
1630 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001631};
Calin Juravle80a21252017-01-17 14:43:25 -08001632
1633// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001634static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001635 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001636 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001637 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001638 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001639 return false;
1640 }
Calin Juravle114f0812017-03-08 19:05:07 -08001641 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001642
Calin Juravle80a21252017-01-17 14:43:25 -08001643 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001644 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1645 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001646 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001647 return false;
1648 }
1649
1650 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001651 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001652
Calin Juravle7d765462017-09-04 15:57:10 -07001653 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001654 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001655 return false;
1656 }
1657
1658 return true;
1659}
1660
Calin Juravle7d765462017-09-04 15:57:10 -07001661// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1662// secondary dex files. This return codes are returned by the child process created for
1663// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001664
Andreas Gampe194fe422018-02-28 20:16:19 -08001665enum DexoptAnalyzerSkipCodes {
1666 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001667 // Specific errors are encoded in the name.
1668 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1669 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1670 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1671 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1672 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001673 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001674 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001675};
Calin Juravle7d765462017-09-04 15:57:10 -07001676
1677// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001678// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1679// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001680// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1681// of dexoptanalyzer.
1682static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001683 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001684 // The result values are defined in dexoptanalyzer.
1685 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001686 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001687 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001688 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001689 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001690 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001691 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001692 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001693 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001694 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1695 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001696 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1697 " Expected odex file status for secondary dex %s"
1698 " : dexoptanalyzer result=%d",
1699 dex_path.c_str(),
1700 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001701 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001702 }
1703
1704 // Use a second switch for enum switch-case analysis.
1705 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001706 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001707 // If the file does not exist there's no need for dexopt.
1708 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1709 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001710
1711 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1712 *error_msg = "Dexoptanalyzer path validation failed";
1713 return false;
1714 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1715 *error_msg = "Dexoptanalyzer open zip failed";
1716 return false;
1717 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1718 *error_msg = "Dexoptanalyzer dir preparation failed";
1719 return false;
1720 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1721 *error_msg = "Dexoptanalyzer open output failed";
1722 return false;
1723 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1724 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001725 return false;
1726 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001727
1728 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1729 dex_path.c_str(),
1730 result);
1731 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001732}
1733
Calin Juravle7d765462017-09-04 15:57:10 -07001734enum SecondaryDexAccess {
1735 kSecondaryDexAccessReadOk = 0,
1736 kSecondaryDexAccessDoesNotExist = 1,
1737 kSecondaryDexAccessPermissionError = 2,
1738 kSecondaryDexAccessIOError = 3
1739};
1740
1741static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1742 // Check if the path exists and can be read. If not, there's nothing to do.
1743 if (access(dex_path.c_str(), R_OK) == 0) {
1744 return kSecondaryDexAccessReadOk;
1745 } else {
1746 if (errno == ENOENT) {
1747 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1748 return kSecondaryDexAccessDoesNotExist;
1749 } else {
1750 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1751 return errno == EACCES
1752 ? kSecondaryDexAccessPermissionError
1753 : kSecondaryDexAccessIOError;
1754 }
1755 }
1756}
1757
1758static bool is_file_public(const std::string& filename) {
1759 struct stat file_stat;
1760 if (stat(filename.c_str(), &file_stat) == 0) {
1761 return (file_stat.st_mode & S_IROTH) != 0;
1762 }
1763 return false;
1764}
1765
1766// Create the oat file structure for the secondary dex 'dex_path' and assign
1767// the individual path component to the 'out_' parameters.
1768static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001769 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001770 size_t dirIndex = dex_path.rfind('/');
1771 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001772 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001773 return false;
1774 }
1775 // TODO(calin): we have similar computations in at lest 3 other places
1776 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1777 // using string append.
1778 std::string apk_dir = dex_path.substr(0, dirIndex);
1779 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1780 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1781
1782 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1783 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001784 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001785 return false;
1786 }
1787 return true;
1788}
1789
1790// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1791// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001792static bool validate_dexopt_storage_flags(int dexopt_flags,
1793 int* out_storage_flag,
1794 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001795 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1796 *out_storage_flag = FLAG_STORAGE_CE;
1797 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001798 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001799 return false;
1800 }
1801 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1802 *out_storage_flag = FLAG_STORAGE_DE;
1803 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001804 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001805 return false;
1806 }
1807 return true;
1808}
1809
David Brazdil4f6027a2019-03-19 11:44:21 +00001810static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1811 /* out */ std::vector<std::string>* context_dex_paths) {
1812 if (class_loader_context == nullptr) {
1813 return true;
1814 }
1815
1816 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1817
1818 // Pipe to get the hash result back from our child process.
1819 unique_fd pipe_read, pipe_write;
1820 if (!Pipe(&pipe_read, &pipe_write)) {
1821 PLOG(ERROR) << "Failed to create pipe";
1822 return false;
1823 }
1824
1825 pid_t pid = fork();
1826 if (pid == 0) {
1827 // child -- drop privileges before continuing.
1828 drop_capabilities(uid);
1829
1830 // Route stdout to `pipe_write`
1831 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1832 pipe_write.reset();
1833 pipe_read.reset();
1834
1835 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1836 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1837 }
1838
1839 /* parent */
1840 pipe_write.reset();
1841
1842 std::string str_dex_paths;
1843 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1844 PLOG(ERROR) << "Failed to read from pipe";
1845 return false;
1846 }
1847 pipe_read.reset();
1848
1849 int return_code = wait_child(pid);
1850 if (!WIFEXITED(return_code)) {
1851 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1852 return false;
1853 }
1854
1855 constexpr int kFlattenClassLoaderContextSuccess = 50;
1856 return_code = WEXITSTATUS(return_code);
1857 if (return_code != kFlattenClassLoaderContextSuccess) {
1858 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1859 return false;
1860 }
1861
1862 if (!str_dex_paths.empty()) {
1863 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1864 }
1865 return true;
1866}
1867
1868static int open_dex_paths(const std::vector<std::string>& dex_paths,
1869 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1870 for (const std::string& dex_path : dex_paths) {
1871 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1872 if (zip_fds->back().get() < 0) {
1873 *error_msg = StringPrintf(
1874 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1875 if (errno == ENOENT) {
1876 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1877 } else {
1878 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1879 }
1880 }
1881 }
1882 return 0;
1883}
1884
1885static std::string join_fds(const std::vector<unique_fd>& fds) {
1886 std::stringstream ss;
1887 bool is_first = true;
1888 for (const unique_fd& fd : fds) {
1889 if (is_first) {
1890 is_first = false;
1891 } else {
1892 ss << ":";
1893 }
1894 ss << fd.get();
1895 }
1896 return ss.str();
1897}
1898
Calin Juravlec9eab382017-01-25 01:17:17 -08001899// 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 -08001900// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1901// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001902// When returning true, the output parameters will be:
1903// - is_public_out: whether or not the oat file should not be made public
1904// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1905// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001906static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001907 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001908 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001909 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001910 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001911 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001912 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001913 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1914 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001915 return false;
1916 }
Calin Juravle7d765462017-09-04 15:57:10 -07001917 // Compute the oat dir as it's not easy to extract it from the child computation.
1918 char oat_path[PKG_PATH_MAX];
1919 char oat_dir[PKG_PATH_MAX];
1920 char oat_isa_dir[PKG_PATH_MAX];
1921 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001922 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1923 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001924 return false;
1925 }
Calin Juravle7d765462017-09-04 15:57:10 -07001926 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001927
Calin Juravle80a21252017-01-17 14:43:25 -08001928 pid_t pid = fork();
1929 if (pid == 0) {
1930 // child -- drop privileges before continuing.
1931 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001932
1933 // Validate the path structure.
1934 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1935 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001936 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001937 }
1938
1939 // Open the dex file.
1940 unique_fd zip_fd;
1941 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1942 if (zip_fd.get() < 0) {
1943 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001944 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001945 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001946 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001947 }
1948 }
1949
David Brazdil4f6027a2019-03-19 11:44:21 +00001950 // Open class loader context dex files.
1951 std::vector<unique_fd> context_zip_fds;
1952 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1953 if (open_dex_paths_rc != 0) {
1954 _exit(open_dex_paths_rc);
1955 }
1956
Calin Juravle7d765462017-09-04 15:57:10 -07001957 // Prepare the oat directories.
1958 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001959 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001960 }
1961
1962 // Open the vdex/oat files if any.
1963 unique_fd oat_file_fd;
1964 unique_fd vdex_file_fd;
1965 if (!maybe_open_oat_and_vdex_file(dex_path,
1966 *oat_dir_out,
1967 instruction_set,
1968 true /* is_secondary_dex */,
1969 &oat_file_fd,
1970 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001971 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001972 }
1973
1974 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001975 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1976 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001977
1978 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001979 // Note that we do not do it before the fork since opening the files is required to happen
1980 // after forking.
1981 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1982 vdex_file_fd.get(),
1983 oat_file_fd.get(),
1984 zip_fd.get(),
1985 instruction_set,
1986 compiler_filter, profile_was_updated,
1987 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001988 class_loader_context,
1989 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001990 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001991 }
1992
1993 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001994 int result = wait_child(pid);
1995 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001996 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1997 dex_path.c_str(),
1998 result);
1999 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002000 return false;
2001 }
2002 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002003 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002004 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2005 result,
2006 dexopt_needed_out,
2007 error_msg);
2008 if (!success) {
2009 LOG(ERROR) << *error_msg;
2010 }
Calin Juravle7d765462017-09-04 15:57:10 -07002011
2012 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2013
Calin Juravle80a21252017-01-17 14:43:25 -08002014 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002015 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2016 // makes the code simpler; force compilation is only needed during tests).
2017 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002018 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002019 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002020 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2021 }
2022
Calin Juravle7d765462017-09-04 15:57:10 -07002023 // Check if we should make the oat file public.
2024 // Note that if the dex file is not public the compiled code cannot be made public.
2025 // It is ok to check this flag outside in the parent process.
2026 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2027
Calin Juravle80a21252017-01-17 14:43:25 -08002028 return success;
2029}
2030
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002031static std::string format_dexopt_error(int status, const char* dex_path) {
2032 if (WIFEXITED(status)) {
2033 int int_code = WEXITSTATUS(status);
2034 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2035 if (code_name != nullptr) {
2036 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2037 }
2038 }
2039 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002040}
2041
Calin Juravlec9eab382017-01-25 01:17:17 -08002042int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002043 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002044 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002045 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002046 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002047 CHECK(pkgname != nullptr);
2048 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002049 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002050 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2051 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002052
Calin Juravled23dee72017-07-06 16:29:11 -07002053 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002054 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002055 return -1;
2056 }
2057
2058 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002059 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2060 class_loader_context);
2061 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002062 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002063 }
2064
Calin Juravleebc8a792017-04-04 20:21:05 -07002065 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002066 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2067 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2068 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002069 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002070 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002071 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002072 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002073 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002074
2075 // Check if we're dealing with a secondary dex file and if we need to compile it.
2076 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002077 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002078 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002079 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2080 *error_msg = "Failed acquiring context dex paths";
2081 return -1; // We had an error, logged in the process method.
2082 }
2083
Calin Juravlec9eab382017-01-25 01:17:17 -08002084 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002085 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002086 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002087 oat_dir = oat_dir_str.c_str();
2088 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2089 return 0; // Nothing to do, report success.
2090 }
2091 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002092 if (error_msg->empty()) { // TODO: Make this a CHECK.
2093 *error_msg = "Failed processing secondary.";
2094 }
Calin Juravle80a21252017-01-17 14:43:25 -08002095 return -1; // We had an error, logged in the process method.
2096 }
2097 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002098 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002099 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002100 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2101 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2102 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002103
2104 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002105 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002106 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002107 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2108 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002109 return -1;
2110 }
2111
David Brazdil4f6027a2019-03-19 11:44:21 +00002112 // Open class loader context dex files.
2113 std::vector<unique_fd> context_input_fds;
2114 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2115 LOG(ERROR) << *error_msg;
2116 return -1;
2117 }
2118
Calin Juravle7a570e82017-01-14 16:23:30 -08002119 // Create the output OAT file.
2120 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002121 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002122 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002123 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002124 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002125 return -1;
2126 }
2127
2128 // Open vdex files.
2129 Dex2oatFileWrapper in_vdex_fd;
2130 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002131 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2132 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002133 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002134 return -1;
2135 }
2136
Calin Juravlecb556e32017-04-04 20:22:50 -07002137 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2138 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2139 // fully inherit their parent context).
2140 // Note that for primary apk the oat files are created before, in a separate installd
2141 // call which also does the restorecon. TODO(calin): unify the paths.
2142 if (is_secondary_dex) {
2143 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2144 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002145 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2146 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002147 return -1;
2148 }
2149 }
2150
Jeff Sharkey90aff262016-12-12 14:28:24 -07002151 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002152 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002153
Calin Juravle7a570e82017-01-14 16:23:30 -08002154 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002155 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002156 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002157
liulvping61907742018-08-21 09:36:52 +08002158 if (reference_profile_fd.get() == -1) {
2159 // We don't create an app image without reference profile since there is no speedup from
2160 // loading it in that case and instead will be a small overhead.
2161 generate_app_image = false;
2162 }
2163
2164 // Create the app image file if needed.
2165 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2166 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2167
Calin Juravle62c5a372018-02-01 17:03:23 +00002168 unique_fd dex_metadata_fd;
2169 if (dex_metadata_path != nullptr) {
2170 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2171 if (dex_metadata_fd.get() < 0) {
2172 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2173 }
2174 }
2175
Andreas Gampe023b2242018-02-28 16:03:25 -08002176 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002177
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002178 RunDex2Oat runner(input_fd.get(),
2179 out_oat_fd.get(),
2180 in_vdex_fd.get(),
2181 out_vdex_fd.get(),
2182 image_fd.get(),
2183 dex_path,
2184 out_oat_path,
2185 swap_fd.get(),
2186 instruction_set,
2187 compiler_filter,
2188 debuggable,
2189 boot_complete,
2190 background_job_compile,
2191 reference_profile_fd.get(),
2192 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002193 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002194 target_sdk_version,
2195 enable_hidden_api_checks,
2196 generate_compact_dex,
2197 dex_metadata_fd.get(),
2198 compilation_reason);
2199
Jeff Sharkey90aff262016-12-12 14:28:24 -07002200 pid_t pid = fork();
2201 if (pid == 0) {
2202 /* child -- drop privileges before continuing */
2203 drop_capabilities(uid);
2204
Richard Uhler76cc0272016-12-08 10:46:35 +00002205 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002206 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002207 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002208 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002209 }
2210
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002211 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002212 } else {
2213 int res = wait_child(pid);
2214 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002215 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002216 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002217 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2218 << std::hex << std::setw(4) << res << ", process failed";
2219 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002220 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002221 }
2222 }
2223
Calin Juravlec9eab382017-01-25 01:17:17 -08002224 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002225
2226 // We've been successful, don't delete output.
2227 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002228 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002229 image_fd.SetCleanup(false);
2230 reference_profile_fd.SetCleanup(false);
2231
2232 return 0;
2233}
2234
Calin Juravlec9eab382017-01-25 01:17:17 -08002235// Try to remove the given directory. Log an error if the directory exists
2236// and is empty but could not be removed.
2237static bool rmdir_if_empty(const char* dir) {
2238 if (rmdir(dir) == 0) {
2239 return true;
2240 }
2241 if (errno == ENOENT || errno == ENOTEMPTY) {
2242 return true;
2243 }
2244 PLOG(ERROR) << "Failed to remove dir: " << dir;
2245 return false;
2246}
2247
2248// Try to unlink the given file. Log an error if the file exists and could not
2249// be unlinked.
2250static bool unlink_if_exists(const std::string& file) {
2251 if (unlink(file.c_str()) == 0) {
2252 return true;
2253 }
2254 if (errno == ENOENT) {
2255 return true;
2256
2257 }
2258 PLOG(ERROR) << "Could not unlink: " << file;
2259 return false;
2260}
2261
Calin Juravle7d765462017-09-04 15:57:10 -07002262enum ReconcileSecondaryDexResult {
2263 kReconcileSecondaryDexExists = 0,
2264 kReconcileSecondaryDexCleanedUp = 1,
2265 kReconcileSecondaryDexValidationError = 2,
2266 kReconcileSecondaryDexCleanUpError = 3,
2267 kReconcileSecondaryDexAccessIOError = 4,
2268};
Calin Juravlec9eab382017-01-25 01:17:17 -08002269
2270// Reconcile the secondary dex 'dex_path' and its generated oat files.
2271// Return true if all the parameters are valid and the secondary dex file was
2272// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2273// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2274// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2275// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2276// Return false if there were errors during processing. In this case
2277// out_secondary_dex_exists will be set to false.
2278bool reconcile_secondary_dex_file(const std::string& dex_path,
2279 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002280 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002281 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002282 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002283 if (isas.size() == 0) {
2284 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2285 return false;
2286 }
2287
Calin Juravle7d765462017-09-04 15:57:10 -07002288 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2289 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2290 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002291 return false;
2292 }
2293
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002294 // As a security measure we want to unlink art artifacts with the reduced capabilities
2295 // of the package user id. So we fork and drop capabilities in the child.
2296 pid_t pid = fork();
2297 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002298 /* child -- drop privileges before continuing */
2299 drop_capabilities(uid);
2300
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002301 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002302 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002303 uid, storage_flag)) {
2304 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2305 _exit(kReconcileSecondaryDexValidationError);
2306 }
2307
2308 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2309 switch (access_check) {
2310 case kSecondaryDexAccessDoesNotExist:
2311 // File does not exist. Proceed with cleaning.
2312 break;
2313 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2314 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2315 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2316 default:
2317 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2318 _exit(kReconcileSecondaryDexValidationError);
2319 }
2320
2321 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002322 char oat_path[PKG_PATH_MAX];
2323 char oat_dir[PKG_PATH_MAX];
2324 char oat_isa_dir[PKG_PATH_MAX];
2325 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002326 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002327 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002328 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002329 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2330 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002331 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002332 }
Calin Juravle51314092017-05-18 15:33:05 -07002333
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002334 // Delete oat/vdex/art files.
2335 result = unlink_if_exists(oat_path) && result;
2336 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2337 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002338
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002339 // Delete profiles.
2340 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002341 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002342 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002343 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002344 result = unlink_if_exists(current_profile) && result;
2345 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002346
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002347 // We upgraded once the location of current profile for secondary dex files.
2348 // Check for any previous left-overs and remove them as well.
2349 std::string old_current_profile = dex_path + ".prof";
2350 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002351
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002352 // Try removing the directories as well, they might be empty.
2353 result = rmdir_if_empty(oat_isa_dir) && result;
2354 result = rmdir_if_empty(oat_dir) && result;
2355 }
Calin Juravle7d765462017-09-04 15:57:10 -07002356 if (!result) {
2357 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2358 }
2359 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002360 }
2361
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002362 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002363 if (!WIFEXITED(return_code)) {
2364 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2365 } else {
2366 return_code = WEXITSTATUS(return_code);
2367 }
2368
2369 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2370
2371 switch (return_code) {
2372 case kReconcileSecondaryDexCleanedUp:
2373 case kReconcileSecondaryDexValidationError:
2374 // If we couldn't validate assume the dex file does not exist.
2375 // This will purge the entry from the PM records.
2376 *out_secondary_dex_exists = false;
2377 return true;
2378 case kReconcileSecondaryDexExists:
2379 *out_secondary_dex_exists = true;
2380 return true;
2381 case kReconcileSecondaryDexAccessIOError:
2382 // We had an access IO error.
2383 // Return false so that we can try again.
2384 // The value of out_secondary_dex_exists does not matter in this case and by convention
2385 // is set to false.
2386 *out_secondary_dex_exists = false;
2387 return false;
2388 default:
2389 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2390 *out_secondary_dex_exists = false;
2391 return false;
2392 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002393}
2394
Alan Stokesa25d90c2017-10-16 10:56:00 +01002395// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2396// Returns true if all parameters are valid and the hash successfully computed and stored in
2397// out_secondary_dex_hash.
2398// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2399// the app.
2400// For any other errors (e.g. if any of the parameters are invalid) returns false.
2401bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002402 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002403 std::vector<uint8_t>* out_secondary_dex_hash) {
2404 out_secondary_dex_hash->clear();
2405
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002406 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002407
2408 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2409 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2410 << storage_flag;
2411 return false;
2412 }
2413
2414 // Pipe to get the hash result back from our child process.
2415 unique_fd pipe_read, pipe_write;
2416 if (!Pipe(&pipe_read, &pipe_write)) {
2417 PLOG(ERROR) << "Failed to create pipe";
2418 return false;
2419 }
2420
2421 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2422 // access data the app itself can access.
2423 pid_t pid = fork();
2424 if (pid == 0) {
2425 // child -- drop privileges before continuing
2426 drop_capabilities(uid);
2427 pipe_read.reset();
2428
2429 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2430 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002431 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002432 }
2433
2434 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2435 if (fd == -1) {
2436 if (errno == EACCES || errno == ENOENT) {
2437 // Not treated as an error.
2438 _exit(0);
2439 }
2440 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002441 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002442 }
2443
2444 SHA256_CTX ctx;
2445 SHA256_Init(&ctx);
2446
2447 std::vector<uint8_t> buffer(65536);
2448 while (true) {
2449 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2450 if (bytes_read == 0) {
2451 break;
2452 } else if (bytes_read == -1) {
2453 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002454 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002455 }
2456
2457 SHA256_Update(&ctx, buffer.data(), bytes_read);
2458 }
2459
2460 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2461 SHA256_Final(hash.data(), &ctx);
2462 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002463 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002464 }
2465
2466 _exit(0);
2467 }
2468
2469 // parent
2470 pipe_write.reset();
2471
2472 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2473 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2474 out_secondary_dex_hash->clear();
2475 }
2476 return wait_child(pid) == 0;
2477}
2478
Jeff Sharkey90aff262016-12-12 14:28:24 -07002479// Helper for move_ab, so that we can have common failure-case cleanup.
2480static bool unlink_and_rename(const char* from, const char* to) {
2481 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2482 // return a failure.
2483 struct stat s;
2484 if (stat(to, &s) == 0) {
2485 if (!S_ISREG(s.st_mode)) {
2486 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2487 return false;
2488 }
2489 if (unlink(to) != 0) {
2490 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2491 return false;
2492 }
2493 } else {
2494 // This may be a permission problem. We could investigate the error code, but we'll just
2495 // let the rename failure do the work for us.
2496 }
2497
2498 // Try to rename "to" to "from."
2499 if (rename(from, to) != 0) {
2500 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2501 return false;
2502 }
2503 return true;
2504}
2505
2506// Move/rename a B artifact (from) to an A artifact (to).
2507static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2508 // Check whether B exists.
2509 {
2510 struct stat s;
2511 if (stat(b_path.c_str(), &s) != 0) {
2512 // Silently ignore for now. The service calling this isn't smart enough to understand
2513 // lack of artifacts at the moment.
2514 return false;
2515 }
2516 if (!S_ISREG(s.st_mode)) {
2517 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2518 // Try to unlink, but swallow errors.
2519 unlink(b_path.c_str());
2520 return false;
2521 }
2522 }
2523
2524 // Rename B to A.
2525 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2526 // Delete the b_path so we don't try again (or fail earlier).
2527 if (unlink(b_path.c_str()) != 0) {
2528 PLOG(ERROR) << "Could not unlink " << b_path;
2529 }
2530
2531 return false;
2532 }
2533
2534 return true;
2535}
2536
2537bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2538 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002539 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2540 if (slot_suffix.empty()) {
2541 return false;
2542 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002543
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002544 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2545 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2546 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002547 }
2548
2549 // Validate other inputs.
2550 if (validate_apk_path(apk_path) != 0) {
2551 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2552 return false;
2553 }
2554 if (validate_apk_path(oat_dir) != 0) {
2555 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2556 return false;
2557 }
2558
2559 char a_path[PKG_PATH_MAX];
2560 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2561 return false;
2562 }
2563 const std::string a_vdex_path = create_vdex_filename(a_path);
2564 const std::string a_image_path = create_image_filename(a_path);
2565
2566 // B path = A path + slot suffix.
2567 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2568 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2569 const std::string b_image_path = StringPrintf("%s.%s",
2570 a_image_path.c_str(),
2571 slot_suffix.c_str());
2572
2573 bool success = true;
2574 if (move_ab_path(b_path, a_path)) {
2575 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2576 // Note: we can live without an app image. As such, ignore failure to move the image file.
2577 // If we decide to require the app image, or the app image being moved correctly,
2578 // then change accordingly.
2579 constexpr bool kIgnoreAppImageFailure = true;
2580
2581 if (!a_image_path.empty()) {
2582 if (!move_ab_path(b_image_path, a_image_path)) {
2583 unlink(a_image_path.c_str());
2584 if (!kIgnoreAppImageFailure) {
2585 success = false;
2586 }
2587 }
2588 }
2589 } else {
2590 // Cleanup: delete B image, ignore errors.
2591 unlink(b_image_path.c_str());
2592 success = false;
2593 }
2594 } else {
2595 // Cleanup: delete B image, ignore errors.
2596 unlink(b_vdex_path.c_str());
2597 unlink(b_image_path.c_str());
2598 success = false;
2599 }
2600 return success;
2601}
2602
2603bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2604 // Delete the oat/odex file.
2605 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002606 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002607 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002608 return false;
2609 }
2610
2611 // In case of a permission failure report the issue. Otherwise just print a warning.
2612 auto unlink_and_check = [](const char* path) -> bool {
2613 int result = unlink(path);
2614 if (result != 0) {
2615 if (errno == EACCES || errno == EPERM) {
2616 PLOG(ERROR) << "Could not unlink " << path;
2617 return false;
2618 }
2619 PLOG(WARNING) << "Could not unlink " << path;
2620 }
2621 return true;
2622 };
2623
2624 // Delete the oat/odex file.
2625 bool return_value_oat = unlink_and_check(out_path);
2626
2627 // Derive and delete the app image.
2628 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2629
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002630 // Derive and delete the vdex file.
2631 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2632
Jeff Sharkey90aff262016-12-12 14:28:24 -07002633 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002634 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002635}
2636
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002637static bool is_absolute_path(const std::string& path) {
2638 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2639 LOG(ERROR) << "Invalid absolute path " << path;
2640 return false;
2641 } else {
2642 return true;
2643 }
2644}
2645
2646static bool is_valid_instruction_set(const std::string& instruction_set) {
2647 // TODO: add explicit whitelisting of instruction sets
2648 if (instruction_set.find('/') != std::string::npos) {
2649 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2650 return false;
2651 } else {
2652 return true;
2653 }
2654}
2655
2656bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2657 const char *apk_path, const char *instruction_set) {
2658 std::string oat_dir_ = oat_dir;
2659 std::string apk_path_ = apk_path;
2660 std::string instruction_set_ = instruction_set;
2661
2662 if (!is_absolute_path(oat_dir_)) return false;
2663 if (!is_absolute_path(apk_path_)) return false;
2664 if (!is_valid_instruction_set(instruction_set_)) return false;
2665
2666 std::string::size_type end = apk_path_.rfind('.');
2667 std::string::size_type start = apk_path_.rfind('/', end);
2668 if (end == std::string::npos || start == std::string::npos) {
2669 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2670 return false;
2671 }
2672
2673 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2674 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2675 const char* res = res_.c_str();
2676 if (strlen(res) >= PKG_PATH_MAX) {
2677 LOG(ERROR) << "Result too large";
2678 return false;
2679 } else {
2680 strlcpy(path, res, PKG_PATH_MAX);
2681 return true;
2682 }
2683}
2684
2685bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2686 const char *instruction_set) {
2687 std::string apk_path_ = apk_path;
2688 std::string instruction_set_ = instruction_set;
2689
2690 if (!is_absolute_path(apk_path_)) return false;
2691 if (!is_valid_instruction_set(instruction_set_)) return false;
2692
2693 std::string::size_type end = apk_path_.rfind('.');
2694 std::string::size_type start = apk_path_.rfind('/', end);
2695 if (end == std::string::npos || start == std::string::npos) {
2696 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2697 return false;
2698 }
2699
2700 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2701 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2702}
2703
2704bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2705 const char *instruction_set) {
2706 std::string src_ = src;
2707 std::string instruction_set_ = instruction_set;
2708
2709 if (!is_absolute_path(src_)) return false;
2710 if (!is_valid_instruction_set(instruction_set_)) return false;
2711
2712 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2713 if (*it == '/') {
2714 *it = '@';
2715 }
2716 }
2717
2718 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2719 + DALVIK_CACHE_POSTFIX;
2720 const char* res = res_.c_str();
2721 if (strlen(res) >= PKG_PATH_MAX) {
2722 LOG(ERROR) << "Result too large";
2723 return false;
2724 } else {
2725 strlcpy(path, res, PKG_PATH_MAX);
2726 return true;
2727 }
2728}
2729
Calin Juravle59f7ab82018-04-27 17:50:23 -07002730bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2731 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002732 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2733 for (const std::string& elem : classpaths_elems) {
2734 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2735 if (fd < 0) {
2736 PLOG(ERROR) << "Could not open classpath elem " << elem;
2737 return false;
2738 } else {
2739 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002740 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002741 }
2742 }
2743 return true;
2744}
2745
2746static bool create_app_profile_snapshot(int32_t app_id,
2747 const std::string& package_name,
2748 const std::string& profile_name,
2749 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002750 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2751
Calin Juravle824a64d2018-01-18 20:23:17 -08002752 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002753 if (snapshot_fd < 0) {
2754 return false;
2755 }
2756
2757 std::vector<unique_fd> profiles_fd;
2758 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002759 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2760 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002761 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2762 return false;
2763 }
2764
2765 profiles_fd.push_back(std::move(reference_profile_fd));
2766
Calin Juravle0d0a4922018-01-23 19:54:11 -08002767 // Open the class paths elements. These will be used to filter out profile data that does
2768 // not belong to the classpath during merge.
2769 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002770 std::vector<std::string> dex_locations;
2771 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002772 return false;
2773 }
2774
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002775 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002776 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002777 pid_t pid = fork();
2778 if (pid == 0) {
2779 /* child -- drop privileges before continuing */
2780 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002781 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002782 }
2783
2784 /* parent */
2785 int return_code = wait_child(pid);
2786 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002787 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002788 return false;
2789 }
2790
Calin Juravle78728f32019-11-08 17:55:46 -08002791 // Verify that profman finished successfully.
2792 int profman_code = WEXITSTATUS(return_code);
2793 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2794 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2795 << ":" << profman_code;
2796 return false;
2797 }
Calin Juravle29591732017-11-20 17:46:19 -08002798 return true;
2799}
2800
Calin Juravle0d0a4922018-01-23 19:54:11 -08002801static bool create_boot_image_profile_snapshot(const std::string& package_name,
2802 const std::string& profile_name,
2803 const std::string& classpath) {
2804 // The reference profile directory for the android package might not be prepared. Do it now.
2805 const std::string ref_profile_dir =
2806 create_primary_reference_profile_package_dir_path(package_name);
2807 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2808 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2809 return false;
2810 }
2811
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002812 // Return false for empty class path since it may otherwise return true below if profiles is
2813 // empty.
2814 if (classpath.empty()) {
2815 PLOG(ERROR) << "Class path is empty";
2816 return false;
2817 }
2818
Calin Juravle0d0a4922018-01-23 19:54:11 -08002819 // Open and create the snapshot profile.
2820 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2821
2822 // Collect all non empty profiles.
2823 // The collection will traverse all applications profiles and find the non empty files.
2824 // This has the potential of inspecting a large number of files and directories (depending
2825 // on the number of applications and users). So there is a slight increase in the chance
2826 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2827 // fail the snapshot and aggregate whatever profile we could open.
2828 //
2829 // The profile snapshot is a best effort based on available data it's ok if some data
2830 // from some apps is missing. It will be counter productive for the snapshot to fail
2831 // because we could not open or read some of the files.
2832 std::vector<std::string> profiles;
2833 if (!collect_profiles(&profiles)) {
2834 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2835 }
2836
2837 // If we have no profiles return early.
2838 if (profiles.empty()) {
2839 return true;
2840 }
2841
2842 // Open the classpath elements. These will be used to filter out profile data that does
2843 // not belong to the classpath during merge.
2844 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002845 std::vector<std::string> dex_locations;
2846 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002847 return false;
2848 }
2849
2850 // If we could not open any files from the classpath return an error.
2851 if (apk_fds.empty()) {
2852 LOG(ERROR) << "Could not open any of the classpath elements.";
2853 return false;
2854 }
2855
2856 // Aggregate the profiles in batches of kAggregationBatchSize.
2857 // We do this to avoid opening a huge a amount of files.
2858 static constexpr size_t kAggregationBatchSize = 10;
2859
Calin Juravle0d0a4922018-01-23 19:54:11 -08002860 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002861 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002862 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2863 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2864 if (fd.get() >= 0) {
2865 profiles_fd.push_back(std::move(fd));
2866 }
2867 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002868
2869 // We aggregate (read & write) into the same fd multiple times in a row.
2870 // We need to reset the cursor every time to ensure we read the whole file every time.
2871 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2872 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2873 return false;
2874 }
2875
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002876 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002877 args.SetupMerge(profiles_fd,
2878 snapshot_fd,
2879 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002880 dex_locations,
2881 /*for_snapshot=*/true,
2882 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002883 pid_t pid = fork();
2884 if (pid == 0) {
2885 /* child -- drop privileges before continuing */
2886 drop_capabilities(AID_SYSTEM);
2887
Calin Juravle59f7ab82018-04-27 17:50:23 -07002888 // The introduction of new access flags into boot jars causes them to
2889 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002890 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002891 }
2892
2893 /* parent */
2894 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002895
Calin Juravle0d0a4922018-01-23 19:54:11 -08002896 if (!WIFEXITED(return_code)) {
2897 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2898 return false;
2899 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002900
2901 // Verify that profman finished successfully.
2902 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002903 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2904 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2905 << ":" << profman_code;
2906 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002907 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002908 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002909
Calin Juravle0d0a4922018-01-23 19:54:11 -08002910 return true;
2911}
2912
2913bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2914 const std::string& profile_name, const std::string& classpath) {
2915 if (app_id == -1) {
2916 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2917 } else {
2918 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2919 }
2920}
2921
Calin Juravlec3b049e2018-01-18 22:32:58 -08002922bool prepare_app_profile(const std::string& package_name,
2923 userid_t user_id,
2924 appid_t app_id,
2925 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002926 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002927 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002928 // Prepare the current profile.
2929 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2930 /*is_secondary_dex*/ false);
2931 uid_t uid = multiuser_get_uid(user_id, app_id);
2932 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2933 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2934 return false;
2935 }
2936
2937 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002938 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002939 return true;
2940 }
2941
2942 // We have a dex metdata. Merge the profile into the reference profile.
2943 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2944 /*read_write*/ true, /*is_secondary_dex*/ false);
2945 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2946 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002947 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2948 if (apk_fd < 0) {
2949 PLOG(ERROR) << "Could not open code path " << code_path;
2950 return false;
2951 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002952
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002953 RunProfman args;
2954 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2955 std::move(ref_profile_fd),
2956 std::move(apk_fd),
2957 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002958 pid_t pid = fork();
2959 if (pid == 0) {
2960 /* child -- drop privileges before continuing */
2961 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2962 drop_capabilities(app_shared_gid);
2963
Calin Juravlef63d4792018-01-30 17:43:34 +00002964 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002965 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002966 }
2967
2968 /* parent */
2969 int return_code = wait_child(pid);
2970 if (!WIFEXITED(return_code)) {
2971 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2972 return false;
2973 }
2974 return true;
2975}
2976
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002977} // namespace installd
2978} // namespace android