blob: 1c4c98010e9ed51fe5d7ae35a5d128839c3bd711 [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
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100377 std::string updatable_bcp_packages =
378 MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
379 "--updatable-bcp-packages-file=%s");
380 if (updatable_bcp_packages.empty()) {
381 // Make dex2oat fail by providing non-existent file name.
382 updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
383 }
384
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800385 std::string resolve_startup_string_arg =
386 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
387 "--resolve-startup-const-strings=%s");
388 if (resolve_startup_string_arg.empty()) {
389 // If empty, fall back to system property.
390 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800391 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
392 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800393 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800394
395 const std::string image_block_size_arg =
396 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
397 "--max-image-block-size=%s");
398
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800399 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700400
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800401 std::string image_format_arg;
402 if (image_fd >= 0) {
403 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000404 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000405
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800406 std::string dex2oat_large_app_threshold_arg =
407 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000408
Calin Juravlef74a7372019-02-28 20:29:41 -0800409
410 const char* dex2oat_bin = select_execution_binary(
411 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000412
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800413 bool generate_minidebug_info = kEnableMinidebugInfo &&
414 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000415
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000416 std::string boot_image;
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000417 std::string use_jitzygote_image =
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000418 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000419 ENABLE_JITZYGOTE_IMAGE,
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000420 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700421
422 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
423 profile_boot_class_path =
424 server_configurable_flags::GetServerConfigurableFlag(
425 RUNTIME_NATIVE_BOOT_NAMESPACE,
426 PROFILE_BOOT_CLASS_PATH,
427 /*default_value=*/ profile_boot_class_path);
428
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000429 if (use_jitzygote_image == "true" || profile_boot_class_path == "true") {
430 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000431 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000432 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000433 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000434
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800435 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
436 // use arraysize instead.
437 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
438 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
439 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
440 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
441 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
442 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
443 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
444 std::string dex2oat_compiler_filter_arg;
445 std::string dex2oat_swap_fd;
446 std::string dex2oat_image_fd;
447 std::string target_sdk_version_arg;
448 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000449 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800450 }
451 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000452 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800453 if (class_loader_context != nullptr) {
454 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
455 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000456 if (!class_loader_context_fds.empty()) {
457 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
458 class_loader_context_fds.c_str());
459 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800460 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000461
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800462 if (swap_fd >= 0) {
463 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
464 }
465 if (image_fd >= 0) {
466 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
467 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000468
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800469 // Compute compiler filter.
470 bool have_dex2oat_relocation_skip_flag = false;
471 if (skip_compilation) {
472 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
473 have_dex2oat_relocation_skip_flag = true;
474 } else if (compiler_filter != nullptr) {
475 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
476 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000477
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800478 if (dex2oat_compiler_filter_arg.empty()) {
479 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
480 "--compiler-filter=%s");
481 }
482
483 // Check whether all apps should be compiled debuggable.
484 if (!debuggable) {
485 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
486 }
487 std::string profile_arg;
488 if (profile_fd != -1) {
489 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
490 }
491
492 // Get the directory of the apk to pass as a base classpath directory.
493 std::string base_dir;
494 std::string apk_dir(input_file_name);
495 unsigned long dir_index = apk_dir.rfind('/');
496 bool has_base_dir = dir_index != std::string::npos;
497 if (has_base_dir) {
498 apk_dir = apk_dir.substr(0, dir_index);
499 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
500 }
501
502 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
503
504 std::string compilation_reason_arg = compilation_reason == nullptr
505 ? ""
506 : std::string("--compilation-reason=") + compilation_reason;
507
508 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
509
510 // Disable cdex if update input vdex is true since this combination of options is not
511 // supported.
512 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
513
514 AddArg(zip_fd_arg);
515 AddArg(zip_location_arg);
516 AddArg(input_vdex_fd_arg);
517 AddArg(output_vdex_fd_arg);
518 AddArg(oat_fd_arg);
519 AddArg(oat_location_arg);
520 AddArg(instruction_set_arg);
521
522 AddArg(instruction_set_variant_arg);
523 AddArg(instruction_set_features_arg);
524
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000525 AddArg(boot_image);
526
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000527 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800528 AddRuntimeArg(dex2oat_Xms_arg);
529 AddRuntimeArg(dex2oat_Xmx_arg);
530
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100531 AddArg(updatable_bcp_packages);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800532 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800533 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800534 AddArg(dex2oat_compiler_filter_arg);
535 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000536 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800537 AddArg(dex2oat_swap_fd);
538 AddArg(dex2oat_image_fd);
539
540 if (generate_debug_info) {
541 AddArg("--generate-debug-info");
542 }
543 if (debuggable) {
544 AddArg("--debuggable");
545 }
546 AddArg(image_format_arg);
547 AddArg(dex2oat_large_app_threshold_arg);
548
549 if (have_dex2oat_relocation_skip_flag) {
550 AddRuntimeArg(dex2oat_norelocation);
551 }
552 AddArg(profile_arg);
553 AddArg(base_dir);
554 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000555 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800556 if (generate_minidebug_info) {
557 AddArg(kMinidebugDex2oatFlag);
558 }
559 if (disable_cdex) {
560 AddArg(kDisableCompactDexFlag);
561 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000562 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800563 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100564 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800565 }
566
567 if (dex_metadata_fd > -1) {
568 AddArg(dex_metadata_fd_arg);
569 }
570
571 AddArg(compilation_reason_arg);
572
573 // Do not add args after dex2oat_flags, they should override others for debugging.
574 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
575
576 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000577 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800578};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700579
580/*
581 * Whether dexopt should use a swap file when compiling an APK.
582 *
583 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
584 * itself, anyways).
585 *
586 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
587 *
588 * Otherwise, return true if this is a low-mem device.
589 *
590 * Otherwise, return default value.
591 */
592static bool kAlwaysProvideSwapFile = false;
593static bool kDefaultProvideSwapFile = true;
594
595static bool ShouldUseSwapFileForDexopt() {
596 if (kAlwaysProvideSwapFile) {
597 return true;
598 }
599
600 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700601 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
602 if (!dex2oat_prop_buf.empty()) {
603 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700604 }
605
606 // Shortcut for default value. This is an implementation optimization for the process sketched
607 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
608 // as low-mem is never returning false. The compiler will optimize this away if it can.
609 if (kDefaultProvideSwapFile) {
610 return true;
611 }
612
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700613 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 return true;
615 }
616
617 // Default value must be false here.
618 return kDefaultProvideSwapFile;
619}
620
Richard Uhler76cc0272016-12-08 10:46:35 +0000621static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700622 if (set_to_bg) {
623 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800624 PLOG(ERROR) << "set_sched_policy failed";
625 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 }
627 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800628 PLOG(ERROR) << "setpriority failed";
629 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700630 }
631 }
632}
633
Calin Juravle29591732017-11-20 17:46:19 -0800634static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
635 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800636 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800637 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800638 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800639 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800640 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700641 }
Calin Juravle114f0812017-03-08 19:05:07 -0800642 // Profiles should belong to the app; make sure of that by giving ownership to
643 // the app uid. If we cannot do that, there's no point in returning the fd
644 // since dex2oat/profman will fail with SElinux denials.
645 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000646 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800647 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800648 }
Calin Juravle29591732017-11-20 17:46:19 -0800649 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800650}
651
Calin Juravle29591732017-11-20 17:46:19 -0800652static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800653 // Do not follow symlinks when opening a profile:
654 // - primary profiles should not contain symlinks in their paths
655 // - secondary dex paths should have been already resolved and validated
656 flags |= O_NOFOLLOW;
657
Calin Juravle29591732017-11-20 17:46:19 -0800658 // Check if we need to create the profile
659 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
660 unique_fd fd;
661 if ((flags & O_CREAT) != 0) {
662 fd = create_profile(uid, profile, flags);
663 } else {
664 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
665 }
666
Calin Juravle114f0812017-03-08 19:05:07 -0800667 if (fd.get() < 0) {
668 if (errno != ENOENT) {
669 // Profiles might be missing for various reasons. For example, in a
670 // multi-user environment, the profile directory for one user can be created
671 // after we start a merge. In this case the current profile for that user
672 // will not be found.
673 // Also, the secondary dex profiles might be deleted by the app at any time,
674 // so we can't we need to prepare if they are missing.
675 PLOG(ERROR) << "Failed to open profile " << profile;
676 }
677 return invalid_unique_fd();
678 }
679
Jeff Sharkey90aff262016-12-12 14:28:24 -0700680 return fd;
681}
682
Calin Juravle824a64d2018-01-18 20:23:17 -0800683static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
684 const std::string& location, bool is_secondary_dex) {
685 std::string profile = create_current_profile_path(user, package_name, location,
686 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800687 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800688}
689
Calin Juravle824a64d2018-01-18 20:23:17 -0800690static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
691 const std::string& location, bool read_write, bool is_secondary_dex) {
692 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800693 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
694}
695
696static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800697 const std::string& location) {
698 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800699 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800700}
701
Calin Juravle824a64d2018-01-18 20:23:17 -0800702static void open_profile_files(uid_t uid, const std::string& package_name,
703 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800704 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800706 *reference_profile_fd = open_reference_profile(uid, package_name, location,
707 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700708
Calin Juravle114f0812017-03-08 19:05:07 -0800709 // For secondary dex files, we don't really need the user but we use it for sanity checks.
710 // Note: the user owning the dex file should be the current user.
711 std::vector<userid_t> users;
712 if (is_secondary_dex){
713 users.push_back(multiuser_get_user_id(uid));
714 } else {
715 users = get_known_users(/*volume_uuid*/ nullptr);
716 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700717 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800718 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
719 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700720 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800721 if (profile_fd.get() >= 0) {
722 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700723 }
724 }
725}
726
Calin Juravle76561322019-11-14 09:08:52 -0800727static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
728static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
729static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
730static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
731static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
732static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
733static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700734
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800735class RunProfman : public ExecVHelper {
736 public:
737 void SetupArgs(const std::vector<unique_fd>& profile_fds,
738 const unique_fd& reference_profile_fd,
739 const std::vector<unique_fd>& apk_fds,
740 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800741 bool copy_and_update,
742 bool for_snapshot,
743 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800744
745 // TODO(calin): Assume for now we run in the bg compile job (which is in
746 // most of the invocation). With the current data flow, is not very easy or
747 // clean to discover this in RunProfman (it will require quite a messy refactoring).
748 const char* profman_bin = select_execution_binary(
749 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800751 if (copy_and_update) {
752 CHECK_EQ(1u, profile_fds.size());
753 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000754 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800755 if (reference_profile_fd != -1) {
756 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000757 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800758
759 for (const unique_fd& fd : profile_fds) {
760 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
761 }
762
763 for (const unique_fd& fd : apk_fds) {
764 AddArg("--apk-fd=" + std::to_string(fd.get()));
765 }
766
767 for (const std::string& dex_location : dex_locations) {
768 AddArg("--dex-location=" + dex_location);
769 }
770
771 if (copy_and_update) {
772 AddArg("--copy-and-update-profile-key");
773 }
774
Calin Juravle78728f32019-11-08 17:55:46 -0800775 if (for_snapshot) {
776 AddArg("--force-merge");
777 }
778
779 if (for_boot_image) {
780 AddArg("--boot-image-merge");
781 }
782
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800783 // Do not add after dex2oat_flags, they should override others for debugging.
784 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800785 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700786
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800787 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
788 const unique_fd& reference_profile_fd,
789 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800790 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
791 bool for_snapshot = false,
792 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800793 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800794 reference_profile_fd,
795 apk_fds,
796 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800797 /*copy_and_update=*/ false,
798 for_snapshot,
799 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800800 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700801
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800802 void SetupCopyAndUpdate(unique_fd&& profile_fd,
803 unique_fd&& reference_profile_fd,
804 unique_fd&& apk_fd,
805 const std::string& dex_location) {
806 // The fds need to stay open longer than the scope of the function, so put them into a local
807 // variable vector.
808 profiles_fd_.push_back(std::move(profile_fd));
809 apk_fds_.push_back(std::move(apk_fd));
810 reference_profile_fd_ = std::move(reference_profile_fd);
811 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800812 SetupArgs(profiles_fd_,
813 reference_profile_fd_,
814 apk_fds_,
815 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800816 /*copy_and_update=*/true,
817 /*for_snapshot*/false,
818 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800819 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000820
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800821 void SetupDump(const std::vector<unique_fd>& profiles_fd,
822 const unique_fd& reference_profile_fd,
823 const std::vector<std::string>& dex_locations,
824 const std::vector<unique_fd>& apk_fds,
825 const unique_fd& output_fd) {
826 AddArg("--dump-only");
827 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800828 SetupArgs(profiles_fd,
829 reference_profile_fd,
830 apk_fds,
831 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800832 /*copy_and_update=*/false,
833 /*for_snapshot*/false,
834 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800835 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000836
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800837 void Exec() {
838 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
839 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000840
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800841 private:
842 unique_fd reference_profile_fd_;
843 std::vector<unique_fd> profiles_fd_;
844 std::vector<unique_fd> apk_fds_;
845};
Mathieu Chartier31636522018-11-09 23:53:07 +0000846
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800847
Calin Juravlef63d4792018-01-30 17:43:34 +0000848
Jeff Sharkey90aff262016-12-12 14:28:24 -0700849// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800850// The location is the package name for primary apks or the dex path for secondary dex files.
851// Returns true if there is enough information in the current profiles that makes it
852// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853// If the return value is true all the current profiles would have been merged into
854// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800855static bool analyze_profiles(uid_t uid, const std::string& package_name,
856 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800857 std::vector<unique_fd> profiles_fd;
858 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800859 open_profile_files(uid, package_name, location, is_secondary_dex,
860 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800861 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862 // Skip profile guided compilation because no profiles were found.
863 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700864 return false;
865 }
866
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800867 RunProfman profman_merge;
868 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700869 pid_t pid = fork();
870 if (pid == 0) {
871 /* child -- drop privileges before continuing */
872 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800873 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874 }
875 /* parent */
876 int return_code = wait_child(pid);
877 bool need_to_compile = false;
878 bool should_clear_current_profiles = false;
879 bool should_clear_reference_profile = false;
880 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800881 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 } else {
883 return_code = WEXITSTATUS(return_code);
884 switch (return_code) {
885 case PROFMAN_BIN_RETURN_CODE_COMPILE:
886 need_to_compile = true;
887 should_clear_current_profiles = true;
888 should_clear_reference_profile = false;
889 break;
890 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
891 need_to_compile = false;
892 should_clear_current_profiles = false;
893 should_clear_reference_profile = false;
894 break;
895 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800896 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700897 need_to_compile = false;
898 should_clear_current_profiles = true;
899 should_clear_reference_profile = true;
900 break;
901 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
902 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
903 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800904 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700905 need_to_compile = false;
906 should_clear_current_profiles = false;
907 should_clear_reference_profile = false;
908 break;
Calin Juravle76561322019-11-14 09:08:52 -0800909 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
910 need_to_compile = false;
911 should_clear_current_profiles = true;
912 should_clear_reference_profile = true;
913 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700914 default:
915 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800916 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800917 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700918 need_to_compile = false;
919 should_clear_current_profiles = true;
920 should_clear_reference_profile = true;
921 break;
922 }
923 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800924
Jeff Sharkey90aff262016-12-12 14:28:24 -0700925 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800926 if (is_secondary_dex) {
927 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800928 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
929 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800930 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800931 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800932 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 }
934 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800935 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700936 }
937 return need_to_compile;
938}
939
Calin Juravle114f0812017-03-08 19:05:07 -0800940// Decides if profile guided compilation is needed or not based on existing profiles.
941// The analysis is done for the primary apks of the given package.
942// Returns true if there is enough information in the current profiles that makes it
943// worth to recompile the package.
944// If the return value is true all the current profiles would have been merged into
945// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800946bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
947 const std::string& profile_name) {
948 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800949}
950
Calin Juravle408cd4a2018-01-20 23:34:18 -0800951bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
952 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800953 std::vector<unique_fd> profile_fds;
954 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800955 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
956 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700957
Calin Juravle408cd4a2018-01-20 23:34:18 -0800958 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800959 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700960
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800961 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700962 const bool has_profiles = !profile_fds.empty();
963
964 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800965 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700966 return false;
967 }
968
Calin Juravle114f0812017-03-08 19:05:07 -0800969 unique_fd output_fd(open(out_file_name.c_str(),
970 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700971 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800972 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 return false;
974 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800975
Jeff Sharkey90aff262016-12-12 14:28:24 -0700976 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800977 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800978 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
979 if (apk_fd == -1) {
980 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
981 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700982 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800983 dex_locations.push_back(get_location_from_path(code_path.c_str()));
984 apk_fds.push_back(std::move(apk_fd));
985
Jeff Sharkey90aff262016-12-12 14:28:24 -0700986
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800987 RunProfman profman_dump;
988 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700989 pid_t pid = fork();
990 if (pid == 0) {
991 /* child -- drop privileges before continuing */
992 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800993 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700994 }
995 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700996 int return_code = wait_child(pid);
997 if (!WIFEXITED(return_code)) {
998 LOG(WARNING) << "profman failed for package " << pkgname << ": "
999 << return_code;
1000 return false;
1001 }
1002 return true;
1003}
1004
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001005bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001006 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001007 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1008 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001009 package_name,
1010 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001011 /*read_write*/ true,
1012 /*secondary*/ false));
1013 if (in_fd.get() < 0) {
1014 PLOG(WARNING) << "Could not open profile " << system_profile;
1015 return false;
1016 }
1017 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001018 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001019 return false;
1020 }
1021
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001022 // As a security measure we want to write the profile information with the reduced capabilities
1023 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001024 pid_t pid = fork();
1025 if (pid == 0) {
1026 /* child -- drop privileges before continuing */
1027 drop_capabilities(packageUid);
1028
1029 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1030 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001031 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001032 }
1033 // This implies that the app owning this profile is running
1034 // (and has acquired the lock).
1035 //
1036 // The app never acquires the lock for the reference profiles of primary apks.
1037 // Only dex2oat from installd will do that. Since installd is single threaded
1038 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001039 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001040 return false;
1041 }
1042
1043 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1044 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001045 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001046 }
1047
1048 // Copy over data.
1049 static constexpr size_t kBufferSize = 4 * 1024;
1050 char buffer[kBufferSize];
1051 while (true) {
1052 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1053 if (bytes == 0) {
1054 break;
1055 }
1056 write(out_fd.get(), buffer, bytes);
1057 }
1058 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001059 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001060 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001061 // Use _exit since we don't want to run the global destructors in the child.
1062 // b/62597429
1063 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001064 }
1065 /* parent */
1066 int return_code = wait_child(pid);
1067 return return_code == 0;
1068}
1069
Jeff Sharkey90aff262016-12-12 14:28:24 -07001070static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1071 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1072 if (EndsWith(oat_path, ".dex")) {
1073 std::string new_path = oat_path;
1074 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001075 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001076 return new_path;
1077 }
1078
1079 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1080 // case (where the base name will have an extension for the B artifact).
1081 size_t odex_pos = oat_path.rfind(".odex");
1082 if (odex_pos != std::string::npos) {
1083 std::string new_path = oat_path;
1084 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1085 CHECK_NE(new_path.find(new_ext), std::string::npos);
1086 return new_path;
1087 }
1088
1089 // Don't know how to handle this.
1090 return "";
1091}
1092
1093// Translate the given oat path to an art (app image) path. An empty string
1094// denotes an error.
1095static std::string create_image_filename(const std::string& oat_path) {
1096 return replace_file_extension(oat_path, ".art");
1097}
1098
1099// Translate the given oat path to a vdex path. An empty string denotes an error.
1100static std::string create_vdex_filename(const std::string& oat_path) {
1101 return replace_file_extension(oat_path, ".vdex");
1102}
1103
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104static int open_output_file(const char* file_name, bool recreate, int permissions) {
1105 int flags = O_RDWR | O_CREAT;
1106 if (recreate) {
1107 if (unlink(file_name) < 0) {
1108 if (errno != ENOENT) {
1109 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1110 }
1111 }
1112 flags |= O_EXCL;
1113 }
1114 return open(file_name, flags, permissions);
1115}
1116
Calin Juravle2289c0a2017-02-15 12:44:14 -08001117static bool set_permissions_and_ownership(
1118 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1119 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1120 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 if (fchmod(fd,
1122 S_IRUSR|S_IWUSR|S_IRGRP |
1123 (is_public ? S_IROTH : 0)) < 0) {
1124 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1125 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001126 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1128 return false;
1129 }
1130 return true;
1131}
1132
1133static bool IsOutputDalvikCache(const char* oat_dir) {
1134 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1135 // into '!'. Play it safe by handling it both.
1136 // TODO: ensure we never get null.
1137 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1138 return oat_dir == nullptr || oat_dir[0] == '!';
1139}
1140
Calin Juravled23dee72017-07-06 16:29:11 -07001141// Best-effort check whether we can fit the the path into our buffers.
1142// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1143// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1144// extension to the cache path (5 bytes).
1145// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1146static bool validate_dex_path_size(const std::string& dex_path) {
1147 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1148 LOG(ERROR) << "dex_path too long: " << dex_path;
1149 return false;
1150 }
1151 return true;
1152}
1153
Jeff Sharkey90aff262016-12-12 14:28:24 -07001154static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001155 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001156 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 return false;
1158 }
1159
1160 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001161 // Oat dirs for secondary dex files are already validated.
1162 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001163 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1164 return false;
1165 }
1166 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1167 return false;
1168 }
1169 } else {
1170 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1171 return false;
1172 }
1173 }
1174 return true;
1175}
1176
1177// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1178// on destruction. It will also run the given cleanup (unless told not to) after closing.
1179//
1180// Usage example:
1181//
Calin Juravle7a570e82017-01-14 16:23:30 -08001182// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001183// [name]() {
1184// unlink(name.c_str());
1185// });
1186// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1187// wrapper if captured as a reference.
1188//
1189// if (file.get() == -1) {
1190// // Error opening...
1191// }
1192//
1193// ...
1194// if (error) {
1195// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1196// // and delete the file (after the fd is closed).
1197// return -1;
1198// }
1199//
1200// (Success case)
1201// file.SetCleanup(false);
1202// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1203// // (leaving the file around; after the fd is closed).
1204//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001205class Dex2oatFileWrapper {
1206 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001208 }
1209
Calin Juravle7a570e82017-01-14 16:23:30 -08001210 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1211 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1212
1213 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1214 value_ = other.value_;
1215 cleanup_ = other.cleanup_;
1216 do_cleanup_ = other.do_cleanup_;
1217 auto_close_ = other.auto_close_;
1218 other.release();
1219 }
1220
1221 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1222 value_ = other.value_;
1223 cleanup_ = other.cleanup_;
1224 do_cleanup_ = other.do_cleanup_;
1225 auto_close_ = other.auto_close_;
1226 other.release();
1227 return *this;
1228 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001229
1230 ~Dex2oatFileWrapper() {
1231 reset(-1);
1232 }
1233
1234 int get() {
1235 return value_;
1236 }
1237
1238 void SetCleanup(bool cleanup) {
1239 do_cleanup_ = cleanup;
1240 }
1241
1242 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001243 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001244 close(value_);
1245 }
1246 if (do_cleanup_ && cleanup_ != nullptr) {
1247 cleanup_();
1248 }
1249
1250 value_ = new_value;
1251 }
1252
Calin Juravle7a570e82017-01-14 16:23:30 -08001253 void reset(int new_value, std::function<void ()> new_cleanup) {
1254 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001255 close(value_);
1256 }
1257 if (do_cleanup_ && cleanup_ != nullptr) {
1258 cleanup_();
1259 }
1260
1261 value_ = new_value;
1262 cleanup_ = new_cleanup;
1263 }
1264
Calin Juravle7a570e82017-01-14 16:23:30 -08001265 void DisableAutoClose() {
1266 auto_close_ = false;
1267 }
1268
Jeff Sharkey90aff262016-12-12 14:28:24 -07001269 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001270 void release() {
1271 value_ = -1;
1272 do_cleanup_ = false;
1273 cleanup_ = nullptr;
1274 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001275 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001276 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001277 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001278 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001279};
1280
Calin Juravle7a570e82017-01-14 16:23:30 -08001281// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001282Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1283 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001284
Calin Juravle7a570e82017-01-14 16:23:30 -08001285 const std::string image_path = create_image_filename(out_oat_path);
1286 if (image_path.empty()) {
1287 // Happens when the out_oat_path has an unknown extension.
1288 return Dex2oatFileWrapper();
1289 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001290
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001291 // In case there is a stale image, remove it now. Ignore any error.
1292 unlink(image_path.c_str());
1293
1294 // Not enabled, exit.
1295 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001296 return Dex2oatFileWrapper();
1297 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001298 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1299 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001300 return Dex2oatFileWrapper();
1301 }
1302 // Recreate is true since we do not want to modify a mapped image. If the app is
1303 // already running and we modify the image file, it can cause crashes (b/27493510).
1304 Dex2oatFileWrapper wrapper_fd(
1305 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1306 [image_path]() { unlink(image_path.c_str()); });
1307 if (wrapper_fd.get() < 0) {
1308 // Could not create application image file. Go on since we can compile without it.
1309 LOG(ERROR) << "installd could not create '" << image_path
1310 << "' for image file during dexopt";
1311 // If we have a valid image file path but no image fd, explicitly erase the image file.
1312 if (unlink(image_path.c_str()) < 0) {
1313 if (errno != ENOENT) {
1314 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1315 }
1316 }
1317 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001318 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001319 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1320 wrapper_fd.reset(-1);
1321 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001322
Calin Juravle7a570e82017-01-14 16:23:30 -08001323 return wrapper_fd;
1324}
1325
1326// Creates the dexopt swap file if necessary and return its fd.
1327// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001328unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001329 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001330 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001331 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001332 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001333 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001334 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001335 if (swap_fd.get() < 0) {
1336 // Could not create swap file. Optimistically go on and hope that we can compile
1337 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001338 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001339 } else {
1340 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001341 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001342 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1343 }
1344 }
1345 return swap_fd;
1346}
1347
1348// Opens the reference profiles if needed.
1349// 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 -08001350Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001351 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001352 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001353 // If we are not profile guided compilation, or we are compiling system server
1354 // do not bother to open the profiles; we won't be using them.
1355 if (!profile_guided || (pkgname[0] == '*')) {
1356 return Dex2oatFileWrapper();
1357 }
1358
1359 // If this is a secondary dex path which is public do not open the profile.
1360 // We cannot compile public secondary dex paths with profiles. That's because
1361 // it will expose how the dex files are used by their owner.
1362 //
1363 // Note that the PackageManager is responsible to set the is_public flag for
1364 // primary apks and we do not check it here. In some cases, e.g. when
1365 // compiling with a public profile from the .dm file the PackageManager will
1366 // set is_public toghether with the profile guided compilation.
1367 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001368 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001369 }
Calin Juravle114f0812017-03-08 19:05:07 -08001370
1371 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001372 std::string location;
1373 if (is_secondary_dex) {
1374 location = dex_path;
1375 } else {
1376 if (profile_name == nullptr) {
1377 // This path is taken for system server re-compilation lunched from ZygoteInit.
1378 return Dex2oatFileWrapper();
1379 } else {
1380 location = profile_name;
1381 }
1382 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001383 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1384 is_secondary_dex);
1385 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1386 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001387 };
1388 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001389}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001390
Calin Juravle7a570e82017-01-14 16:23:30 -08001391// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1392// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001393bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001394 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001395 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001396 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1397 CHECK(in_vdex_wrapper_fd != nullptr);
1398 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001399 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1400 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001401 char in_odex_path[PKG_PATH_MAX];
1402 int dexopt_action = abs(dexopt_needed);
1403 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001404 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001405
1406 // Infer the name of the output VDEX.
1407 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1408 if (out_vdex_path_str.empty()) {
1409 return false;
1410 }
1411
1412 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001413 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001414 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1415 const char* path = nullptr;
1416 if (is_odex_location) {
1417 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1418 path = in_odex_path;
1419 } else {
1420 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001421 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001422 }
1423 } else {
1424 path = out_oat_path;
1425 }
1426 in_vdex_path_str = create_vdex_filename(path);
1427 if (in_vdex_path_str.empty()) {
1428 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001429 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001430 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001431 // We can update in place when all these conditions are met:
1432 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1433 // on /system typically cannot be updated in place).
1434 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1435 // cannot be currently used by a running process.
1436 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1437 // different vdex files to operate.
1438 update_vdex_in_place =
1439 (in_vdex_path_str == out_vdex_path_str) &&
1440 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1441 !profile_guided;
1442 if (update_vdex_in_place) {
1443 // Open the file read-write to be able to update it.
1444 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1445 if (in_vdex_wrapper_fd->get() == -1) {
1446 // If we failed to open the file, we cannot update it in place.
1447 update_vdex_in_place = false;
1448 }
1449 } else {
1450 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1451 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001452 }
1453
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001454 // If we are updating the vdex in place, we do not need to recreate a vdex,
1455 // and can use the same existing one.
1456 if (update_vdex_in_place) {
1457 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1458 // have bogus stale vdex files.
1459 out_vdex_wrapper_fd->reset(
1460 in_vdex_wrapper_fd->get(),
1461 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1462 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1463 // wrapper).
1464 in_vdex_wrapper_fd->DisableAutoClose();
1465 } else {
1466 out_vdex_wrapper_fd->reset(
1467 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1468 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1469 if (out_vdex_wrapper_fd->get() < 0) {
1470 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1471 return false;
1472 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001473 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001474 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001475 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001476 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1477 return false;
1478 }
1479
1480 // If we got here we successfully opened the vdex files.
1481 return true;
1482}
1483
1484// Opens the output oat file for the given apk.
1485// If successful it stores the output path into out_oat_path and returns true.
1486Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001487 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1488 char* out_oat_path) {
1489 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001490 return Dex2oatFileWrapper();
1491 }
1492 const std::string out_oat_path_str(out_oat_path);
1493 Dex2oatFileWrapper wrapper_fd(
1494 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1495 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1496 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001497 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001498 } else if (!set_permissions_and_ownership(
1499 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001500 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1501 wrapper_fd.reset(-1);
1502 }
1503 return wrapper_fd;
1504}
1505
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001506// Creates RDONLY fds for oat and vdex files, if exist.
1507// Returns false if it fails to create oat out path for the given apk path.
1508// Note that the method returns true even if the files could not be opened.
1509bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1510 const std::string& oat_dir,
1511 const std::string& instruction_set,
1512 bool is_secondary_dex,
1513 unique_fd* oat_file_fd,
1514 unique_fd* vdex_file_fd) {
1515 char oat_path[PKG_PATH_MAX];
1516 if (!create_oat_out_path(apk_path.c_str(),
1517 instruction_set.c_str(),
1518 oat_dir.c_str(),
1519 is_secondary_dex,
1520 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001521 LOG(ERROR) << "Could not create oat out path for "
1522 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001523 return false;
1524 }
1525 oat_file_fd->reset(open(oat_path, O_RDONLY));
1526 if (oat_file_fd->get() < 0) {
1527 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1528 }
1529
1530 std::string vdex_filename = create_vdex_filename(oat_path);
1531 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1532 if (vdex_file_fd->get() < 0) {
1533 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1534 }
1535
1536 return true;
1537}
1538
Calin Juravle7a570e82017-01-14 16:23:30 -08001539// Updates the access times of out_oat_path based on those from apk_path.
1540void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1541 struct stat input_stat;
1542 memset(&input_stat, 0, sizeof(input_stat));
1543 if (stat(apk_path, &input_stat) != 0) {
1544 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1545 return;
1546 }
1547
1548 struct utimbuf ut;
1549 ut.actime = input_stat.st_atime;
1550 ut.modtime = input_stat.st_mtime;
1551 if (utime(out_oat_path, &ut) != 0) {
1552 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1553 }
1554}
1555
Calin Juravle80a21252017-01-17 14:43:25 -08001556// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001557// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1558// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1559// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001560class RunDexoptAnalyzer : public ExecVHelper {
1561 public:
1562 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001563 int vdex_fd,
1564 int oat_fd,
1565 int zip_fd,
1566 const std::string& instruction_set,
1567 const std::string& compiler_filter,
1568 bool profile_was_updated,
1569 bool downgrade,
1570 const char* class_loader_context,
1571 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001572 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001573
1574 // We always run the analyzer in the background job.
1575 const char* dexoptanalyzer_bin = select_execution_binary(
1576 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001577
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001578 std::string dex_file_arg = "--dex-file=" + dex_file;
1579 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1580 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1581 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1582 std::string isa_arg = "--isa=" + instruction_set;
1583 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1584 const char* assume_profile_changed = "--assume-profile-changed";
1585 const char* downgrade_flag = "--downgrade";
1586 std::string class_loader_context_arg = "--class-loader-context=";
1587 if (class_loader_context != nullptr) {
1588 class_loader_context_arg += class_loader_context;
1589 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001590 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1591 if (!class_loader_context_fds.empty()) {
1592 class_loader_context_fds_arg += class_loader_context_fds;
1593 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001594
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001595 // program name, dex file, isa, filter
1596 AddArg(dex_file_arg);
1597 AddArg(isa_arg);
1598 AddArg(compiler_filter_arg);
1599 if (oat_fd >= 0) {
1600 AddArg(oat_fd_arg);
1601 }
1602 if (vdex_fd >= 0) {
1603 AddArg(vdex_fd_arg);
1604 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001605 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001606 if (profile_was_updated) {
1607 AddArg(assume_profile_changed);
1608 }
1609 if (downgrade) {
1610 AddArg(downgrade_flag);
1611 }
1612 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001613 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001614 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001615 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001616 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001617 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001618
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001619 PrepareArgs(dexoptanalyzer_bin);
1620 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001621
1622 // Dexoptanalyzer mode which flattens the given class loader context and
1623 // prints a list of its dex files in that flattened order.
1624 RunDexoptAnalyzer(const char* class_loader_context) {
1625 CHECK(class_loader_context != nullptr);
1626
1627 // We always run the analyzer in the background job.
1628 const char* dexoptanalyzer_bin = select_execution_binary(
1629 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1630
1631 AddArg("--flatten-class-loader-context");
1632 AddArg(std::string("--class-loader-context=") + class_loader_context);
1633 PrepareArgs(dexoptanalyzer_bin);
1634 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001635};
Calin Juravle80a21252017-01-17 14:43:25 -08001636
1637// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001638static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001639 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001640 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001641 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001642 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001643 return false;
1644 }
Calin Juravle114f0812017-03-08 19:05:07 -08001645 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001646
Calin Juravle80a21252017-01-17 14:43:25 -08001647 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001648 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1649 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001650 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001651 return false;
1652 }
1653
1654 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001655 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001656
Calin Juravle7d765462017-09-04 15:57:10 -07001657 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001658 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001659 return false;
1660 }
1661
1662 return true;
1663}
1664
Calin Juravle7d765462017-09-04 15:57:10 -07001665// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1666// secondary dex files. This return codes are returned by the child process created for
1667// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001668
Andreas Gampe194fe422018-02-28 20:16:19 -08001669enum DexoptAnalyzerSkipCodes {
1670 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001671 // Specific errors are encoded in the name.
1672 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1673 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1674 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1675 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1676 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001677 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001678 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001679};
Calin Juravle7d765462017-09-04 15:57:10 -07001680
1681// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001682// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1683// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001684// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1685// of dexoptanalyzer.
1686static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001687 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001688 // The result values are defined in dexoptanalyzer.
1689 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001690 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001691 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001692 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001693 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001694 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001695 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001696 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001697 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001698 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1699 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001700 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1701 " Expected odex file status for secondary dex %s"
1702 " : dexoptanalyzer result=%d",
1703 dex_path.c_str(),
1704 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001705 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001706 }
1707
1708 // Use a second switch for enum switch-case analysis.
1709 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001710 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001711 // If the file does not exist there's no need for dexopt.
1712 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1713 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001714
1715 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1716 *error_msg = "Dexoptanalyzer path validation failed";
1717 return false;
1718 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1719 *error_msg = "Dexoptanalyzer open zip failed";
1720 return false;
1721 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1722 *error_msg = "Dexoptanalyzer dir preparation failed";
1723 return false;
1724 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1725 *error_msg = "Dexoptanalyzer open output failed";
1726 return false;
1727 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1728 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001729 return false;
1730 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001731
1732 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1733 dex_path.c_str(),
1734 result);
1735 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001736}
1737
Calin Juravle7d765462017-09-04 15:57:10 -07001738enum SecondaryDexAccess {
1739 kSecondaryDexAccessReadOk = 0,
1740 kSecondaryDexAccessDoesNotExist = 1,
1741 kSecondaryDexAccessPermissionError = 2,
1742 kSecondaryDexAccessIOError = 3
1743};
1744
1745static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1746 // Check if the path exists and can be read. If not, there's nothing to do.
1747 if (access(dex_path.c_str(), R_OK) == 0) {
1748 return kSecondaryDexAccessReadOk;
1749 } else {
1750 if (errno == ENOENT) {
1751 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1752 return kSecondaryDexAccessDoesNotExist;
1753 } else {
1754 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1755 return errno == EACCES
1756 ? kSecondaryDexAccessPermissionError
1757 : kSecondaryDexAccessIOError;
1758 }
1759 }
1760}
1761
1762static bool is_file_public(const std::string& filename) {
1763 struct stat file_stat;
1764 if (stat(filename.c_str(), &file_stat) == 0) {
1765 return (file_stat.st_mode & S_IROTH) != 0;
1766 }
1767 return false;
1768}
1769
1770// Create the oat file structure for the secondary dex 'dex_path' and assign
1771// the individual path component to the 'out_' parameters.
1772static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001773 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001774 size_t dirIndex = dex_path.rfind('/');
1775 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001776 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001777 return false;
1778 }
1779 // TODO(calin): we have similar computations in at lest 3 other places
1780 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1781 // using string append.
1782 std::string apk_dir = dex_path.substr(0, dirIndex);
1783 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1784 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1785
1786 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1787 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001788 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001789 return false;
1790 }
1791 return true;
1792}
1793
1794// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1795// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001796static bool validate_dexopt_storage_flags(int dexopt_flags,
1797 int* out_storage_flag,
1798 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001799 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1800 *out_storage_flag = FLAG_STORAGE_CE;
1801 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001802 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001803 return false;
1804 }
1805 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1806 *out_storage_flag = FLAG_STORAGE_DE;
1807 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001808 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001809 return false;
1810 }
1811 return true;
1812}
1813
David Brazdil4f6027a2019-03-19 11:44:21 +00001814static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1815 /* out */ std::vector<std::string>* context_dex_paths) {
1816 if (class_loader_context == nullptr) {
1817 return true;
1818 }
1819
1820 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1821
1822 // Pipe to get the hash result back from our child process.
1823 unique_fd pipe_read, pipe_write;
1824 if (!Pipe(&pipe_read, &pipe_write)) {
1825 PLOG(ERROR) << "Failed to create pipe";
1826 return false;
1827 }
1828
1829 pid_t pid = fork();
1830 if (pid == 0) {
1831 // child -- drop privileges before continuing.
1832 drop_capabilities(uid);
1833
1834 // Route stdout to `pipe_write`
1835 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1836 pipe_write.reset();
1837 pipe_read.reset();
1838
1839 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1840 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1841 }
1842
1843 /* parent */
1844 pipe_write.reset();
1845
1846 std::string str_dex_paths;
1847 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1848 PLOG(ERROR) << "Failed to read from pipe";
1849 return false;
1850 }
1851 pipe_read.reset();
1852
1853 int return_code = wait_child(pid);
1854 if (!WIFEXITED(return_code)) {
1855 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1856 return false;
1857 }
1858
1859 constexpr int kFlattenClassLoaderContextSuccess = 50;
1860 return_code = WEXITSTATUS(return_code);
1861 if (return_code != kFlattenClassLoaderContextSuccess) {
1862 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1863 return false;
1864 }
1865
1866 if (!str_dex_paths.empty()) {
1867 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1868 }
1869 return true;
1870}
1871
1872static int open_dex_paths(const std::vector<std::string>& dex_paths,
1873 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1874 for (const std::string& dex_path : dex_paths) {
1875 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1876 if (zip_fds->back().get() < 0) {
1877 *error_msg = StringPrintf(
1878 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1879 if (errno == ENOENT) {
1880 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1881 } else {
1882 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1883 }
1884 }
1885 }
1886 return 0;
1887}
1888
1889static std::string join_fds(const std::vector<unique_fd>& fds) {
1890 std::stringstream ss;
1891 bool is_first = true;
1892 for (const unique_fd& fd : fds) {
1893 if (is_first) {
1894 is_first = false;
1895 } else {
1896 ss << ":";
1897 }
1898 ss << fd.get();
1899 }
1900 return ss.str();
1901}
1902
Calin Juravlec9eab382017-01-25 01:17:17 -08001903// 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 -08001904// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1905// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001906// When returning true, the output parameters will be:
1907// - is_public_out: whether or not the oat file should not be made public
1908// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1909// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001910static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001911 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001912 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001913 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001914 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001915 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001916 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001917 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1918 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001919 return false;
1920 }
Calin Juravle7d765462017-09-04 15:57:10 -07001921 // Compute the oat dir as it's not easy to extract it from the child computation.
1922 char oat_path[PKG_PATH_MAX];
1923 char oat_dir[PKG_PATH_MAX];
1924 char oat_isa_dir[PKG_PATH_MAX];
1925 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001926 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1927 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001928 return false;
1929 }
Calin Juravle7d765462017-09-04 15:57:10 -07001930 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001931
Calin Juravle80a21252017-01-17 14:43:25 -08001932 pid_t pid = fork();
1933 if (pid == 0) {
1934 // child -- drop privileges before continuing.
1935 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001936
1937 // Validate the path structure.
1938 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1939 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001940 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001941 }
1942
1943 // Open the dex file.
1944 unique_fd zip_fd;
1945 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1946 if (zip_fd.get() < 0) {
1947 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001948 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001949 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001950 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001951 }
1952 }
1953
David Brazdil4f6027a2019-03-19 11:44:21 +00001954 // Open class loader context dex files.
1955 std::vector<unique_fd> context_zip_fds;
1956 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1957 if (open_dex_paths_rc != 0) {
1958 _exit(open_dex_paths_rc);
1959 }
1960
Calin Juravle7d765462017-09-04 15:57:10 -07001961 // Prepare the oat directories.
1962 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001963 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001964 }
1965
1966 // Open the vdex/oat files if any.
1967 unique_fd oat_file_fd;
1968 unique_fd vdex_file_fd;
1969 if (!maybe_open_oat_and_vdex_file(dex_path,
1970 *oat_dir_out,
1971 instruction_set,
1972 true /* is_secondary_dex */,
1973 &oat_file_fd,
1974 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001975 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001976 }
1977
1978 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001979 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1980 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001981
1982 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001983 // Note that we do not do it before the fork since opening the files is required to happen
1984 // after forking.
1985 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1986 vdex_file_fd.get(),
1987 oat_file_fd.get(),
1988 zip_fd.get(),
1989 instruction_set,
1990 compiler_filter, profile_was_updated,
1991 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001992 class_loader_context,
1993 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001994 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001995 }
1996
1997 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001998 int result = wait_child(pid);
1999 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002000 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2001 dex_path.c_str(),
2002 result);
2003 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002004 return false;
2005 }
2006 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002007 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002008 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2009 result,
2010 dexopt_needed_out,
2011 error_msg);
2012 if (!success) {
2013 LOG(ERROR) << *error_msg;
2014 }
Calin Juravle7d765462017-09-04 15:57:10 -07002015
2016 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2017
Calin Juravle80a21252017-01-17 14:43:25 -08002018 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002019 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2020 // makes the code simpler; force compilation is only needed during tests).
2021 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002022 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002023 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002024 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2025 }
2026
Calin Juravle7d765462017-09-04 15:57:10 -07002027 // Check if we should make the oat file public.
2028 // Note that if the dex file is not public the compiled code cannot be made public.
2029 // It is ok to check this flag outside in the parent process.
2030 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2031
Calin Juravle80a21252017-01-17 14:43:25 -08002032 return success;
2033}
2034
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002035static std::string format_dexopt_error(int status, const char* dex_path) {
2036 if (WIFEXITED(status)) {
2037 int int_code = WEXITSTATUS(status);
2038 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2039 if (code_name != nullptr) {
2040 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2041 }
2042 }
2043 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002044}
2045
Calin Juravlec9eab382017-01-25 01:17:17 -08002046int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002047 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002048 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002049 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002050 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002051 CHECK(pkgname != nullptr);
2052 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002053 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002054 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2055 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002056
Calin Juravled23dee72017-07-06 16:29:11 -07002057 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002058 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002059 return -1;
2060 }
2061
2062 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002063 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2064 class_loader_context);
2065 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002066 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002067 }
2068
Calin Juravleebc8a792017-04-04 20:21:05 -07002069 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002070 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2071 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2072 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002073 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002074 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002075 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002076 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002077 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002078
2079 // Check if we're dealing with a secondary dex file and if we need to compile it.
2080 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002081 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002082 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002083 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2084 *error_msg = "Failed acquiring context dex paths";
2085 return -1; // We had an error, logged in the process method.
2086 }
2087
Calin Juravlec9eab382017-01-25 01:17:17 -08002088 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002089 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002090 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002091 oat_dir = oat_dir_str.c_str();
2092 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2093 return 0; // Nothing to do, report success.
2094 }
2095 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002096 if (error_msg->empty()) { // TODO: Make this a CHECK.
2097 *error_msg = "Failed processing secondary.";
2098 }
Calin Juravle80a21252017-01-17 14:43:25 -08002099 return -1; // We had an error, logged in the process method.
2100 }
2101 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002102 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002103 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002104 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2105 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2106 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002107
2108 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002109 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002110 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002111 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2112 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002113 return -1;
2114 }
2115
David Brazdil4f6027a2019-03-19 11:44:21 +00002116 // Open class loader context dex files.
2117 std::vector<unique_fd> context_input_fds;
2118 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2119 LOG(ERROR) << *error_msg;
2120 return -1;
2121 }
2122
Calin Juravle7a570e82017-01-14 16:23:30 -08002123 // Create the output OAT file.
2124 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002125 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002126 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002127 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002128 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002129 return -1;
2130 }
2131
2132 // Open vdex files.
2133 Dex2oatFileWrapper in_vdex_fd;
2134 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002135 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2136 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002137 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002138 return -1;
2139 }
2140
Calin Juravlecb556e32017-04-04 20:22:50 -07002141 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2142 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2143 // fully inherit their parent context).
2144 // Note that for primary apk the oat files are created before, in a separate installd
2145 // call which also does the restorecon. TODO(calin): unify the paths.
2146 if (is_secondary_dex) {
2147 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2148 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002149 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2150 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002151 return -1;
2152 }
2153 }
2154
Jeff Sharkey90aff262016-12-12 14:28:24 -07002155 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002156 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002157
Calin Juravle7a570e82017-01-14 16:23:30 -08002158 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002159 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002160 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002161
liulvping61907742018-08-21 09:36:52 +08002162 if (reference_profile_fd.get() == -1) {
2163 // We don't create an app image without reference profile since there is no speedup from
2164 // loading it in that case and instead will be a small overhead.
2165 generate_app_image = false;
2166 }
2167
2168 // Create the app image file if needed.
2169 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2170 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2171
Calin Juravle62c5a372018-02-01 17:03:23 +00002172 unique_fd dex_metadata_fd;
2173 if (dex_metadata_path != nullptr) {
2174 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2175 if (dex_metadata_fd.get() < 0) {
2176 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2177 }
2178 }
2179
Andreas Gampe023b2242018-02-28 16:03:25 -08002180 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002181
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002182 RunDex2Oat runner(input_fd.get(),
2183 out_oat_fd.get(),
2184 in_vdex_fd.get(),
2185 out_vdex_fd.get(),
2186 image_fd.get(),
2187 dex_path,
2188 out_oat_path,
2189 swap_fd.get(),
2190 instruction_set,
2191 compiler_filter,
2192 debuggable,
2193 boot_complete,
2194 background_job_compile,
2195 reference_profile_fd.get(),
2196 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002197 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002198 target_sdk_version,
2199 enable_hidden_api_checks,
2200 generate_compact_dex,
2201 dex_metadata_fd.get(),
2202 compilation_reason);
2203
Jeff Sharkey90aff262016-12-12 14:28:24 -07002204 pid_t pid = fork();
2205 if (pid == 0) {
2206 /* child -- drop privileges before continuing */
2207 drop_capabilities(uid);
2208
Richard Uhler76cc0272016-12-08 10:46:35 +00002209 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002210 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002211 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002212 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002213 }
2214
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002215 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002216 } else {
2217 int res = wait_child(pid);
2218 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002219 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002220 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002221 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2222 << std::hex << std::setw(4) << res << ", process failed";
2223 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002224 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002225 }
2226 }
2227
Calin Juravlec9eab382017-01-25 01:17:17 -08002228 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002229
2230 // We've been successful, don't delete output.
2231 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002232 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002233 image_fd.SetCleanup(false);
2234 reference_profile_fd.SetCleanup(false);
2235
2236 return 0;
2237}
2238
Calin Juravlec9eab382017-01-25 01:17:17 -08002239// Try to remove the given directory. Log an error if the directory exists
2240// and is empty but could not be removed.
2241static bool rmdir_if_empty(const char* dir) {
2242 if (rmdir(dir) == 0) {
2243 return true;
2244 }
2245 if (errno == ENOENT || errno == ENOTEMPTY) {
2246 return true;
2247 }
2248 PLOG(ERROR) << "Failed to remove dir: " << dir;
2249 return false;
2250}
2251
2252// Try to unlink the given file. Log an error if the file exists and could not
2253// be unlinked.
2254static bool unlink_if_exists(const std::string& file) {
2255 if (unlink(file.c_str()) == 0) {
2256 return true;
2257 }
2258 if (errno == ENOENT) {
2259 return true;
2260
2261 }
2262 PLOG(ERROR) << "Could not unlink: " << file;
2263 return false;
2264}
2265
Calin Juravle7d765462017-09-04 15:57:10 -07002266enum ReconcileSecondaryDexResult {
2267 kReconcileSecondaryDexExists = 0,
2268 kReconcileSecondaryDexCleanedUp = 1,
2269 kReconcileSecondaryDexValidationError = 2,
2270 kReconcileSecondaryDexCleanUpError = 3,
2271 kReconcileSecondaryDexAccessIOError = 4,
2272};
Calin Juravlec9eab382017-01-25 01:17:17 -08002273
2274// Reconcile the secondary dex 'dex_path' and its generated oat files.
2275// Return true if all the parameters are valid and the secondary dex file was
2276// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2277// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2278// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2279// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2280// Return false if there were errors during processing. In this case
2281// out_secondary_dex_exists will be set to false.
2282bool reconcile_secondary_dex_file(const std::string& dex_path,
2283 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002284 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002285 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002286 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002287 if (isas.size() == 0) {
2288 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2289 return false;
2290 }
2291
Calin Juravle7d765462017-09-04 15:57:10 -07002292 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2293 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2294 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002295 return false;
2296 }
2297
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002298 // As a security measure we want to unlink art artifacts with the reduced capabilities
2299 // of the package user id. So we fork and drop capabilities in the child.
2300 pid_t pid = fork();
2301 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002302 /* child -- drop privileges before continuing */
2303 drop_capabilities(uid);
2304
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002305 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002306 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002307 uid, storage_flag)) {
2308 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2309 _exit(kReconcileSecondaryDexValidationError);
2310 }
2311
2312 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2313 switch (access_check) {
2314 case kSecondaryDexAccessDoesNotExist:
2315 // File does not exist. Proceed with cleaning.
2316 break;
2317 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2318 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2319 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2320 default:
2321 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2322 _exit(kReconcileSecondaryDexValidationError);
2323 }
2324
2325 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002326 char oat_path[PKG_PATH_MAX];
2327 char oat_dir[PKG_PATH_MAX];
2328 char oat_isa_dir[PKG_PATH_MAX];
2329 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002330 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002331 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002332 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002333 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2334 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002335 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002336 }
Calin Juravle51314092017-05-18 15:33:05 -07002337
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002338 // Delete oat/vdex/art files.
2339 result = unlink_if_exists(oat_path) && result;
2340 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2341 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002342
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002343 // Delete profiles.
2344 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002345 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002346 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002347 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002348 result = unlink_if_exists(current_profile) && result;
2349 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002350
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002351 // We upgraded once the location of current profile for secondary dex files.
2352 // Check for any previous left-overs and remove them as well.
2353 std::string old_current_profile = dex_path + ".prof";
2354 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002355
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002356 // Try removing the directories as well, they might be empty.
2357 result = rmdir_if_empty(oat_isa_dir) && result;
2358 result = rmdir_if_empty(oat_dir) && result;
2359 }
Calin Juravle7d765462017-09-04 15:57:10 -07002360 if (!result) {
2361 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2362 }
2363 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002364 }
2365
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002366 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002367 if (!WIFEXITED(return_code)) {
2368 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2369 } else {
2370 return_code = WEXITSTATUS(return_code);
2371 }
2372
2373 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2374
2375 switch (return_code) {
2376 case kReconcileSecondaryDexCleanedUp:
2377 case kReconcileSecondaryDexValidationError:
2378 // If we couldn't validate assume the dex file does not exist.
2379 // This will purge the entry from the PM records.
2380 *out_secondary_dex_exists = false;
2381 return true;
2382 case kReconcileSecondaryDexExists:
2383 *out_secondary_dex_exists = true;
2384 return true;
2385 case kReconcileSecondaryDexAccessIOError:
2386 // We had an access IO error.
2387 // Return false so that we can try again.
2388 // The value of out_secondary_dex_exists does not matter in this case and by convention
2389 // is set to false.
2390 *out_secondary_dex_exists = false;
2391 return false;
2392 default:
2393 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2394 *out_secondary_dex_exists = false;
2395 return false;
2396 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002397}
2398
Alan Stokesa25d90c2017-10-16 10:56:00 +01002399// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2400// Returns true if all parameters are valid and the hash successfully computed and stored in
2401// out_secondary_dex_hash.
2402// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2403// the app.
2404// For any other errors (e.g. if any of the parameters are invalid) returns false.
2405bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002406 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002407 std::vector<uint8_t>* out_secondary_dex_hash) {
2408 out_secondary_dex_hash->clear();
2409
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002410 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002411
2412 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2413 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2414 << storage_flag;
2415 return false;
2416 }
2417
2418 // Pipe to get the hash result back from our child process.
2419 unique_fd pipe_read, pipe_write;
2420 if (!Pipe(&pipe_read, &pipe_write)) {
2421 PLOG(ERROR) << "Failed to create pipe";
2422 return false;
2423 }
2424
2425 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2426 // access data the app itself can access.
2427 pid_t pid = fork();
2428 if (pid == 0) {
2429 // child -- drop privileges before continuing
2430 drop_capabilities(uid);
2431 pipe_read.reset();
2432
2433 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2434 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002435 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002436 }
2437
2438 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2439 if (fd == -1) {
2440 if (errno == EACCES || errno == ENOENT) {
2441 // Not treated as an error.
2442 _exit(0);
2443 }
2444 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002445 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002446 }
2447
2448 SHA256_CTX ctx;
2449 SHA256_Init(&ctx);
2450
2451 std::vector<uint8_t> buffer(65536);
2452 while (true) {
2453 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2454 if (bytes_read == 0) {
2455 break;
2456 } else if (bytes_read == -1) {
2457 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002458 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002459 }
2460
2461 SHA256_Update(&ctx, buffer.data(), bytes_read);
2462 }
2463
2464 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2465 SHA256_Final(hash.data(), &ctx);
2466 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002467 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002468 }
2469
2470 _exit(0);
2471 }
2472
2473 // parent
2474 pipe_write.reset();
2475
2476 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2477 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2478 out_secondary_dex_hash->clear();
2479 }
2480 return wait_child(pid) == 0;
2481}
2482
Jeff Sharkey90aff262016-12-12 14:28:24 -07002483// Helper for move_ab, so that we can have common failure-case cleanup.
2484static bool unlink_and_rename(const char* from, const char* to) {
2485 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2486 // return a failure.
2487 struct stat s;
2488 if (stat(to, &s) == 0) {
2489 if (!S_ISREG(s.st_mode)) {
2490 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2491 return false;
2492 }
2493 if (unlink(to) != 0) {
2494 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2495 return false;
2496 }
2497 } else {
2498 // This may be a permission problem. We could investigate the error code, but we'll just
2499 // let the rename failure do the work for us.
2500 }
2501
2502 // Try to rename "to" to "from."
2503 if (rename(from, to) != 0) {
2504 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2505 return false;
2506 }
2507 return true;
2508}
2509
2510// Move/rename a B artifact (from) to an A artifact (to).
2511static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2512 // Check whether B exists.
2513 {
2514 struct stat s;
2515 if (stat(b_path.c_str(), &s) != 0) {
2516 // Silently ignore for now. The service calling this isn't smart enough to understand
2517 // lack of artifacts at the moment.
2518 return false;
2519 }
2520 if (!S_ISREG(s.st_mode)) {
2521 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2522 // Try to unlink, but swallow errors.
2523 unlink(b_path.c_str());
2524 return false;
2525 }
2526 }
2527
2528 // Rename B to A.
2529 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2530 // Delete the b_path so we don't try again (or fail earlier).
2531 if (unlink(b_path.c_str()) != 0) {
2532 PLOG(ERROR) << "Could not unlink " << b_path;
2533 }
2534
2535 return false;
2536 }
2537
2538 return true;
2539}
2540
2541bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2542 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002543 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2544 if (slot_suffix.empty()) {
2545 return false;
2546 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002547
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002548 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2549 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2550 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002551 }
2552
2553 // Validate other inputs.
2554 if (validate_apk_path(apk_path) != 0) {
2555 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2556 return false;
2557 }
2558 if (validate_apk_path(oat_dir) != 0) {
2559 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2560 return false;
2561 }
2562
2563 char a_path[PKG_PATH_MAX];
2564 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2565 return false;
2566 }
2567 const std::string a_vdex_path = create_vdex_filename(a_path);
2568 const std::string a_image_path = create_image_filename(a_path);
2569
2570 // B path = A path + slot suffix.
2571 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2572 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2573 const std::string b_image_path = StringPrintf("%s.%s",
2574 a_image_path.c_str(),
2575 slot_suffix.c_str());
2576
2577 bool success = true;
2578 if (move_ab_path(b_path, a_path)) {
2579 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2580 // Note: we can live without an app image. As such, ignore failure to move the image file.
2581 // If we decide to require the app image, or the app image being moved correctly,
2582 // then change accordingly.
2583 constexpr bool kIgnoreAppImageFailure = true;
2584
2585 if (!a_image_path.empty()) {
2586 if (!move_ab_path(b_image_path, a_image_path)) {
2587 unlink(a_image_path.c_str());
2588 if (!kIgnoreAppImageFailure) {
2589 success = false;
2590 }
2591 }
2592 }
2593 } else {
2594 // Cleanup: delete B image, ignore errors.
2595 unlink(b_image_path.c_str());
2596 success = false;
2597 }
2598 } else {
2599 // Cleanup: delete B image, ignore errors.
2600 unlink(b_vdex_path.c_str());
2601 unlink(b_image_path.c_str());
2602 success = false;
2603 }
2604 return success;
2605}
2606
2607bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2608 // Delete the oat/odex file.
2609 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002610 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002611 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002612 return false;
2613 }
2614
2615 // In case of a permission failure report the issue. Otherwise just print a warning.
2616 auto unlink_and_check = [](const char* path) -> bool {
2617 int result = unlink(path);
2618 if (result != 0) {
2619 if (errno == EACCES || errno == EPERM) {
2620 PLOG(ERROR) << "Could not unlink " << path;
2621 return false;
2622 }
2623 PLOG(WARNING) << "Could not unlink " << path;
2624 }
2625 return true;
2626 };
2627
2628 // Delete the oat/odex file.
2629 bool return_value_oat = unlink_and_check(out_path);
2630
2631 // Derive and delete the app image.
2632 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2633
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002634 // Derive and delete the vdex file.
2635 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2636
Jeff Sharkey90aff262016-12-12 14:28:24 -07002637 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002638 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002639}
2640
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002641static bool is_absolute_path(const std::string& path) {
2642 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2643 LOG(ERROR) << "Invalid absolute path " << path;
2644 return false;
2645 } else {
2646 return true;
2647 }
2648}
2649
2650static bool is_valid_instruction_set(const std::string& instruction_set) {
2651 // TODO: add explicit whitelisting of instruction sets
2652 if (instruction_set.find('/') != std::string::npos) {
2653 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2654 return false;
2655 } else {
2656 return true;
2657 }
2658}
2659
2660bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2661 const char *apk_path, const char *instruction_set) {
2662 std::string oat_dir_ = oat_dir;
2663 std::string apk_path_ = apk_path;
2664 std::string instruction_set_ = instruction_set;
2665
2666 if (!is_absolute_path(oat_dir_)) return false;
2667 if (!is_absolute_path(apk_path_)) return false;
2668 if (!is_valid_instruction_set(instruction_set_)) return false;
2669
2670 std::string::size_type end = apk_path_.rfind('.');
2671 std::string::size_type start = apk_path_.rfind('/', end);
2672 if (end == std::string::npos || start == std::string::npos) {
2673 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2674 return false;
2675 }
2676
2677 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2678 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2679 const char* res = res_.c_str();
2680 if (strlen(res) >= PKG_PATH_MAX) {
2681 LOG(ERROR) << "Result too large";
2682 return false;
2683 } else {
2684 strlcpy(path, res, PKG_PATH_MAX);
2685 return true;
2686 }
2687}
2688
2689bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2690 const char *instruction_set) {
2691 std::string apk_path_ = apk_path;
2692 std::string instruction_set_ = instruction_set;
2693
2694 if (!is_absolute_path(apk_path_)) return false;
2695 if (!is_valid_instruction_set(instruction_set_)) return false;
2696
2697 std::string::size_type end = apk_path_.rfind('.');
2698 std::string::size_type start = apk_path_.rfind('/', end);
2699 if (end == std::string::npos || start == std::string::npos) {
2700 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2701 return false;
2702 }
2703
2704 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2705 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2706}
2707
2708bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2709 const char *instruction_set) {
2710 std::string src_ = src;
2711 std::string instruction_set_ = instruction_set;
2712
2713 if (!is_absolute_path(src_)) return false;
2714 if (!is_valid_instruction_set(instruction_set_)) return false;
2715
2716 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2717 if (*it == '/') {
2718 *it = '@';
2719 }
2720 }
2721
2722 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2723 + DALVIK_CACHE_POSTFIX;
2724 const char* res = res_.c_str();
2725 if (strlen(res) >= PKG_PATH_MAX) {
2726 LOG(ERROR) << "Result too large";
2727 return false;
2728 } else {
2729 strlcpy(path, res, PKG_PATH_MAX);
2730 return true;
2731 }
2732}
2733
Calin Juravle59f7ab82018-04-27 17:50:23 -07002734bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2735 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002736 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2737 for (const std::string& elem : classpaths_elems) {
2738 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2739 if (fd < 0) {
2740 PLOG(ERROR) << "Could not open classpath elem " << elem;
2741 return false;
2742 } else {
2743 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002744 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002745 }
2746 }
2747 return true;
2748}
2749
2750static bool create_app_profile_snapshot(int32_t app_id,
2751 const std::string& package_name,
2752 const std::string& profile_name,
2753 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002754 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2755
Calin Juravle824a64d2018-01-18 20:23:17 -08002756 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002757 if (snapshot_fd < 0) {
2758 return false;
2759 }
2760
2761 std::vector<unique_fd> profiles_fd;
2762 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002763 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2764 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002765 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2766 return false;
2767 }
2768
2769 profiles_fd.push_back(std::move(reference_profile_fd));
2770
Calin Juravle0d0a4922018-01-23 19:54:11 -08002771 // Open the class paths elements. These will be used to filter out profile data that does
2772 // not belong to the classpath during merge.
2773 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002774 std::vector<std::string> dex_locations;
2775 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002776 return false;
2777 }
2778
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002779 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002780 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002781 pid_t pid = fork();
2782 if (pid == 0) {
2783 /* child -- drop privileges before continuing */
2784 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002785 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002786 }
2787
2788 /* parent */
2789 int return_code = wait_child(pid);
2790 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002791 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002792 return false;
2793 }
2794
Calin Juravle78728f32019-11-08 17:55:46 -08002795 // Verify that profman finished successfully.
2796 int profman_code = WEXITSTATUS(return_code);
2797 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2798 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2799 << ":" << profman_code;
2800 return false;
2801 }
Calin Juravle29591732017-11-20 17:46:19 -08002802 return true;
2803}
2804
Calin Juravle0d0a4922018-01-23 19:54:11 -08002805static bool create_boot_image_profile_snapshot(const std::string& package_name,
2806 const std::string& profile_name,
2807 const std::string& classpath) {
2808 // The reference profile directory for the android package might not be prepared. Do it now.
2809 const std::string ref_profile_dir =
2810 create_primary_reference_profile_package_dir_path(package_name);
2811 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2812 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2813 return false;
2814 }
2815
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002816 // Return false for empty class path since it may otherwise return true below if profiles is
2817 // empty.
2818 if (classpath.empty()) {
2819 PLOG(ERROR) << "Class path is empty";
2820 return false;
2821 }
2822
Calin Juravle0d0a4922018-01-23 19:54:11 -08002823 // Open and create the snapshot profile.
2824 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2825
2826 // Collect all non empty profiles.
2827 // The collection will traverse all applications profiles and find the non empty files.
2828 // This has the potential of inspecting a large number of files and directories (depending
2829 // on the number of applications and users). So there is a slight increase in the chance
2830 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2831 // fail the snapshot and aggregate whatever profile we could open.
2832 //
2833 // The profile snapshot is a best effort based on available data it's ok if some data
2834 // from some apps is missing. It will be counter productive for the snapshot to fail
2835 // because we could not open or read some of the files.
2836 std::vector<std::string> profiles;
2837 if (!collect_profiles(&profiles)) {
2838 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2839 }
2840
2841 // If we have no profiles return early.
2842 if (profiles.empty()) {
2843 return true;
2844 }
2845
2846 // Open the classpath elements. These will be used to filter out profile data that does
2847 // not belong to the classpath during merge.
2848 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002849 std::vector<std::string> dex_locations;
2850 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002851 return false;
2852 }
2853
2854 // If we could not open any files from the classpath return an error.
2855 if (apk_fds.empty()) {
2856 LOG(ERROR) << "Could not open any of the classpath elements.";
2857 return false;
2858 }
2859
2860 // Aggregate the profiles in batches of kAggregationBatchSize.
2861 // We do this to avoid opening a huge a amount of files.
2862 static constexpr size_t kAggregationBatchSize = 10;
2863
Calin Juravle0d0a4922018-01-23 19:54:11 -08002864 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002865 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002866 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2867 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2868 if (fd.get() >= 0) {
2869 profiles_fd.push_back(std::move(fd));
2870 }
2871 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002872
2873 // We aggregate (read & write) into the same fd multiple times in a row.
2874 // We need to reset the cursor every time to ensure we read the whole file every time.
2875 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2876 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2877 return false;
2878 }
2879
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002880 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002881 args.SetupMerge(profiles_fd,
2882 snapshot_fd,
2883 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002884 dex_locations,
2885 /*for_snapshot=*/true,
2886 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002887 pid_t pid = fork();
2888 if (pid == 0) {
2889 /* child -- drop privileges before continuing */
2890 drop_capabilities(AID_SYSTEM);
2891
Calin Juravle59f7ab82018-04-27 17:50:23 -07002892 // The introduction of new access flags into boot jars causes them to
2893 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002894 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002895 }
2896
2897 /* parent */
2898 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002899
Calin Juravle0d0a4922018-01-23 19:54:11 -08002900 if (!WIFEXITED(return_code)) {
2901 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2902 return false;
2903 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002904
2905 // Verify that profman finished successfully.
2906 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002907 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2908 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2909 << ":" << profman_code;
2910 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002911 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002912 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002913
Calin Juravle0d0a4922018-01-23 19:54:11 -08002914 return true;
2915}
2916
2917bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2918 const std::string& profile_name, const std::string& classpath) {
2919 if (app_id == -1) {
2920 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2921 } else {
2922 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2923 }
2924}
2925
Calin Juravlec3b049e2018-01-18 22:32:58 -08002926bool prepare_app_profile(const std::string& package_name,
2927 userid_t user_id,
2928 appid_t app_id,
2929 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002930 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002931 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002932 // Prepare the current profile.
2933 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2934 /*is_secondary_dex*/ false);
2935 uid_t uid = multiuser_get_uid(user_id, app_id);
2936 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2937 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2938 return false;
2939 }
2940
2941 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002942 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002943 return true;
2944 }
2945
2946 // We have a dex metdata. Merge the profile into the reference profile.
2947 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2948 /*read_write*/ true, /*is_secondary_dex*/ false);
2949 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2950 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002951 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2952 if (apk_fd < 0) {
2953 PLOG(ERROR) << "Could not open code path " << code_path;
2954 return false;
2955 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002956
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002957 RunProfman args;
2958 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2959 std::move(ref_profile_fd),
2960 std::move(apk_fd),
2961 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002962 pid_t pid = fork();
2963 if (pid == 0) {
2964 /* child -- drop privileges before continuing */
2965 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2966 drop_capabilities(app_shared_gid);
2967
Calin Juravlef63d4792018-01-30 17:43:34 +00002968 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002969 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002970 }
2971
2972 /* parent */
2973 int return_code = wait_child(pid);
2974 if (!WIFEXITED(return_code)) {
2975 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2976 return false;
2977 }
2978 return true;
2979}
2980
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002981} // namespace installd
2982} // namespace android