blob: 91b0e75473a4b1045d197c7474e8a748827ac4d5 [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.
302static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
303// Location of the apex image.
304static const char* kApexImage = "/system/framework/apex.art";
305
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700306// Phenotype property name for enabling profiling the boot class path.
307static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
308
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800309class RunDex2Oat : public ExecVHelper {
310 public:
311 RunDex2Oat(int zip_fd,
312 int oat_fd,
313 int input_vdex_fd,
314 int output_vdex_fd,
315 int image_fd,
316 const char* input_file_name,
317 const char* output_file_name,
318 int swap_fd,
319 const char* instruction_set,
320 const char* compiler_filter,
321 bool debuggable,
322 bool post_bootcomplete,
323 bool background_job_compile,
324 int profile_fd,
325 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000326 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800327 int target_sdk_version,
328 bool enable_hidden_api_checks,
329 bool generate_compact_dex,
330 int dex_metadata_fd,
331 const char* compilation_reason) {
332 // Get the relative path to the input file.
333 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700334
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800335 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
336 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700337
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800338 const char* threads_property = post_bootcomplete
339 ? "dalvik.vm.dex2oat-threads"
340 : "dalvik.vm.boot-dex2oat-threads";
341 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Orion Hodson45837462019-11-14 18:20:17 +0000342 const char* cpu_set_property = post_bootcomplete
343 ? "dalvik.vm.dex2oat-cpu-set"
344 : "dalvik.vm.boot-dex2oat-cpu-set";
345 std::string dex2oat_cpu_set_arg = MapPropertyToArg(cpu_set_property, "--cpu-set=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700346
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000347 std::string bootclasspath;
348 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
349 if (dex2oat_bootclasspath != nullptr) {
350 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
351 }
352 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
353 // BOOTCLASSPATH.
354
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800355 const std::string dex2oat_isa_features_key =
356 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
357 std::string instruction_set_features_arg =
358 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700359
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800360 const std::string dex2oat_isa_variant_key =
361 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
362 std::string instruction_set_variant_arg =
363 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700364
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800365 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700366
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800367 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
368 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
369 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700370
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800371 // If we are booting without the real /data, don't spend time compiling.
372 std::string vold_decrypt = GetProperty("vold.decrypt", "");
373 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
374 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700375
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800376 std::string resolve_startup_string_arg =
377 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
378 "--resolve-startup-const-strings=%s");
379 if (resolve_startup_string_arg.empty()) {
380 // If empty, fall back to system property.
381 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800382 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
383 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800384 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800385
386 const std::string image_block_size_arg =
387 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
388 "--max-image-block-size=%s");
389
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800390 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700391
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800392 std::string image_format_arg;
393 if (image_fd >= 0) {
394 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000395 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000396
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800397 std::string dex2oat_large_app_threshold_arg =
398 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000399
Calin Juravlef74a7372019-02-28 20:29:41 -0800400
401 const char* dex2oat_bin = select_execution_binary(
402 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000403
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800404 bool generate_minidebug_info = kEnableMinidebugInfo &&
405 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000406
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000407 std::string boot_image;
408 std::string use_apex_image =
409 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
410 ENABLE_APEX_IMAGE,
411 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700412
413 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
414 profile_boot_class_path =
415 server_configurable_flags::GetServerConfigurableFlag(
416 RUNTIME_NATIVE_BOOT_NAMESPACE,
417 PROFILE_BOOT_CLASS_PATH,
418 /*default_value=*/ profile_boot_class_path);
419
420 if (use_apex_image == "true" || profile_boot_class_path == "true") {
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000421 boot_image = StringPrintf("-Ximage:%s", kApexImage);
422 } else {
423 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
424 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000425
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800426 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
427 // use arraysize instead.
428 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
429 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
430 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
431 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
432 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
433 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
434 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
435 std::string dex2oat_compiler_filter_arg;
436 std::string dex2oat_swap_fd;
437 std::string dex2oat_image_fd;
438 std::string target_sdk_version_arg;
439 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000440 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800441 }
442 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000443 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800444 if (class_loader_context != nullptr) {
445 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
446 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000447 if (!class_loader_context_fds.empty()) {
448 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
449 class_loader_context_fds.c_str());
450 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800451 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000452
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800453 if (swap_fd >= 0) {
454 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
455 }
456 if (image_fd >= 0) {
457 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
458 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000459
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800460 // Compute compiler filter.
461 bool have_dex2oat_relocation_skip_flag = false;
462 if (skip_compilation) {
463 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
464 have_dex2oat_relocation_skip_flag = true;
465 } else if (compiler_filter != nullptr) {
466 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
467 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000468
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800469 if (dex2oat_compiler_filter_arg.empty()) {
470 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
471 "--compiler-filter=%s");
472 }
473
474 // Check whether all apps should be compiled debuggable.
475 if (!debuggable) {
476 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
477 }
478 std::string profile_arg;
479 if (profile_fd != -1) {
480 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
481 }
482
483 // Get the directory of the apk to pass as a base classpath directory.
484 std::string base_dir;
485 std::string apk_dir(input_file_name);
486 unsigned long dir_index = apk_dir.rfind('/');
487 bool has_base_dir = dir_index != std::string::npos;
488 if (has_base_dir) {
489 apk_dir = apk_dir.substr(0, dir_index);
490 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
491 }
492
493 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
494
495 std::string compilation_reason_arg = compilation_reason == nullptr
496 ? ""
497 : std::string("--compilation-reason=") + compilation_reason;
498
499 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
500
501 // Disable cdex if update input vdex is true since this combination of options is not
502 // supported.
503 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
504
505 AddArg(zip_fd_arg);
506 AddArg(zip_location_arg);
507 AddArg(input_vdex_fd_arg);
508 AddArg(output_vdex_fd_arg);
509 AddArg(oat_fd_arg);
510 AddArg(oat_location_arg);
511 AddArg(instruction_set_arg);
512
513 AddArg(instruction_set_variant_arg);
514 AddArg(instruction_set_features_arg);
515
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000516 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000517 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800518 AddRuntimeArg(dex2oat_Xms_arg);
519 AddRuntimeArg(dex2oat_Xmx_arg);
520
521 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800522 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800523 AddArg(dex2oat_compiler_filter_arg);
524 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000525 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800526 AddArg(dex2oat_swap_fd);
527 AddArg(dex2oat_image_fd);
528
529 if (generate_debug_info) {
530 AddArg("--generate-debug-info");
531 }
532 if (debuggable) {
533 AddArg("--debuggable");
534 }
535 AddArg(image_format_arg);
536 AddArg(dex2oat_large_app_threshold_arg);
537
538 if (have_dex2oat_relocation_skip_flag) {
539 AddRuntimeArg(dex2oat_norelocation);
540 }
541 AddArg(profile_arg);
542 AddArg(base_dir);
543 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000544 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800545 if (generate_minidebug_info) {
546 AddArg(kMinidebugDex2oatFlag);
547 }
548 if (disable_cdex) {
549 AddArg(kDisableCompactDexFlag);
550 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000551 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800552 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100553 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800554 }
555
556 if (dex_metadata_fd > -1) {
557 AddArg(dex_metadata_fd_arg);
558 }
559
560 AddArg(compilation_reason_arg);
561
562 // Do not add args after dex2oat_flags, they should override others for debugging.
563 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
564
565 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000566 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800567};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700568
569/*
570 * Whether dexopt should use a swap file when compiling an APK.
571 *
572 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
573 * itself, anyways).
574 *
575 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
576 *
577 * Otherwise, return true if this is a low-mem device.
578 *
579 * Otherwise, return default value.
580 */
581static bool kAlwaysProvideSwapFile = false;
582static bool kDefaultProvideSwapFile = true;
583
584static bool ShouldUseSwapFileForDexopt() {
585 if (kAlwaysProvideSwapFile) {
586 return true;
587 }
588
589 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700590 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
591 if (!dex2oat_prop_buf.empty()) {
592 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700593 }
594
595 // Shortcut for default value. This is an implementation optimization for the process sketched
596 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
597 // as low-mem is never returning false. The compiler will optimize this away if it can.
598 if (kDefaultProvideSwapFile) {
599 return true;
600 }
601
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700602 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700603 return true;
604 }
605
606 // Default value must be false here.
607 return kDefaultProvideSwapFile;
608}
609
Richard Uhler76cc0272016-12-08 10:46:35 +0000610static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611 if (set_to_bg) {
612 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800613 PLOG(ERROR) << "set_sched_policy failed";
614 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700615 }
616 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800617 PLOG(ERROR) << "setpriority failed";
618 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700619 }
620 }
621}
622
Calin Juravle29591732017-11-20 17:46:19 -0800623static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
624 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800625 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800626 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800627 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800628 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800629 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700630 }
Calin Juravle114f0812017-03-08 19:05:07 -0800631 // Profiles should belong to the app; make sure of that by giving ownership to
632 // the app uid. If we cannot do that, there's no point in returning the fd
633 // since dex2oat/profman will fail with SElinux denials.
634 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000635 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800636 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800637 }
Calin Juravle29591732017-11-20 17:46:19 -0800638 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800639}
640
Calin Juravle29591732017-11-20 17:46:19 -0800641static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800642 // Do not follow symlinks when opening a profile:
643 // - primary profiles should not contain symlinks in their paths
644 // - secondary dex paths should have been already resolved and validated
645 flags |= O_NOFOLLOW;
646
Calin Juravle29591732017-11-20 17:46:19 -0800647 // Check if we need to create the profile
648 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
649 unique_fd fd;
650 if ((flags & O_CREAT) != 0) {
651 fd = create_profile(uid, profile, flags);
652 } else {
653 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
654 }
655
Calin Juravle114f0812017-03-08 19:05:07 -0800656 if (fd.get() < 0) {
657 if (errno != ENOENT) {
658 // Profiles might be missing for various reasons. For example, in a
659 // multi-user environment, the profile directory for one user can be created
660 // after we start a merge. In this case the current profile for that user
661 // will not be found.
662 // Also, the secondary dex profiles might be deleted by the app at any time,
663 // so we can't we need to prepare if they are missing.
664 PLOG(ERROR) << "Failed to open profile " << profile;
665 }
666 return invalid_unique_fd();
667 }
668
Jeff Sharkey90aff262016-12-12 14:28:24 -0700669 return fd;
670}
671
Calin Juravle824a64d2018-01-18 20:23:17 -0800672static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
673 const std::string& location, bool is_secondary_dex) {
674 std::string profile = create_current_profile_path(user, package_name, location,
675 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800676 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800677}
678
Calin Juravle824a64d2018-01-18 20:23:17 -0800679static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
680 const std::string& location, bool read_write, bool is_secondary_dex) {
681 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800682 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
683}
684
685static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800686 const std::string& location) {
687 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800688 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800689}
690
Calin Juravle824a64d2018-01-18 20:23:17 -0800691static void open_profile_files(uid_t uid, const std::string& package_name,
692 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800693 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800695 *reference_profile_fd = open_reference_profile(uid, package_name, location,
696 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700697
Calin Juravle114f0812017-03-08 19:05:07 -0800698 // For secondary dex files, we don't really need the user but we use it for sanity checks.
699 // Note: the user owning the dex file should be the current user.
700 std::vector<userid_t> users;
701 if (is_secondary_dex){
702 users.push_back(multiuser_get_user_id(uid));
703 } else {
704 users = get_known_users(/*volume_uuid*/ nullptr);
705 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700706 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800707 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
708 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700709 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800710 if (profile_fd.get() >= 0) {
711 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712 }
713 }
714}
715
Jeff Sharkey90aff262016-12-12 14:28:24 -0700716static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
717static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
718static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
719static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
720static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
Calin Juravle78728f32019-11-08 17:55:46 -0800721static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 5;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700722
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800723class RunProfman : public ExecVHelper {
724 public:
725 void SetupArgs(const std::vector<unique_fd>& profile_fds,
726 const unique_fd& reference_profile_fd,
727 const std::vector<unique_fd>& apk_fds,
728 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800729 bool copy_and_update,
730 bool for_snapshot,
731 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800732
733 // TODO(calin): Assume for now we run in the bg compile job (which is in
734 // most of the invocation). With the current data flow, is not very easy or
735 // clean to discover this in RunProfman (it will require quite a messy refactoring).
736 const char* profman_bin = select_execution_binary(
737 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700738
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800739 if (copy_and_update) {
740 CHECK_EQ(1u, profile_fds.size());
741 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000742 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800743 if (reference_profile_fd != -1) {
744 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000745 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800746
747 for (const unique_fd& fd : profile_fds) {
748 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
749 }
750
751 for (const unique_fd& fd : apk_fds) {
752 AddArg("--apk-fd=" + std::to_string(fd.get()));
753 }
754
755 for (const std::string& dex_location : dex_locations) {
756 AddArg("--dex-location=" + dex_location);
757 }
758
759 if (copy_and_update) {
760 AddArg("--copy-and-update-profile-key");
761 }
762
Calin Juravle78728f32019-11-08 17:55:46 -0800763 if (for_snapshot) {
764 AddArg("--force-merge");
765 }
766
767 if (for_boot_image) {
768 AddArg("--boot-image-merge");
769 }
770
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800771 // Do not add after dex2oat_flags, they should override others for debugging.
772 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800773 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800775 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
776 const unique_fd& reference_profile_fd,
777 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800778 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
779 bool for_snapshot = false,
780 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800781 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800782 reference_profile_fd,
783 apk_fds,
784 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800785 /*copy_and_update=*/ false,
786 for_snapshot,
787 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800788 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800790 void SetupCopyAndUpdate(unique_fd&& profile_fd,
791 unique_fd&& reference_profile_fd,
792 unique_fd&& apk_fd,
793 const std::string& dex_location) {
794 // The fds need to stay open longer than the scope of the function, so put them into a local
795 // variable vector.
796 profiles_fd_.push_back(std::move(profile_fd));
797 apk_fds_.push_back(std::move(apk_fd));
798 reference_profile_fd_ = std::move(reference_profile_fd);
799 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800800 SetupArgs(profiles_fd_,
801 reference_profile_fd_,
802 apk_fds_,
803 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800804 /*copy_and_update=*/true,
805 /*for_snapshot*/false,
806 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800807 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000808
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800809 void SetupDump(const std::vector<unique_fd>& profiles_fd,
810 const unique_fd& reference_profile_fd,
811 const std::vector<std::string>& dex_locations,
812 const std::vector<unique_fd>& apk_fds,
813 const unique_fd& output_fd) {
814 AddArg("--dump-only");
815 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800816 SetupArgs(profiles_fd,
817 reference_profile_fd,
818 apk_fds,
819 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800820 /*copy_and_update=*/false,
821 /*for_snapshot*/false,
822 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800823 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000824
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800825 void Exec() {
826 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
827 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000828
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800829 private:
830 unique_fd reference_profile_fd_;
831 std::vector<unique_fd> profiles_fd_;
832 std::vector<unique_fd> apk_fds_;
833};
Mathieu Chartier31636522018-11-09 23:53:07 +0000834
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800835
Calin Juravlef63d4792018-01-30 17:43:34 +0000836
Jeff Sharkey90aff262016-12-12 14:28:24 -0700837// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800838// The location is the package name for primary apks or the dex path for secondary dex files.
839// Returns true if there is enough information in the current profiles that makes it
840// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841// If the return value is true all the current profiles would have been merged into
842// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800843static bool analyze_profiles(uid_t uid, const std::string& package_name,
844 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800845 std::vector<unique_fd> profiles_fd;
846 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800847 open_profile_files(uid, package_name, location, is_secondary_dex,
848 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800849 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 // Skip profile guided compilation because no profiles were found.
851 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700852 return false;
853 }
854
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800855 RunProfman profman_merge;
856 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700857 pid_t pid = fork();
858 if (pid == 0) {
859 /* child -- drop privileges before continuing */
860 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800861 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862 }
863 /* parent */
864 int return_code = wait_child(pid);
865 bool need_to_compile = false;
866 bool should_clear_current_profiles = false;
867 bool should_clear_reference_profile = false;
868 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800869 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 } else {
871 return_code = WEXITSTATUS(return_code);
872 switch (return_code) {
873 case PROFMAN_BIN_RETURN_CODE_COMPILE:
874 need_to_compile = true;
875 should_clear_current_profiles = true;
876 should_clear_reference_profile = false;
877 break;
878 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
879 need_to_compile = false;
880 should_clear_current_profiles = false;
881 should_clear_reference_profile = false;
882 break;
883 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800884 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700885 need_to_compile = false;
886 should_clear_current_profiles = true;
887 should_clear_reference_profile = true;
888 break;
889 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
890 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
891 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800892 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700893 need_to_compile = false;
894 should_clear_current_profiles = false;
895 should_clear_reference_profile = false;
896 break;
897 default:
898 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800899 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800900 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700901 need_to_compile = false;
902 should_clear_current_profiles = true;
903 should_clear_reference_profile = true;
904 break;
905 }
906 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800907
Jeff Sharkey90aff262016-12-12 14:28:24 -0700908 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800909 if (is_secondary_dex) {
910 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800911 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
912 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800913 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800914 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800915 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700916 }
917 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800918 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700919 }
920 return need_to_compile;
921}
922
Calin Juravle114f0812017-03-08 19:05:07 -0800923// Decides if profile guided compilation is needed or not based on existing profiles.
924// The analysis is done for the primary apks of the given package.
925// Returns true if there is enough information in the current profiles that makes it
926// worth to recompile the package.
927// If the return value is true all the current profiles would have been merged into
928// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800929bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
930 const std::string& profile_name) {
931 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800932}
933
Calin Juravle408cd4a2018-01-20 23:34:18 -0800934bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
935 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800936 std::vector<unique_fd> profile_fds;
937 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800938 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
939 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940
Calin Juravle408cd4a2018-01-20 23:34:18 -0800941 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800942 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700943
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800944 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700945 const bool has_profiles = !profile_fds.empty();
946
947 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800948 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700949 return false;
950 }
951
Calin Juravle114f0812017-03-08 19:05:07 -0800952 unique_fd output_fd(open(out_file_name.c_str(),
953 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800955 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956 return false;
957 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800958
Jeff Sharkey90aff262016-12-12 14:28:24 -0700959 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800960 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800961 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
962 if (apk_fd == -1) {
963 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
964 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700965 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800966 dex_locations.push_back(get_location_from_path(code_path.c_str()));
967 apk_fds.push_back(std::move(apk_fd));
968
Jeff Sharkey90aff262016-12-12 14:28:24 -0700969
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800970 RunProfman profman_dump;
971 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972 pid_t pid = fork();
973 if (pid == 0) {
974 /* child -- drop privileges before continuing */
975 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800976 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700977 }
978 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700979 int return_code = wait_child(pid);
980 if (!WIFEXITED(return_code)) {
981 LOG(WARNING) << "profman failed for package " << pkgname << ": "
982 << return_code;
983 return false;
984 }
985 return true;
986}
987
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700988bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800989 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700990 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
991 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800992 package_name,
993 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700994 /*read_write*/ true,
995 /*secondary*/ false));
996 if (in_fd.get() < 0) {
997 PLOG(WARNING) << "Could not open profile " << system_profile;
998 return false;
999 }
1000 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001001 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001002 return false;
1003 }
1004
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001005 // As a security measure we want to write the profile information with the reduced capabilities
1006 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001007 pid_t pid = fork();
1008 if (pid == 0) {
1009 /* child -- drop privileges before continuing */
1010 drop_capabilities(packageUid);
1011
1012 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1013 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001014 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001015 }
1016 // This implies that the app owning this profile is running
1017 // (and has acquired the lock).
1018 //
1019 // The app never acquires the lock for the reference profiles of primary apks.
1020 // Only dex2oat from installd will do that. Since installd is single threaded
1021 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001022 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001023 return false;
1024 }
1025
1026 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1027 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001028 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001029 }
1030
1031 // Copy over data.
1032 static constexpr size_t kBufferSize = 4 * 1024;
1033 char buffer[kBufferSize];
1034 while (true) {
1035 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1036 if (bytes == 0) {
1037 break;
1038 }
1039 write(out_fd.get(), buffer, bytes);
1040 }
1041 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001042 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001043 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001044 // Use _exit since we don't want to run the global destructors in the child.
1045 // b/62597429
1046 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001047 }
1048 /* parent */
1049 int return_code = wait_child(pid);
1050 return return_code == 0;
1051}
1052
Jeff Sharkey90aff262016-12-12 14:28:24 -07001053static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1054 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1055 if (EndsWith(oat_path, ".dex")) {
1056 std::string new_path = oat_path;
1057 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001058 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001059 return new_path;
1060 }
1061
1062 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1063 // case (where the base name will have an extension for the B artifact).
1064 size_t odex_pos = oat_path.rfind(".odex");
1065 if (odex_pos != std::string::npos) {
1066 std::string new_path = oat_path;
1067 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1068 CHECK_NE(new_path.find(new_ext), std::string::npos);
1069 return new_path;
1070 }
1071
1072 // Don't know how to handle this.
1073 return "";
1074}
1075
1076// Translate the given oat path to an art (app image) path. An empty string
1077// denotes an error.
1078static std::string create_image_filename(const std::string& oat_path) {
1079 return replace_file_extension(oat_path, ".art");
1080}
1081
1082// Translate the given oat path to a vdex path. An empty string denotes an error.
1083static std::string create_vdex_filename(const std::string& oat_path) {
1084 return replace_file_extension(oat_path, ".vdex");
1085}
1086
Jeff Sharkey90aff262016-12-12 14:28:24 -07001087static int open_output_file(const char* file_name, bool recreate, int permissions) {
1088 int flags = O_RDWR | O_CREAT;
1089 if (recreate) {
1090 if (unlink(file_name) < 0) {
1091 if (errno != ENOENT) {
1092 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1093 }
1094 }
1095 flags |= O_EXCL;
1096 }
1097 return open(file_name, flags, permissions);
1098}
1099
Calin Juravle2289c0a2017-02-15 12:44:14 -08001100static bool set_permissions_and_ownership(
1101 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1102 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1103 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104 if (fchmod(fd,
1105 S_IRUSR|S_IWUSR|S_IRGRP |
1106 (is_public ? S_IROTH : 0)) < 0) {
1107 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1108 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001109 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001110 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1111 return false;
1112 }
1113 return true;
1114}
1115
1116static bool IsOutputDalvikCache(const char* oat_dir) {
1117 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1118 // into '!'. Play it safe by handling it both.
1119 // TODO: ensure we never get null.
1120 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1121 return oat_dir == nullptr || oat_dir[0] == '!';
1122}
1123
Calin Juravled23dee72017-07-06 16:29:11 -07001124// Best-effort check whether we can fit the the path into our buffers.
1125// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1126// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1127// extension to the cache path (5 bytes).
1128// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1129static bool validate_dex_path_size(const std::string& dex_path) {
1130 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1131 LOG(ERROR) << "dex_path too long: " << dex_path;
1132 return false;
1133 }
1134 return true;
1135}
1136
Jeff Sharkey90aff262016-12-12 14:28:24 -07001137static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001138 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001139 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001140 return false;
1141 }
1142
1143 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001144 // Oat dirs for secondary dex files are already validated.
1145 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1147 return false;
1148 }
1149 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1150 return false;
1151 }
1152 } else {
1153 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1154 return false;
1155 }
1156 }
1157 return true;
1158}
1159
1160// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1161// on destruction. It will also run the given cleanup (unless told not to) after closing.
1162//
1163// Usage example:
1164//
Calin Juravle7a570e82017-01-14 16:23:30 -08001165// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001166// [name]() {
1167// unlink(name.c_str());
1168// });
1169// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1170// wrapper if captured as a reference.
1171//
1172// if (file.get() == -1) {
1173// // Error opening...
1174// }
1175//
1176// ...
1177// if (error) {
1178// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1179// // and delete the file (after the fd is closed).
1180// return -1;
1181// }
1182//
1183// (Success case)
1184// file.SetCleanup(false);
1185// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1186// // (leaving the file around; after the fd is closed).
1187//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001188class Dex2oatFileWrapper {
1189 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001190 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001191 }
1192
Calin Juravle7a570e82017-01-14 16:23:30 -08001193 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1194 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1195
1196 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1197 value_ = other.value_;
1198 cleanup_ = other.cleanup_;
1199 do_cleanup_ = other.do_cleanup_;
1200 auto_close_ = other.auto_close_;
1201 other.release();
1202 }
1203
1204 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1205 value_ = other.value_;
1206 cleanup_ = other.cleanup_;
1207 do_cleanup_ = other.do_cleanup_;
1208 auto_close_ = other.auto_close_;
1209 other.release();
1210 return *this;
1211 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001212
1213 ~Dex2oatFileWrapper() {
1214 reset(-1);
1215 }
1216
1217 int get() {
1218 return value_;
1219 }
1220
1221 void SetCleanup(bool cleanup) {
1222 do_cleanup_ = cleanup;
1223 }
1224
1225 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001226 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001227 close(value_);
1228 }
1229 if (do_cleanup_ && cleanup_ != nullptr) {
1230 cleanup_();
1231 }
1232
1233 value_ = new_value;
1234 }
1235
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 void reset(int new_value, std::function<void ()> new_cleanup) {
1237 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001238 close(value_);
1239 }
1240 if (do_cleanup_ && cleanup_ != nullptr) {
1241 cleanup_();
1242 }
1243
1244 value_ = new_value;
1245 cleanup_ = new_cleanup;
1246 }
1247
Calin Juravle7a570e82017-01-14 16:23:30 -08001248 void DisableAutoClose() {
1249 auto_close_ = false;
1250 }
1251
Jeff Sharkey90aff262016-12-12 14:28:24 -07001252 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001253 void release() {
1254 value_ = -1;
1255 do_cleanup_ = false;
1256 cleanup_ = nullptr;
1257 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001258 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001259 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001261 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001262};
1263
Calin Juravle7a570e82017-01-14 16:23:30 -08001264// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001265Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1266 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001267
1268 // We don't create an image for secondary dex files.
1269 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001270 return Dex2oatFileWrapper();
1271 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001272
Calin Juravle7a570e82017-01-14 16:23:30 -08001273 const std::string image_path = create_image_filename(out_oat_path);
1274 if (image_path.empty()) {
1275 // Happens when the out_oat_path has an unknown extension.
1276 return Dex2oatFileWrapper();
1277 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001278
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001279 // In case there is a stale image, remove it now. Ignore any error.
1280 unlink(image_path.c_str());
1281
1282 // Not enabled, exit.
1283 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001284 return Dex2oatFileWrapper();
1285 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001286 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1287 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001288 return Dex2oatFileWrapper();
1289 }
1290 // Recreate is true since we do not want to modify a mapped image. If the app is
1291 // already running and we modify the image file, it can cause crashes (b/27493510).
1292 Dex2oatFileWrapper wrapper_fd(
1293 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1294 [image_path]() { unlink(image_path.c_str()); });
1295 if (wrapper_fd.get() < 0) {
1296 // Could not create application image file. Go on since we can compile without it.
1297 LOG(ERROR) << "installd could not create '" << image_path
1298 << "' for image file during dexopt";
1299 // If we have a valid image file path but no image fd, explicitly erase the image file.
1300 if (unlink(image_path.c_str()) < 0) {
1301 if (errno != ENOENT) {
1302 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1303 }
1304 }
1305 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001306 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001307 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1308 wrapper_fd.reset(-1);
1309 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001310
Calin Juravle7a570e82017-01-14 16:23:30 -08001311 return wrapper_fd;
1312}
1313
1314// Creates the dexopt swap file if necessary and return its fd.
1315// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001316unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001317 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001318 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001319 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001320 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001321 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001322 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001323 if (swap_fd.get() < 0) {
1324 // Could not create swap file. Optimistically go on and hope that we can compile
1325 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001326 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001327 } else {
1328 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001329 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001330 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1331 }
1332 }
1333 return swap_fd;
1334}
1335
1336// Opens the reference profiles if needed.
1337// 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 -08001338Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001339 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001340 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001341 // If we are not profile guided compilation, or we are compiling system server
1342 // do not bother to open the profiles; we won't be using them.
1343 if (!profile_guided || (pkgname[0] == '*')) {
1344 return Dex2oatFileWrapper();
1345 }
1346
1347 // If this is a secondary dex path which is public do not open the profile.
1348 // We cannot compile public secondary dex paths with profiles. That's because
1349 // it will expose how the dex files are used by their owner.
1350 //
1351 // Note that the PackageManager is responsible to set the is_public flag for
1352 // primary apks and we do not check it here. In some cases, e.g. when
1353 // compiling with a public profile from the .dm file the PackageManager will
1354 // set is_public toghether with the profile guided compilation.
1355 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001356 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001357 }
Calin Juravle114f0812017-03-08 19:05:07 -08001358
1359 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001360 std::string location;
1361 if (is_secondary_dex) {
1362 location = dex_path;
1363 } else {
1364 if (profile_name == nullptr) {
1365 // This path is taken for system server re-compilation lunched from ZygoteInit.
1366 return Dex2oatFileWrapper();
1367 } else {
1368 location = profile_name;
1369 }
1370 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001371 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1372 is_secondary_dex);
1373 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1374 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001375 };
1376 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001377}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001378
Calin Juravle7a570e82017-01-14 16:23:30 -08001379// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1380// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001381bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001382 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001383 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001384 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1385 CHECK(in_vdex_wrapper_fd != nullptr);
1386 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001387 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1388 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001389 char in_odex_path[PKG_PATH_MAX];
1390 int dexopt_action = abs(dexopt_needed);
1391 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001392 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001393
1394 // Infer the name of the output VDEX.
1395 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1396 if (out_vdex_path_str.empty()) {
1397 return false;
1398 }
1399
1400 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001401 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001402 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1403 const char* path = nullptr;
1404 if (is_odex_location) {
1405 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1406 path = in_odex_path;
1407 } else {
1408 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001409 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001410 }
1411 } else {
1412 path = out_oat_path;
1413 }
1414 in_vdex_path_str = create_vdex_filename(path);
1415 if (in_vdex_path_str.empty()) {
1416 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001417 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001418 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001419 // We can update in place when all these conditions are met:
1420 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1421 // on /system typically cannot be updated in place).
1422 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1423 // cannot be currently used by a running process.
1424 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1425 // different vdex files to operate.
1426 update_vdex_in_place =
1427 (in_vdex_path_str == out_vdex_path_str) &&
1428 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1429 !profile_guided;
1430 if (update_vdex_in_place) {
1431 // Open the file read-write to be able to update it.
1432 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1433 if (in_vdex_wrapper_fd->get() == -1) {
1434 // If we failed to open the file, we cannot update it in place.
1435 update_vdex_in_place = false;
1436 }
1437 } else {
1438 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1439 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001440 }
1441
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001442 // If we are updating the vdex in place, we do not need to recreate a vdex,
1443 // and can use the same existing one.
1444 if (update_vdex_in_place) {
1445 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1446 // have bogus stale vdex files.
1447 out_vdex_wrapper_fd->reset(
1448 in_vdex_wrapper_fd->get(),
1449 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1450 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1451 // wrapper).
1452 in_vdex_wrapper_fd->DisableAutoClose();
1453 } else {
1454 out_vdex_wrapper_fd->reset(
1455 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1456 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1457 if (out_vdex_wrapper_fd->get() < 0) {
1458 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1459 return false;
1460 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001461 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001462 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001463 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001464 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1465 return false;
1466 }
1467
1468 // If we got here we successfully opened the vdex files.
1469 return true;
1470}
1471
1472// Opens the output oat file for the given apk.
1473// If successful it stores the output path into out_oat_path and returns true.
1474Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001475 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1476 char* out_oat_path) {
1477 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001478 return Dex2oatFileWrapper();
1479 }
1480 const std::string out_oat_path_str(out_oat_path);
1481 Dex2oatFileWrapper wrapper_fd(
1482 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1483 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1484 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001485 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001486 } else if (!set_permissions_and_ownership(
1487 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001488 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1489 wrapper_fd.reset(-1);
1490 }
1491 return wrapper_fd;
1492}
1493
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001494// Creates RDONLY fds for oat and vdex files, if exist.
1495// Returns false if it fails to create oat out path for the given apk path.
1496// Note that the method returns true even if the files could not be opened.
1497bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1498 const std::string& oat_dir,
1499 const std::string& instruction_set,
1500 bool is_secondary_dex,
1501 unique_fd* oat_file_fd,
1502 unique_fd* vdex_file_fd) {
1503 char oat_path[PKG_PATH_MAX];
1504 if (!create_oat_out_path(apk_path.c_str(),
1505 instruction_set.c_str(),
1506 oat_dir.c_str(),
1507 is_secondary_dex,
1508 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001509 LOG(ERROR) << "Could not create oat out path for "
1510 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001511 return false;
1512 }
1513 oat_file_fd->reset(open(oat_path, O_RDONLY));
1514 if (oat_file_fd->get() < 0) {
1515 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1516 }
1517
1518 std::string vdex_filename = create_vdex_filename(oat_path);
1519 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1520 if (vdex_file_fd->get() < 0) {
1521 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1522 }
1523
1524 return true;
1525}
1526
Calin Juravle7a570e82017-01-14 16:23:30 -08001527// Updates the access times of out_oat_path based on those from apk_path.
1528void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1529 struct stat input_stat;
1530 memset(&input_stat, 0, sizeof(input_stat));
1531 if (stat(apk_path, &input_stat) != 0) {
1532 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1533 return;
1534 }
1535
1536 struct utimbuf ut;
1537 ut.actime = input_stat.st_atime;
1538 ut.modtime = input_stat.st_mtime;
1539 if (utime(out_oat_path, &ut) != 0) {
1540 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1541 }
1542}
1543
Calin Juravle80a21252017-01-17 14:43:25 -08001544// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001545// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1546// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1547// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001548class RunDexoptAnalyzer : public ExecVHelper {
1549 public:
1550 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001551 int vdex_fd,
1552 int oat_fd,
1553 int zip_fd,
1554 const std::string& instruction_set,
1555 const std::string& compiler_filter,
1556 bool profile_was_updated,
1557 bool downgrade,
1558 const char* class_loader_context,
1559 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001560 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001561
1562 // We always run the analyzer in the background job.
1563 const char* dexoptanalyzer_bin = select_execution_binary(
1564 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001565
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001566 std::string dex_file_arg = "--dex-file=" + dex_file;
1567 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1568 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1569 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1570 std::string isa_arg = "--isa=" + instruction_set;
1571 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1572 const char* assume_profile_changed = "--assume-profile-changed";
1573 const char* downgrade_flag = "--downgrade";
1574 std::string class_loader_context_arg = "--class-loader-context=";
1575 if (class_loader_context != nullptr) {
1576 class_loader_context_arg += class_loader_context;
1577 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001578 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1579 if (!class_loader_context_fds.empty()) {
1580 class_loader_context_fds_arg += class_loader_context_fds;
1581 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001582
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001583 // program name, dex file, isa, filter
1584 AddArg(dex_file_arg);
1585 AddArg(isa_arg);
1586 AddArg(compiler_filter_arg);
1587 if (oat_fd >= 0) {
1588 AddArg(oat_fd_arg);
1589 }
1590 if (vdex_fd >= 0) {
1591 AddArg(vdex_fd_arg);
1592 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001593 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001594 if (profile_was_updated) {
1595 AddArg(assume_profile_changed);
1596 }
1597 if (downgrade) {
1598 AddArg(downgrade_flag);
1599 }
1600 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001601 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001602 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001603 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001604 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001605 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001606
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001607 PrepareArgs(dexoptanalyzer_bin);
1608 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001609
1610 // Dexoptanalyzer mode which flattens the given class loader context and
1611 // prints a list of its dex files in that flattened order.
1612 RunDexoptAnalyzer(const char* class_loader_context) {
1613 CHECK(class_loader_context != nullptr);
1614
1615 // We always run the analyzer in the background job.
1616 const char* dexoptanalyzer_bin = select_execution_binary(
1617 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1618
1619 AddArg("--flatten-class-loader-context");
1620 AddArg(std::string("--class-loader-context=") + class_loader_context);
1621 PrepareArgs(dexoptanalyzer_bin);
1622 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001623};
Calin Juravle80a21252017-01-17 14:43:25 -08001624
1625// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001626static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001627 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001628 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001629 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001630 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001631 return false;
1632 }
Calin Juravle114f0812017-03-08 19:05:07 -08001633 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001634
Calin Juravle80a21252017-01-17 14:43:25 -08001635 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001636 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1637 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001638 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001639 return false;
1640 }
1641
1642 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001643 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001644
Calin Juravle7d765462017-09-04 15:57:10 -07001645 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001646 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001647 return false;
1648 }
1649
1650 return true;
1651}
1652
Calin Juravle7d765462017-09-04 15:57:10 -07001653// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1654// secondary dex files. This return codes are returned by the child process created for
1655// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001656
Andreas Gampe194fe422018-02-28 20:16:19 -08001657enum DexoptAnalyzerSkipCodes {
1658 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001659 // Specific errors are encoded in the name.
1660 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1661 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1662 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1663 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1664 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001665 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001666 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001667};
Calin Juravle7d765462017-09-04 15:57:10 -07001668
1669// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001670// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1671// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001672// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1673// of dexoptanalyzer.
1674static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001675 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001676 // The result values are defined in dexoptanalyzer.
1677 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001678 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001679 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001680 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001681 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001682 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001683 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001684 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001685 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001686 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1687 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001688 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1689 " Expected odex file status for secondary dex %s"
1690 " : dexoptanalyzer result=%d",
1691 dex_path.c_str(),
1692 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001693 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001694 }
1695
1696 // Use a second switch for enum switch-case analysis.
1697 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001698 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001699 // If the file does not exist there's no need for dexopt.
1700 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1701 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001702
1703 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1704 *error_msg = "Dexoptanalyzer path validation failed";
1705 return false;
1706 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1707 *error_msg = "Dexoptanalyzer open zip failed";
1708 return false;
1709 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1710 *error_msg = "Dexoptanalyzer dir preparation failed";
1711 return false;
1712 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1713 *error_msg = "Dexoptanalyzer open output failed";
1714 return false;
1715 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1716 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001717 return false;
1718 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001719
1720 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1721 dex_path.c_str(),
1722 result);
1723 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001724}
1725
Calin Juravle7d765462017-09-04 15:57:10 -07001726enum SecondaryDexAccess {
1727 kSecondaryDexAccessReadOk = 0,
1728 kSecondaryDexAccessDoesNotExist = 1,
1729 kSecondaryDexAccessPermissionError = 2,
1730 kSecondaryDexAccessIOError = 3
1731};
1732
1733static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1734 // Check if the path exists and can be read. If not, there's nothing to do.
1735 if (access(dex_path.c_str(), R_OK) == 0) {
1736 return kSecondaryDexAccessReadOk;
1737 } else {
1738 if (errno == ENOENT) {
1739 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1740 return kSecondaryDexAccessDoesNotExist;
1741 } else {
1742 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1743 return errno == EACCES
1744 ? kSecondaryDexAccessPermissionError
1745 : kSecondaryDexAccessIOError;
1746 }
1747 }
1748}
1749
1750static bool is_file_public(const std::string& filename) {
1751 struct stat file_stat;
1752 if (stat(filename.c_str(), &file_stat) == 0) {
1753 return (file_stat.st_mode & S_IROTH) != 0;
1754 }
1755 return false;
1756}
1757
1758// Create the oat file structure for the secondary dex 'dex_path' and assign
1759// the individual path component to the 'out_' parameters.
1760static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001761 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001762 size_t dirIndex = dex_path.rfind('/');
1763 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001764 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001765 return false;
1766 }
1767 // TODO(calin): we have similar computations in at lest 3 other places
1768 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1769 // using string append.
1770 std::string apk_dir = dex_path.substr(0, dirIndex);
1771 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1772 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1773
1774 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1775 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001776 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001777 return false;
1778 }
1779 return true;
1780}
1781
1782// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1783// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001784static bool validate_dexopt_storage_flags(int dexopt_flags,
1785 int* out_storage_flag,
1786 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001787 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1788 *out_storage_flag = FLAG_STORAGE_CE;
1789 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001790 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001791 return false;
1792 }
1793 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1794 *out_storage_flag = FLAG_STORAGE_DE;
1795 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001796 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001797 return false;
1798 }
1799 return true;
1800}
1801
David Brazdil4f6027a2019-03-19 11:44:21 +00001802static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1803 /* out */ std::vector<std::string>* context_dex_paths) {
1804 if (class_loader_context == nullptr) {
1805 return true;
1806 }
1807
1808 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1809
1810 // Pipe to get the hash result back from our child process.
1811 unique_fd pipe_read, pipe_write;
1812 if (!Pipe(&pipe_read, &pipe_write)) {
1813 PLOG(ERROR) << "Failed to create pipe";
1814 return false;
1815 }
1816
1817 pid_t pid = fork();
1818 if (pid == 0) {
1819 // child -- drop privileges before continuing.
1820 drop_capabilities(uid);
1821
1822 // Route stdout to `pipe_write`
1823 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1824 pipe_write.reset();
1825 pipe_read.reset();
1826
1827 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1828 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1829 }
1830
1831 /* parent */
1832 pipe_write.reset();
1833
1834 std::string str_dex_paths;
1835 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1836 PLOG(ERROR) << "Failed to read from pipe";
1837 return false;
1838 }
1839 pipe_read.reset();
1840
1841 int return_code = wait_child(pid);
1842 if (!WIFEXITED(return_code)) {
1843 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1844 return false;
1845 }
1846
1847 constexpr int kFlattenClassLoaderContextSuccess = 50;
1848 return_code = WEXITSTATUS(return_code);
1849 if (return_code != kFlattenClassLoaderContextSuccess) {
1850 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1851 return false;
1852 }
1853
1854 if (!str_dex_paths.empty()) {
1855 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1856 }
1857 return true;
1858}
1859
1860static int open_dex_paths(const std::vector<std::string>& dex_paths,
1861 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1862 for (const std::string& dex_path : dex_paths) {
1863 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1864 if (zip_fds->back().get() < 0) {
1865 *error_msg = StringPrintf(
1866 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1867 if (errno == ENOENT) {
1868 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1869 } else {
1870 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1871 }
1872 }
1873 }
1874 return 0;
1875}
1876
1877static std::string join_fds(const std::vector<unique_fd>& fds) {
1878 std::stringstream ss;
1879 bool is_first = true;
1880 for (const unique_fd& fd : fds) {
1881 if (is_first) {
1882 is_first = false;
1883 } else {
1884 ss << ":";
1885 }
1886 ss << fd.get();
1887 }
1888 return ss.str();
1889}
1890
Calin Juravlec9eab382017-01-25 01:17:17 -08001891// 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 -08001892// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1893// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001894// When returning true, the output parameters will be:
1895// - is_public_out: whether or not the oat file should not be made public
1896// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1897// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001898static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001899 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001900 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001901 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001902 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001903 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001904 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001905 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1906 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001907 return false;
1908 }
Calin Juravle7d765462017-09-04 15:57:10 -07001909 // Compute the oat dir as it's not easy to extract it from the child computation.
1910 char oat_path[PKG_PATH_MAX];
1911 char oat_dir[PKG_PATH_MAX];
1912 char oat_isa_dir[PKG_PATH_MAX];
1913 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001914 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1915 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001916 return false;
1917 }
Calin Juravle7d765462017-09-04 15:57:10 -07001918 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001919
Calin Juravle80a21252017-01-17 14:43:25 -08001920 pid_t pid = fork();
1921 if (pid == 0) {
1922 // child -- drop privileges before continuing.
1923 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001924
1925 // Validate the path structure.
1926 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1927 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001928 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001929 }
1930
1931 // Open the dex file.
1932 unique_fd zip_fd;
1933 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1934 if (zip_fd.get() < 0) {
1935 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001936 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001937 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001938 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001939 }
1940 }
1941
David Brazdil4f6027a2019-03-19 11:44:21 +00001942 // Open class loader context dex files.
1943 std::vector<unique_fd> context_zip_fds;
1944 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1945 if (open_dex_paths_rc != 0) {
1946 _exit(open_dex_paths_rc);
1947 }
1948
Calin Juravle7d765462017-09-04 15:57:10 -07001949 // Prepare the oat directories.
1950 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001951 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001952 }
1953
1954 // Open the vdex/oat files if any.
1955 unique_fd oat_file_fd;
1956 unique_fd vdex_file_fd;
1957 if (!maybe_open_oat_and_vdex_file(dex_path,
1958 *oat_dir_out,
1959 instruction_set,
1960 true /* is_secondary_dex */,
1961 &oat_file_fd,
1962 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001963 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001964 }
1965
1966 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001967 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1968 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001969
1970 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001971 // Note that we do not do it before the fork since opening the files is required to happen
1972 // after forking.
1973 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1974 vdex_file_fd.get(),
1975 oat_file_fd.get(),
1976 zip_fd.get(),
1977 instruction_set,
1978 compiler_filter, profile_was_updated,
1979 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001980 class_loader_context,
1981 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001982 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001983 }
1984
1985 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001986 int result = wait_child(pid);
1987 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001988 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1989 dex_path.c_str(),
1990 result);
1991 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001992 return false;
1993 }
1994 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001995 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001996 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1997 result,
1998 dexopt_needed_out,
1999 error_msg);
2000 if (!success) {
2001 LOG(ERROR) << *error_msg;
2002 }
Calin Juravle7d765462017-09-04 15:57:10 -07002003
2004 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2005
Calin Juravle80a21252017-01-17 14:43:25 -08002006 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002007 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2008 // makes the code simpler; force compilation is only needed during tests).
2009 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002010 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002011 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002012 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2013 }
2014
Calin Juravle7d765462017-09-04 15:57:10 -07002015 // Check if we should make the oat file public.
2016 // Note that if the dex file is not public the compiled code cannot be made public.
2017 // It is ok to check this flag outside in the parent process.
2018 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2019
Calin Juravle80a21252017-01-17 14:43:25 -08002020 return success;
2021}
2022
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002023static std::string format_dexopt_error(int status, const char* dex_path) {
2024 if (WIFEXITED(status)) {
2025 int int_code = WEXITSTATUS(status);
2026 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2027 if (code_name != nullptr) {
2028 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2029 }
2030 }
2031 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002032}
2033
Calin Juravlec9eab382017-01-25 01:17:17 -08002034int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002035 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002036 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002037 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002038 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002039 CHECK(pkgname != nullptr);
2040 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002041 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002042 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2043 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002044
Calin Juravled23dee72017-07-06 16:29:11 -07002045 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002046 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002047 return -1;
2048 }
2049
2050 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002051 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2052 class_loader_context);
2053 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002054 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002055 }
2056
Calin Juravleebc8a792017-04-04 20:21:05 -07002057 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002058 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2059 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2060 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002061 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002062 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002063 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002064 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002065 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002066
2067 // Check if we're dealing with a secondary dex file and if we need to compile it.
2068 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002069 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002070 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002071 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2072 *error_msg = "Failed acquiring context dex paths";
2073 return -1; // We had an error, logged in the process method.
2074 }
2075
Calin Juravlec9eab382017-01-25 01:17:17 -08002076 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002077 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002078 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002079 oat_dir = oat_dir_str.c_str();
2080 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2081 return 0; // Nothing to do, report success.
2082 }
2083 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002084 if (error_msg->empty()) { // TODO: Make this a CHECK.
2085 *error_msg = "Failed processing secondary.";
2086 }
Calin Juravle80a21252017-01-17 14:43:25 -08002087 return -1; // We had an error, logged in the process method.
2088 }
2089 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002090 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002091 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002092 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2093 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2094 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002095
2096 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002097 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002098 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002099 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2100 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002101 return -1;
2102 }
2103
David Brazdil4f6027a2019-03-19 11:44:21 +00002104 // Open class loader context dex files.
2105 std::vector<unique_fd> context_input_fds;
2106 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2107 LOG(ERROR) << *error_msg;
2108 return -1;
2109 }
2110
Calin Juravle7a570e82017-01-14 16:23:30 -08002111 // Create the output OAT file.
2112 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002113 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002114 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002115 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002116 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002117 return -1;
2118 }
2119
2120 // Open vdex files.
2121 Dex2oatFileWrapper in_vdex_fd;
2122 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002123 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2124 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002125 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002126 return -1;
2127 }
2128
Calin Juravlecb556e32017-04-04 20:22:50 -07002129 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2130 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2131 // fully inherit their parent context).
2132 // Note that for primary apk the oat files are created before, in a separate installd
2133 // call which also does the restorecon. TODO(calin): unify the paths.
2134 if (is_secondary_dex) {
2135 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2136 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002137 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2138 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002139 return -1;
2140 }
2141 }
2142
Jeff Sharkey90aff262016-12-12 14:28:24 -07002143 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002144 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002145
Calin Juravle7a570e82017-01-14 16:23:30 -08002146 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002147 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002148 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002149
liulvping61907742018-08-21 09:36:52 +08002150 if (reference_profile_fd.get() == -1) {
2151 // We don't create an app image without reference profile since there is no speedup from
2152 // loading it in that case and instead will be a small overhead.
2153 generate_app_image = false;
2154 }
2155
2156 // Create the app image file if needed.
2157 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2158 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2159
Calin Juravle62c5a372018-02-01 17:03:23 +00002160 unique_fd dex_metadata_fd;
2161 if (dex_metadata_path != nullptr) {
2162 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2163 if (dex_metadata_fd.get() < 0) {
2164 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2165 }
2166 }
2167
Andreas Gampe023b2242018-02-28 16:03:25 -08002168 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002169
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002170 RunDex2Oat runner(input_fd.get(),
2171 out_oat_fd.get(),
2172 in_vdex_fd.get(),
2173 out_vdex_fd.get(),
2174 image_fd.get(),
2175 dex_path,
2176 out_oat_path,
2177 swap_fd.get(),
2178 instruction_set,
2179 compiler_filter,
2180 debuggable,
2181 boot_complete,
2182 background_job_compile,
2183 reference_profile_fd.get(),
2184 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002185 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002186 target_sdk_version,
2187 enable_hidden_api_checks,
2188 generate_compact_dex,
2189 dex_metadata_fd.get(),
2190 compilation_reason);
2191
Jeff Sharkey90aff262016-12-12 14:28:24 -07002192 pid_t pid = fork();
2193 if (pid == 0) {
2194 /* child -- drop privileges before continuing */
2195 drop_capabilities(uid);
2196
Richard Uhler76cc0272016-12-08 10:46:35 +00002197 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002198 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002199 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002200 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002201 }
2202
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002203 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002204 } else {
2205 int res = wait_child(pid);
2206 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002207 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002208 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002209 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2210 << std::hex << std::setw(4) << res << ", process failed";
2211 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002212 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002213 }
2214 }
2215
Calin Juravlec9eab382017-01-25 01:17:17 -08002216 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002217
2218 // We've been successful, don't delete output.
2219 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002220 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002221 image_fd.SetCleanup(false);
2222 reference_profile_fd.SetCleanup(false);
2223
2224 return 0;
2225}
2226
Calin Juravlec9eab382017-01-25 01:17:17 -08002227// Try to remove the given directory. Log an error if the directory exists
2228// and is empty but could not be removed.
2229static bool rmdir_if_empty(const char* dir) {
2230 if (rmdir(dir) == 0) {
2231 return true;
2232 }
2233 if (errno == ENOENT || errno == ENOTEMPTY) {
2234 return true;
2235 }
2236 PLOG(ERROR) << "Failed to remove dir: " << dir;
2237 return false;
2238}
2239
2240// Try to unlink the given file. Log an error if the file exists and could not
2241// be unlinked.
2242static bool unlink_if_exists(const std::string& file) {
2243 if (unlink(file.c_str()) == 0) {
2244 return true;
2245 }
2246 if (errno == ENOENT) {
2247 return true;
2248
2249 }
2250 PLOG(ERROR) << "Could not unlink: " << file;
2251 return false;
2252}
2253
Calin Juravle7d765462017-09-04 15:57:10 -07002254enum ReconcileSecondaryDexResult {
2255 kReconcileSecondaryDexExists = 0,
2256 kReconcileSecondaryDexCleanedUp = 1,
2257 kReconcileSecondaryDexValidationError = 2,
2258 kReconcileSecondaryDexCleanUpError = 3,
2259 kReconcileSecondaryDexAccessIOError = 4,
2260};
Calin Juravlec9eab382017-01-25 01:17:17 -08002261
2262// Reconcile the secondary dex 'dex_path' and its generated oat files.
2263// Return true if all the parameters are valid and the secondary dex file was
2264// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2265// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2266// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2267// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2268// Return false if there were errors during processing. In this case
2269// out_secondary_dex_exists will be set to false.
2270bool reconcile_secondary_dex_file(const std::string& dex_path,
2271 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2272 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2273 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002274 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002275 if (isas.size() == 0) {
2276 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2277 return false;
2278 }
2279
Calin Juravle7d765462017-09-04 15:57:10 -07002280 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2281 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2282 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002283 return false;
2284 }
2285
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002286 // As a security measure we want to unlink art artifacts with the reduced capabilities
2287 // of the package user id. So we fork and drop capabilities in the child.
2288 pid_t pid = fork();
2289 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002290 /* child -- drop privileges before continuing */
2291 drop_capabilities(uid);
2292
2293 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Greg Kaiser8042c372019-03-26 06:23:19 -07002294 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002295 uid, storage_flag)) {
2296 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2297 _exit(kReconcileSecondaryDexValidationError);
2298 }
2299
2300 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2301 switch (access_check) {
2302 case kSecondaryDexAccessDoesNotExist:
2303 // File does not exist. Proceed with cleaning.
2304 break;
2305 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2306 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2307 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2308 default:
2309 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2310 _exit(kReconcileSecondaryDexValidationError);
2311 }
2312
2313 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002314 char oat_path[PKG_PATH_MAX];
2315 char oat_dir[PKG_PATH_MAX];
2316 char oat_isa_dir[PKG_PATH_MAX];
2317 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002318 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002319 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002320 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002321 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2322 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002323 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002324 }
Calin Juravle51314092017-05-18 15:33:05 -07002325
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002326 // Delete oat/vdex/art files.
2327 result = unlink_if_exists(oat_path) && result;
2328 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2329 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002330
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002331 // Delete profiles.
2332 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002333 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002334 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002335 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002336 result = unlink_if_exists(current_profile) && result;
2337 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002338
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002339 // We upgraded once the location of current profile for secondary dex files.
2340 // Check for any previous left-overs and remove them as well.
2341 std::string old_current_profile = dex_path + ".prof";
2342 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002343
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002344 // Try removing the directories as well, they might be empty.
2345 result = rmdir_if_empty(oat_isa_dir) && result;
2346 result = rmdir_if_empty(oat_dir) && result;
2347 }
Calin Juravle7d765462017-09-04 15:57:10 -07002348 if (!result) {
2349 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2350 }
2351 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002352 }
2353
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002354 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002355 if (!WIFEXITED(return_code)) {
2356 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2357 } else {
2358 return_code = WEXITSTATUS(return_code);
2359 }
2360
2361 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2362
2363 switch (return_code) {
2364 case kReconcileSecondaryDexCleanedUp:
2365 case kReconcileSecondaryDexValidationError:
2366 // If we couldn't validate assume the dex file does not exist.
2367 // This will purge the entry from the PM records.
2368 *out_secondary_dex_exists = false;
2369 return true;
2370 case kReconcileSecondaryDexExists:
2371 *out_secondary_dex_exists = true;
2372 return true;
2373 case kReconcileSecondaryDexAccessIOError:
2374 // We had an access IO error.
2375 // Return false so that we can try again.
2376 // The value of out_secondary_dex_exists does not matter in this case and by convention
2377 // is set to false.
2378 *out_secondary_dex_exists = false;
2379 return false;
2380 default:
2381 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2382 *out_secondary_dex_exists = false;
2383 return false;
2384 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002385}
2386
Alan Stokesa25d90c2017-10-16 10:56:00 +01002387// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2388// Returns true if all parameters are valid and the hash successfully computed and stored in
2389// out_secondary_dex_hash.
2390// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2391// the app.
2392// For any other errors (e.g. if any of the parameters are invalid) returns false.
2393bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2394 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2395 std::vector<uint8_t>* out_secondary_dex_hash) {
2396 out_secondary_dex_hash->clear();
2397
2398 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2399
2400 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2401 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2402 << storage_flag;
2403 return false;
2404 }
2405
2406 // Pipe to get the hash result back from our child process.
2407 unique_fd pipe_read, pipe_write;
2408 if (!Pipe(&pipe_read, &pipe_write)) {
2409 PLOG(ERROR) << "Failed to create pipe";
2410 return false;
2411 }
2412
2413 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2414 // access data the app itself can access.
2415 pid_t pid = fork();
2416 if (pid == 0) {
2417 // child -- drop privileges before continuing
2418 drop_capabilities(uid);
2419 pipe_read.reset();
2420
2421 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2422 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002423 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002424 }
2425
2426 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2427 if (fd == -1) {
2428 if (errno == EACCES || errno == ENOENT) {
2429 // Not treated as an error.
2430 _exit(0);
2431 }
2432 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002433 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002434 }
2435
2436 SHA256_CTX ctx;
2437 SHA256_Init(&ctx);
2438
2439 std::vector<uint8_t> buffer(65536);
2440 while (true) {
2441 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2442 if (bytes_read == 0) {
2443 break;
2444 } else if (bytes_read == -1) {
2445 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002446 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002447 }
2448
2449 SHA256_Update(&ctx, buffer.data(), bytes_read);
2450 }
2451
2452 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2453 SHA256_Final(hash.data(), &ctx);
2454 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002455 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002456 }
2457
2458 _exit(0);
2459 }
2460
2461 // parent
2462 pipe_write.reset();
2463
2464 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2465 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2466 out_secondary_dex_hash->clear();
2467 }
2468 return wait_child(pid) == 0;
2469}
2470
Jeff Sharkey90aff262016-12-12 14:28:24 -07002471// Helper for move_ab, so that we can have common failure-case cleanup.
2472static bool unlink_and_rename(const char* from, const char* to) {
2473 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2474 // return a failure.
2475 struct stat s;
2476 if (stat(to, &s) == 0) {
2477 if (!S_ISREG(s.st_mode)) {
2478 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2479 return false;
2480 }
2481 if (unlink(to) != 0) {
2482 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2483 return false;
2484 }
2485 } else {
2486 // This may be a permission problem. We could investigate the error code, but we'll just
2487 // let the rename failure do the work for us.
2488 }
2489
2490 // Try to rename "to" to "from."
2491 if (rename(from, to) != 0) {
2492 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2493 return false;
2494 }
2495 return true;
2496}
2497
2498// Move/rename a B artifact (from) to an A artifact (to).
2499static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2500 // Check whether B exists.
2501 {
2502 struct stat s;
2503 if (stat(b_path.c_str(), &s) != 0) {
2504 // Silently ignore for now. The service calling this isn't smart enough to understand
2505 // lack of artifacts at the moment.
2506 return false;
2507 }
2508 if (!S_ISREG(s.st_mode)) {
2509 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2510 // Try to unlink, but swallow errors.
2511 unlink(b_path.c_str());
2512 return false;
2513 }
2514 }
2515
2516 // Rename B to A.
2517 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2518 // Delete the b_path so we don't try again (or fail earlier).
2519 if (unlink(b_path.c_str()) != 0) {
2520 PLOG(ERROR) << "Could not unlink " << b_path;
2521 }
2522
2523 return false;
2524 }
2525
2526 return true;
2527}
2528
2529bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2530 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002531 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2532 if (slot_suffix.empty()) {
2533 return false;
2534 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002535
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002536 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2537 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2538 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002539 }
2540
2541 // Validate other inputs.
2542 if (validate_apk_path(apk_path) != 0) {
2543 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2544 return false;
2545 }
2546 if (validate_apk_path(oat_dir) != 0) {
2547 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2548 return false;
2549 }
2550
2551 char a_path[PKG_PATH_MAX];
2552 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2553 return false;
2554 }
2555 const std::string a_vdex_path = create_vdex_filename(a_path);
2556 const std::string a_image_path = create_image_filename(a_path);
2557
2558 // B path = A path + slot suffix.
2559 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2560 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2561 const std::string b_image_path = StringPrintf("%s.%s",
2562 a_image_path.c_str(),
2563 slot_suffix.c_str());
2564
2565 bool success = true;
2566 if (move_ab_path(b_path, a_path)) {
2567 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2568 // Note: we can live without an app image. As such, ignore failure to move the image file.
2569 // If we decide to require the app image, or the app image being moved correctly,
2570 // then change accordingly.
2571 constexpr bool kIgnoreAppImageFailure = true;
2572
2573 if (!a_image_path.empty()) {
2574 if (!move_ab_path(b_image_path, a_image_path)) {
2575 unlink(a_image_path.c_str());
2576 if (!kIgnoreAppImageFailure) {
2577 success = false;
2578 }
2579 }
2580 }
2581 } else {
2582 // Cleanup: delete B image, ignore errors.
2583 unlink(b_image_path.c_str());
2584 success = false;
2585 }
2586 } else {
2587 // Cleanup: delete B image, ignore errors.
2588 unlink(b_vdex_path.c_str());
2589 unlink(b_image_path.c_str());
2590 success = false;
2591 }
2592 return success;
2593}
2594
2595bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2596 // Delete the oat/odex file.
2597 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002598 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002599 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002600 return false;
2601 }
2602
2603 // In case of a permission failure report the issue. Otherwise just print a warning.
2604 auto unlink_and_check = [](const char* path) -> bool {
2605 int result = unlink(path);
2606 if (result != 0) {
2607 if (errno == EACCES || errno == EPERM) {
2608 PLOG(ERROR) << "Could not unlink " << path;
2609 return false;
2610 }
2611 PLOG(WARNING) << "Could not unlink " << path;
2612 }
2613 return true;
2614 };
2615
2616 // Delete the oat/odex file.
2617 bool return_value_oat = unlink_and_check(out_path);
2618
2619 // Derive and delete the app image.
2620 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2621
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002622 // Derive and delete the vdex file.
2623 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2624
Jeff Sharkey90aff262016-12-12 14:28:24 -07002625 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002626 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002627}
2628
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002629static bool is_absolute_path(const std::string& path) {
2630 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2631 LOG(ERROR) << "Invalid absolute path " << path;
2632 return false;
2633 } else {
2634 return true;
2635 }
2636}
2637
2638static bool is_valid_instruction_set(const std::string& instruction_set) {
2639 // TODO: add explicit whitelisting of instruction sets
2640 if (instruction_set.find('/') != std::string::npos) {
2641 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2642 return false;
2643 } else {
2644 return true;
2645 }
2646}
2647
2648bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2649 const char *apk_path, const char *instruction_set) {
2650 std::string oat_dir_ = oat_dir;
2651 std::string apk_path_ = apk_path;
2652 std::string instruction_set_ = instruction_set;
2653
2654 if (!is_absolute_path(oat_dir_)) return false;
2655 if (!is_absolute_path(apk_path_)) return false;
2656 if (!is_valid_instruction_set(instruction_set_)) return false;
2657
2658 std::string::size_type end = apk_path_.rfind('.');
2659 std::string::size_type start = apk_path_.rfind('/', end);
2660 if (end == std::string::npos || start == std::string::npos) {
2661 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2662 return false;
2663 }
2664
2665 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2666 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2667 const char* res = res_.c_str();
2668 if (strlen(res) >= PKG_PATH_MAX) {
2669 LOG(ERROR) << "Result too large";
2670 return false;
2671 } else {
2672 strlcpy(path, res, PKG_PATH_MAX);
2673 return true;
2674 }
2675}
2676
2677bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2678 const char *instruction_set) {
2679 std::string apk_path_ = apk_path;
2680 std::string instruction_set_ = instruction_set;
2681
2682 if (!is_absolute_path(apk_path_)) return false;
2683 if (!is_valid_instruction_set(instruction_set_)) return false;
2684
2685 std::string::size_type end = apk_path_.rfind('.');
2686 std::string::size_type start = apk_path_.rfind('/', end);
2687 if (end == std::string::npos || start == std::string::npos) {
2688 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2689 return false;
2690 }
2691
2692 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2693 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2694}
2695
2696bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2697 const char *instruction_set) {
2698 std::string src_ = src;
2699 std::string instruction_set_ = instruction_set;
2700
2701 if (!is_absolute_path(src_)) return false;
2702 if (!is_valid_instruction_set(instruction_set_)) return false;
2703
2704 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2705 if (*it == '/') {
2706 *it = '@';
2707 }
2708 }
2709
2710 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2711 + DALVIK_CACHE_POSTFIX;
2712 const char* res = res_.c_str();
2713 if (strlen(res) >= PKG_PATH_MAX) {
2714 LOG(ERROR) << "Result too large";
2715 return false;
2716 } else {
2717 strlcpy(path, res, PKG_PATH_MAX);
2718 return true;
2719 }
2720}
2721
Calin Juravle59f7ab82018-04-27 17:50:23 -07002722bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2723 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002724 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2725 for (const std::string& elem : classpaths_elems) {
2726 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2727 if (fd < 0) {
2728 PLOG(ERROR) << "Could not open classpath elem " << elem;
2729 return false;
2730 } else {
2731 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002732 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002733 }
2734 }
2735 return true;
2736}
2737
2738static bool create_app_profile_snapshot(int32_t app_id,
2739 const std::string& package_name,
2740 const std::string& profile_name,
2741 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002742 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2743
Calin Juravle824a64d2018-01-18 20:23:17 -08002744 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002745 if (snapshot_fd < 0) {
2746 return false;
2747 }
2748
2749 std::vector<unique_fd> profiles_fd;
2750 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002751 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2752 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002753 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2754 return false;
2755 }
2756
2757 profiles_fd.push_back(std::move(reference_profile_fd));
2758
Calin Juravle0d0a4922018-01-23 19:54:11 -08002759 // Open the class paths elements. These will be used to filter out profile data that does
2760 // not belong to the classpath during merge.
2761 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002762 std::vector<std::string> dex_locations;
2763 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002764 return false;
2765 }
2766
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002767 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002768 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002769 pid_t pid = fork();
2770 if (pid == 0) {
2771 /* child -- drop privileges before continuing */
2772 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002773 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002774 }
2775
2776 /* parent */
2777 int return_code = wait_child(pid);
2778 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002779 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002780 return false;
2781 }
2782
Calin Juravle78728f32019-11-08 17:55:46 -08002783 // Verify that profman finished successfully.
2784 int profman_code = WEXITSTATUS(return_code);
2785 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2786 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2787 << ":" << profman_code;
2788 return false;
2789 }
Calin Juravle29591732017-11-20 17:46:19 -08002790 return true;
2791}
2792
Calin Juravle0d0a4922018-01-23 19:54:11 -08002793static bool create_boot_image_profile_snapshot(const std::string& package_name,
2794 const std::string& profile_name,
2795 const std::string& classpath) {
2796 // The reference profile directory for the android package might not be prepared. Do it now.
2797 const std::string ref_profile_dir =
2798 create_primary_reference_profile_package_dir_path(package_name);
2799 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2800 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2801 return false;
2802 }
2803
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002804 // Return false for empty class path since it may otherwise return true below if profiles is
2805 // empty.
2806 if (classpath.empty()) {
2807 PLOG(ERROR) << "Class path is empty";
2808 return false;
2809 }
2810
Calin Juravle0d0a4922018-01-23 19:54:11 -08002811 // Open and create the snapshot profile.
2812 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2813
2814 // Collect all non empty profiles.
2815 // The collection will traverse all applications profiles and find the non empty files.
2816 // This has the potential of inspecting a large number of files and directories (depending
2817 // on the number of applications and users). So there is a slight increase in the chance
2818 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2819 // fail the snapshot and aggregate whatever profile we could open.
2820 //
2821 // The profile snapshot is a best effort based on available data it's ok if some data
2822 // from some apps is missing. It will be counter productive for the snapshot to fail
2823 // because we could not open or read some of the files.
2824 std::vector<std::string> profiles;
2825 if (!collect_profiles(&profiles)) {
2826 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2827 }
2828
2829 // If we have no profiles return early.
2830 if (profiles.empty()) {
2831 return true;
2832 }
2833
2834 // Open the classpath elements. These will be used to filter out profile data that does
2835 // not belong to the classpath during merge.
2836 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002837 std::vector<std::string> dex_locations;
2838 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002839 return false;
2840 }
2841
2842 // If we could not open any files from the classpath return an error.
2843 if (apk_fds.empty()) {
2844 LOG(ERROR) << "Could not open any of the classpath elements.";
2845 return false;
2846 }
2847
2848 // Aggregate the profiles in batches of kAggregationBatchSize.
2849 // We do this to avoid opening a huge a amount of files.
2850 static constexpr size_t kAggregationBatchSize = 10;
2851
Calin Juravle0d0a4922018-01-23 19:54:11 -08002852 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002853 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002854 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2855 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2856 if (fd.get() >= 0) {
2857 profiles_fd.push_back(std::move(fd));
2858 }
2859 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002860
2861 // We aggregate (read & write) into the same fd multiple times in a row.
2862 // We need to reset the cursor every time to ensure we read the whole file every time.
2863 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2864 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2865 return false;
2866 }
2867
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002868 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002869 args.SetupMerge(profiles_fd,
2870 snapshot_fd,
2871 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002872 dex_locations,
2873 /*for_snapshot=*/true,
2874 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002875 pid_t pid = fork();
2876 if (pid == 0) {
2877 /* child -- drop privileges before continuing */
2878 drop_capabilities(AID_SYSTEM);
2879
Calin Juravle59f7ab82018-04-27 17:50:23 -07002880 // The introduction of new access flags into boot jars causes them to
2881 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002882 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002883 }
2884
2885 /* parent */
2886 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002887
Calin Juravle0d0a4922018-01-23 19:54:11 -08002888 if (!WIFEXITED(return_code)) {
2889 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2890 return false;
2891 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002892
2893 // Verify that profman finished successfully.
2894 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002895 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2896 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2897 << ":" << profman_code;
2898 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002899 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002900 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002901
Calin Juravle0d0a4922018-01-23 19:54:11 -08002902 return true;
2903}
2904
2905bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2906 const std::string& profile_name, const std::string& classpath) {
2907 if (app_id == -1) {
2908 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2909 } else {
2910 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2911 }
2912}
2913
Calin Juravlec3b049e2018-01-18 22:32:58 -08002914bool prepare_app_profile(const std::string& package_name,
2915 userid_t user_id,
2916 appid_t app_id,
2917 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002918 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002919 const std::unique_ptr<std::string>& dex_metadata) {
2920 // Prepare the current profile.
2921 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2922 /*is_secondary_dex*/ false);
2923 uid_t uid = multiuser_get_uid(user_id, app_id);
2924 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2925 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2926 return false;
2927 }
2928
2929 // Check if we need to install the profile from the dex metadata.
2930 if (dex_metadata == nullptr) {
2931 return true;
2932 }
2933
2934 // We have a dex metdata. Merge the profile into the reference profile.
2935 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2936 /*read_write*/ true, /*is_secondary_dex*/ false);
2937 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2938 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002939 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2940 if (apk_fd < 0) {
2941 PLOG(ERROR) << "Could not open code path " << code_path;
2942 return false;
2943 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002944
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002945 RunProfman args;
2946 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2947 std::move(ref_profile_fd),
2948 std::move(apk_fd),
2949 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002950 pid_t pid = fork();
2951 if (pid == 0) {
2952 /* child -- drop privileges before continuing */
2953 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2954 drop_capabilities(app_shared_gid);
2955
Calin Juravlef63d4792018-01-30 17:43:34 +00002956 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002957 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002958 }
2959
2960 /* parent */
2961 int return_code = wait_child(pid);
2962 if (!WIFEXITED(return_code)) {
2963 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2964 return false;
2965 }
2966 return true;
2967}
2968
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002969} // namespace installd
2970} // namespace android