blob: 768d9005917721f7cf2b3c77388e86f4d2a08bf3 [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");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000343 std::string bootclasspath;
344 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
345 if (dex2oat_bootclasspath != nullptr) {
346 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
347 }
348 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
349 // BOOTCLASSPATH.
350
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800351 const std::string dex2oat_isa_features_key =
352 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
353 std::string instruction_set_features_arg =
354 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700355
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800356 const std::string dex2oat_isa_variant_key =
357 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
358 std::string instruction_set_variant_arg =
359 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700360
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800361 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700362
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800363 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
364 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
365 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700366
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800367 // If we are booting without the real /data, don't spend time compiling.
368 std::string vold_decrypt = GetProperty("vold.decrypt", "");
369 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
370 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700371
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800372 std::string resolve_startup_string_arg =
373 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
374 "--resolve-startup-const-strings=%s");
375 if (resolve_startup_string_arg.empty()) {
376 // If empty, fall back to system property.
377 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800378 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
379 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800380 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800381
382 const std::string image_block_size_arg =
383 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
384 "--max-image-block-size=%s");
385
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800386 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388 std::string image_format_arg;
389 if (image_fd >= 0) {
390 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000391 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000392
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800393 std::string dex2oat_large_app_threshold_arg =
394 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000395
Calin Juravlef74a7372019-02-28 20:29:41 -0800396
397 const char* dex2oat_bin = select_execution_binary(
398 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000399
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800400 bool generate_minidebug_info = kEnableMinidebugInfo &&
401 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000402
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000403 std::string boot_image;
404 std::string use_apex_image =
405 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
406 ENABLE_APEX_IMAGE,
407 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700408
409 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
410 profile_boot_class_path =
411 server_configurable_flags::GetServerConfigurableFlag(
412 RUNTIME_NATIVE_BOOT_NAMESPACE,
413 PROFILE_BOOT_CLASS_PATH,
414 /*default_value=*/ profile_boot_class_path);
415
416 if (use_apex_image == "true" || profile_boot_class_path == "true") {
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000417 boot_image = StringPrintf("-Ximage:%s", kApexImage);
418 } else {
419 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
420 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000421
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800422 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
423 // use arraysize instead.
424 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
425 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
426 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
427 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
428 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
429 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
430 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
431 std::string dex2oat_compiler_filter_arg;
432 std::string dex2oat_swap_fd;
433 std::string dex2oat_image_fd;
434 std::string target_sdk_version_arg;
435 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000436 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800437 }
438 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000439 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800440 if (class_loader_context != nullptr) {
441 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
442 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000443 if (!class_loader_context_fds.empty()) {
444 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
445 class_loader_context_fds.c_str());
446 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800447 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000448
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800449 if (swap_fd >= 0) {
450 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
451 }
452 if (image_fd >= 0) {
453 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
454 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000455
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800456 // Compute compiler filter.
457 bool have_dex2oat_relocation_skip_flag = false;
458 if (skip_compilation) {
459 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
460 have_dex2oat_relocation_skip_flag = true;
461 } else if (compiler_filter != nullptr) {
462 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
463 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000464
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800465 if (dex2oat_compiler_filter_arg.empty()) {
466 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
467 "--compiler-filter=%s");
468 }
469
470 // Check whether all apps should be compiled debuggable.
471 if (!debuggable) {
472 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
473 }
474 std::string profile_arg;
475 if (profile_fd != -1) {
476 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
477 }
478
479 // Get the directory of the apk to pass as a base classpath directory.
480 std::string base_dir;
481 std::string apk_dir(input_file_name);
482 unsigned long dir_index = apk_dir.rfind('/');
483 bool has_base_dir = dir_index != std::string::npos;
484 if (has_base_dir) {
485 apk_dir = apk_dir.substr(0, dir_index);
486 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
487 }
488
489 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
490
491 std::string compilation_reason_arg = compilation_reason == nullptr
492 ? ""
493 : std::string("--compilation-reason=") + compilation_reason;
494
495 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
496
497 // Disable cdex if update input vdex is true since this combination of options is not
498 // supported.
499 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
500
501 AddArg(zip_fd_arg);
502 AddArg(zip_location_arg);
503 AddArg(input_vdex_fd_arg);
504 AddArg(output_vdex_fd_arg);
505 AddArg(oat_fd_arg);
506 AddArg(oat_location_arg);
507 AddArg(instruction_set_arg);
508
509 AddArg(instruction_set_variant_arg);
510 AddArg(instruction_set_features_arg);
511
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000512 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000513 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800514 AddRuntimeArg(dex2oat_Xms_arg);
515 AddRuntimeArg(dex2oat_Xmx_arg);
516
517 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800518 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800519 AddArg(dex2oat_compiler_filter_arg);
520 AddArg(dex2oat_threads_arg);
521 AddArg(dex2oat_swap_fd);
522 AddArg(dex2oat_image_fd);
523
524 if (generate_debug_info) {
525 AddArg("--generate-debug-info");
526 }
527 if (debuggable) {
528 AddArg("--debuggable");
529 }
530 AddArg(image_format_arg);
531 AddArg(dex2oat_large_app_threshold_arg);
532
533 if (have_dex2oat_relocation_skip_flag) {
534 AddRuntimeArg(dex2oat_norelocation);
535 }
536 AddArg(profile_arg);
537 AddArg(base_dir);
538 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000539 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800540 if (generate_minidebug_info) {
541 AddArg(kMinidebugDex2oatFlag);
542 }
543 if (disable_cdex) {
544 AddArg(kDisableCompactDexFlag);
545 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000546 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800547 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100548 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800549 }
550
551 if (dex_metadata_fd > -1) {
552 AddArg(dex_metadata_fd_arg);
553 }
554
555 AddArg(compilation_reason_arg);
556
557 // Do not add args after dex2oat_flags, they should override others for debugging.
558 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
559
560 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000561 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800562};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700563
564/*
565 * Whether dexopt should use a swap file when compiling an APK.
566 *
567 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
568 * itself, anyways).
569 *
570 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
571 *
572 * Otherwise, return true if this is a low-mem device.
573 *
574 * Otherwise, return default value.
575 */
576static bool kAlwaysProvideSwapFile = false;
577static bool kDefaultProvideSwapFile = true;
578
579static bool ShouldUseSwapFileForDexopt() {
580 if (kAlwaysProvideSwapFile) {
581 return true;
582 }
583
584 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700585 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
586 if (!dex2oat_prop_buf.empty()) {
587 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700588 }
589
590 // Shortcut for default value. This is an implementation optimization for the process sketched
591 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
592 // as low-mem is never returning false. The compiler will optimize this away if it can.
593 if (kDefaultProvideSwapFile) {
594 return true;
595 }
596
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700597 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598 return true;
599 }
600
601 // Default value must be false here.
602 return kDefaultProvideSwapFile;
603}
604
Richard Uhler76cc0272016-12-08 10:46:35 +0000605static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700606 if (set_to_bg) {
607 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800608 PLOG(ERROR) << "set_sched_policy failed";
609 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700610 }
611 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800612 PLOG(ERROR) << "setpriority failed";
613 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 }
615 }
616}
617
Calin Juravle29591732017-11-20 17:46:19 -0800618static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
619 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800620 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800621 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800622 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800623 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800624 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700625 }
Calin Juravle114f0812017-03-08 19:05:07 -0800626 // Profiles should belong to the app; make sure of that by giving ownership to
627 // the app uid. If we cannot do that, there's no point in returning the fd
628 // since dex2oat/profman will fail with SElinux denials.
629 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000630 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800631 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800632 }
Calin Juravle29591732017-11-20 17:46:19 -0800633 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800634}
635
Calin Juravle29591732017-11-20 17:46:19 -0800636static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800637 // Do not follow symlinks when opening a profile:
638 // - primary profiles should not contain symlinks in their paths
639 // - secondary dex paths should have been already resolved and validated
640 flags |= O_NOFOLLOW;
641
Calin Juravle29591732017-11-20 17:46:19 -0800642 // Check if we need to create the profile
643 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
644 unique_fd fd;
645 if ((flags & O_CREAT) != 0) {
646 fd = create_profile(uid, profile, flags);
647 } else {
648 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
649 }
650
Calin Juravle114f0812017-03-08 19:05:07 -0800651 if (fd.get() < 0) {
652 if (errno != ENOENT) {
653 // Profiles might be missing for various reasons. For example, in a
654 // multi-user environment, the profile directory for one user can be created
655 // after we start a merge. In this case the current profile for that user
656 // will not be found.
657 // Also, the secondary dex profiles might be deleted by the app at any time,
658 // so we can't we need to prepare if they are missing.
659 PLOG(ERROR) << "Failed to open profile " << profile;
660 }
661 return invalid_unique_fd();
662 }
663
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664 return fd;
665}
666
Calin Juravle824a64d2018-01-18 20:23:17 -0800667static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
668 const std::string& location, bool is_secondary_dex) {
669 std::string profile = create_current_profile_path(user, package_name, location,
670 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800671 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800672}
673
Calin Juravle824a64d2018-01-18 20:23:17 -0800674static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
675 const std::string& location, bool read_write, bool is_secondary_dex) {
676 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800677 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
678}
679
680static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800681 const std::string& location) {
682 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800683 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800684}
685
Calin Juravle824a64d2018-01-18 20:23:17 -0800686static void open_profile_files(uid_t uid, const std::string& package_name,
687 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800688 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800690 *reference_profile_fd = open_reference_profile(uid, package_name, location,
691 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692
Calin Juravle114f0812017-03-08 19:05:07 -0800693 // For secondary dex files, we don't really need the user but we use it for sanity checks.
694 // Note: the user owning the dex file should be the current user.
695 std::vector<userid_t> users;
696 if (is_secondary_dex){
697 users.push_back(multiuser_get_user_id(uid));
698 } else {
699 users = get_known_users(/*volume_uuid*/ nullptr);
700 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800702 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
703 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700704 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800705 if (profile_fd.get() >= 0) {
706 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 }
708 }
709}
710
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
712static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
713static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
714static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
715static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
Calin Juravle78728f32019-11-08 17:55:46 -0800716static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 5;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700717
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800718class RunProfman : public ExecVHelper {
719 public:
720 void SetupArgs(const std::vector<unique_fd>& profile_fds,
721 const unique_fd& reference_profile_fd,
722 const std::vector<unique_fd>& apk_fds,
723 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800724 bool copy_and_update,
725 bool for_snapshot,
726 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800727
728 // TODO(calin): Assume for now we run in the bg compile job (which is in
729 // most of the invocation). With the current data flow, is not very easy or
730 // clean to discover this in RunProfman (it will require quite a messy refactoring).
731 const char* profman_bin = select_execution_binary(
732 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700733
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800734 if (copy_and_update) {
735 CHECK_EQ(1u, profile_fds.size());
736 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000737 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800738 if (reference_profile_fd != -1) {
739 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000740 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800741
742 for (const unique_fd& fd : profile_fds) {
743 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
744 }
745
746 for (const unique_fd& fd : apk_fds) {
747 AddArg("--apk-fd=" + std::to_string(fd.get()));
748 }
749
750 for (const std::string& dex_location : dex_locations) {
751 AddArg("--dex-location=" + dex_location);
752 }
753
754 if (copy_and_update) {
755 AddArg("--copy-and-update-profile-key");
756 }
757
Calin Juravle78728f32019-11-08 17:55:46 -0800758 if (for_snapshot) {
759 AddArg("--force-merge");
760 }
761
762 if (for_boot_image) {
763 AddArg("--boot-image-merge");
764 }
765
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800766 // Do not add after dex2oat_flags, they should override others for debugging.
767 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800768 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800770 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
771 const unique_fd& reference_profile_fd,
772 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800773 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
774 bool for_snapshot = false,
775 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800776 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800777 reference_profile_fd,
778 apk_fds,
779 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800780 /*copy_and_update=*/ false,
781 for_snapshot,
782 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800783 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800785 void SetupCopyAndUpdate(unique_fd&& profile_fd,
786 unique_fd&& reference_profile_fd,
787 unique_fd&& apk_fd,
788 const std::string& dex_location) {
789 // The fds need to stay open longer than the scope of the function, so put them into a local
790 // variable vector.
791 profiles_fd_.push_back(std::move(profile_fd));
792 apk_fds_.push_back(std::move(apk_fd));
793 reference_profile_fd_ = std::move(reference_profile_fd);
794 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800795 SetupArgs(profiles_fd_,
796 reference_profile_fd_,
797 apk_fds_,
798 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800799 /*copy_and_update=*/true,
800 /*for_snapshot*/false,
801 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800802 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000803
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800804 void SetupDump(const std::vector<unique_fd>& profiles_fd,
805 const unique_fd& reference_profile_fd,
806 const std::vector<std::string>& dex_locations,
807 const std::vector<unique_fd>& apk_fds,
808 const unique_fd& output_fd) {
809 AddArg("--dump-only");
810 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800811 SetupArgs(profiles_fd,
812 reference_profile_fd,
813 apk_fds,
814 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800815 /*copy_and_update=*/false,
816 /*for_snapshot*/false,
817 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800818 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000819
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800820 void Exec() {
821 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
822 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000823
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800824 private:
825 unique_fd reference_profile_fd_;
826 std::vector<unique_fd> profiles_fd_;
827 std::vector<unique_fd> apk_fds_;
828};
Mathieu Chartier31636522018-11-09 23:53:07 +0000829
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800830
Calin Juravlef63d4792018-01-30 17:43:34 +0000831
Jeff Sharkey90aff262016-12-12 14:28:24 -0700832// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800833// The location is the package name for primary apks or the dex path for secondary dex files.
834// Returns true if there is enough information in the current profiles that makes it
835// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836// If the return value is true all the current profiles would have been merged into
837// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800838static bool analyze_profiles(uid_t uid, const std::string& package_name,
839 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800840 std::vector<unique_fd> profiles_fd;
841 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800842 open_profile_files(uid, package_name, location, is_secondary_dex,
843 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800844 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700845 // Skip profile guided compilation because no profiles were found.
846 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 return false;
848 }
849
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800850 RunProfman profman_merge;
851 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700852 pid_t pid = fork();
853 if (pid == 0) {
854 /* child -- drop privileges before continuing */
855 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800856 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700857 }
858 /* parent */
859 int return_code = wait_child(pid);
860 bool need_to_compile = false;
861 bool should_clear_current_profiles = false;
862 bool should_clear_reference_profile = false;
863 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800864 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865 } else {
866 return_code = WEXITSTATUS(return_code);
867 switch (return_code) {
868 case PROFMAN_BIN_RETURN_CODE_COMPILE:
869 need_to_compile = true;
870 should_clear_current_profiles = true;
871 should_clear_reference_profile = false;
872 break;
873 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
874 need_to_compile = false;
875 should_clear_current_profiles = false;
876 should_clear_reference_profile = false;
877 break;
878 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800879 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700880 need_to_compile = false;
881 should_clear_current_profiles = true;
882 should_clear_reference_profile = true;
883 break;
884 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
885 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
886 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800887 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 need_to_compile = false;
889 should_clear_current_profiles = false;
890 should_clear_reference_profile = false;
891 break;
892 default:
893 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800894 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800895 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 need_to_compile = false;
897 should_clear_current_profiles = true;
898 should_clear_reference_profile = true;
899 break;
900 }
901 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800902
Jeff Sharkey90aff262016-12-12 14:28:24 -0700903 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800904 if (is_secondary_dex) {
905 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800906 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
907 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800908 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800909 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800910 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700911 }
912 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800913 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700914 }
915 return need_to_compile;
916}
917
Calin Juravle114f0812017-03-08 19:05:07 -0800918// Decides if profile guided compilation is needed or not based on existing profiles.
919// The analysis is done for the primary apks of the given package.
920// Returns true if there is enough information in the current profiles that makes it
921// worth to recompile the package.
922// If the return value is true all the current profiles would have been merged into
923// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800924bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
925 const std::string& profile_name) {
926 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800927}
928
Calin Juravle408cd4a2018-01-20 23:34:18 -0800929bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
930 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800931 std::vector<unique_fd> profile_fds;
932 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800933 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
934 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935
Calin Juravle408cd4a2018-01-20 23:34:18 -0800936 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800937 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700938
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800939 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940 const bool has_profiles = !profile_fds.empty();
941
942 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800943 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700944 return false;
945 }
946
Calin Juravle114f0812017-03-08 19:05:07 -0800947 unique_fd output_fd(open(out_file_name.c_str(),
948 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700949 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800950 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700951 return false;
952 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800953
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800955 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800956 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
957 if (apk_fd == -1) {
958 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
959 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700960 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800961 dex_locations.push_back(get_location_from_path(code_path.c_str()));
962 apk_fds.push_back(std::move(apk_fd));
963
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800965 RunProfman profman_dump;
966 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967 pid_t pid = fork();
968 if (pid == 0) {
969 /* child -- drop privileges before continuing */
970 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800971 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972 }
973 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700974 int return_code = wait_child(pid);
975 if (!WIFEXITED(return_code)) {
976 LOG(WARNING) << "profman failed for package " << pkgname << ": "
977 << return_code;
978 return false;
979 }
980 return true;
981}
982
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700983bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800984 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700985 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
986 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800987 package_name,
988 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700989 /*read_write*/ true,
990 /*secondary*/ false));
991 if (in_fd.get() < 0) {
992 PLOG(WARNING) << "Could not open profile " << system_profile;
993 return false;
994 }
995 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800996 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700997 return false;
998 }
999
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001000 // As a security measure we want to write the profile information with the reduced capabilities
1001 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001002 pid_t pid = fork();
1003 if (pid == 0) {
1004 /* child -- drop privileges before continuing */
1005 drop_capabilities(packageUid);
1006
1007 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1008 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001009 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001010 }
1011 // This implies that the app owning this profile is running
1012 // (and has acquired the lock).
1013 //
1014 // The app never acquires the lock for the reference profiles of primary apks.
1015 // Only dex2oat from installd will do that. Since installd is single threaded
1016 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001017 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001018 return false;
1019 }
1020
1021 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1022 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001023 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001024 }
1025
1026 // Copy over data.
1027 static constexpr size_t kBufferSize = 4 * 1024;
1028 char buffer[kBufferSize];
1029 while (true) {
1030 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1031 if (bytes == 0) {
1032 break;
1033 }
1034 write(out_fd.get(), buffer, bytes);
1035 }
1036 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001037 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001038 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001039 // Use _exit since we don't want to run the global destructors in the child.
1040 // b/62597429
1041 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001042 }
1043 /* parent */
1044 int return_code = wait_child(pid);
1045 return return_code == 0;
1046}
1047
Jeff Sharkey90aff262016-12-12 14:28:24 -07001048static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1049 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1050 if (EndsWith(oat_path, ".dex")) {
1051 std::string new_path = oat_path;
1052 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001053 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001054 return new_path;
1055 }
1056
1057 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1058 // case (where the base name will have an extension for the B artifact).
1059 size_t odex_pos = oat_path.rfind(".odex");
1060 if (odex_pos != std::string::npos) {
1061 std::string new_path = oat_path;
1062 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1063 CHECK_NE(new_path.find(new_ext), std::string::npos);
1064 return new_path;
1065 }
1066
1067 // Don't know how to handle this.
1068 return "";
1069}
1070
1071// Translate the given oat path to an art (app image) path. An empty string
1072// denotes an error.
1073static std::string create_image_filename(const std::string& oat_path) {
1074 return replace_file_extension(oat_path, ".art");
1075}
1076
1077// Translate the given oat path to a vdex path. An empty string denotes an error.
1078static std::string create_vdex_filename(const std::string& oat_path) {
1079 return replace_file_extension(oat_path, ".vdex");
1080}
1081
Jeff Sharkey90aff262016-12-12 14:28:24 -07001082static int open_output_file(const char* file_name, bool recreate, int permissions) {
1083 int flags = O_RDWR | O_CREAT;
1084 if (recreate) {
1085 if (unlink(file_name) < 0) {
1086 if (errno != ENOENT) {
1087 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1088 }
1089 }
1090 flags |= O_EXCL;
1091 }
1092 return open(file_name, flags, permissions);
1093}
1094
Calin Juravle2289c0a2017-02-15 12:44:14 -08001095static bool set_permissions_and_ownership(
1096 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1097 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1098 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001099 if (fchmod(fd,
1100 S_IRUSR|S_IWUSR|S_IRGRP |
1101 (is_public ? S_IROTH : 0)) < 0) {
1102 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1103 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001104 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001105 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1106 return false;
1107 }
1108 return true;
1109}
1110
1111static bool IsOutputDalvikCache(const char* oat_dir) {
1112 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1113 // into '!'. Play it safe by handling it both.
1114 // TODO: ensure we never get null.
1115 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1116 return oat_dir == nullptr || oat_dir[0] == '!';
1117}
1118
Calin Juravled23dee72017-07-06 16:29:11 -07001119// Best-effort check whether we can fit the the path into our buffers.
1120// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1121// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1122// extension to the cache path (5 bytes).
1123// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1124static bool validate_dex_path_size(const std::string& dex_path) {
1125 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1126 LOG(ERROR) << "dex_path too long: " << dex_path;
1127 return false;
1128 }
1129 return true;
1130}
1131
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001133 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001134 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135 return false;
1136 }
1137
1138 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001139 // Oat dirs for secondary dex files are already validated.
1140 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001141 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1142 return false;
1143 }
1144 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1145 return false;
1146 }
1147 } else {
1148 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1149 return false;
1150 }
1151 }
1152 return true;
1153}
1154
1155// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1156// on destruction. It will also run the given cleanup (unless told not to) after closing.
1157//
1158// Usage example:
1159//
Calin Juravle7a570e82017-01-14 16:23:30 -08001160// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001161// [name]() {
1162// unlink(name.c_str());
1163// });
1164// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1165// wrapper if captured as a reference.
1166//
1167// if (file.get() == -1) {
1168// // Error opening...
1169// }
1170//
1171// ...
1172// if (error) {
1173// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1174// // and delete the file (after the fd is closed).
1175// return -1;
1176// }
1177//
1178// (Success case)
1179// file.SetCleanup(false);
1180// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1181// // (leaving the file around; after the fd is closed).
1182//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001183class Dex2oatFileWrapper {
1184 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001185 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001186 }
1187
Calin Juravle7a570e82017-01-14 16:23:30 -08001188 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1189 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1190
1191 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1192 value_ = other.value_;
1193 cleanup_ = other.cleanup_;
1194 do_cleanup_ = other.do_cleanup_;
1195 auto_close_ = other.auto_close_;
1196 other.release();
1197 }
1198
1199 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1200 value_ = other.value_;
1201 cleanup_ = other.cleanup_;
1202 do_cleanup_ = other.do_cleanup_;
1203 auto_close_ = other.auto_close_;
1204 other.release();
1205 return *this;
1206 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001207
1208 ~Dex2oatFileWrapper() {
1209 reset(-1);
1210 }
1211
1212 int get() {
1213 return value_;
1214 }
1215
1216 void SetCleanup(bool cleanup) {
1217 do_cleanup_ = cleanup;
1218 }
1219
1220 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001221 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001222 close(value_);
1223 }
1224 if (do_cleanup_ && cleanup_ != nullptr) {
1225 cleanup_();
1226 }
1227
1228 value_ = new_value;
1229 }
1230
Calin Juravle7a570e82017-01-14 16:23:30 -08001231 void reset(int new_value, std::function<void ()> new_cleanup) {
1232 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001233 close(value_);
1234 }
1235 if (do_cleanup_ && cleanup_ != nullptr) {
1236 cleanup_();
1237 }
1238
1239 value_ = new_value;
1240 cleanup_ = new_cleanup;
1241 }
1242
Calin Juravle7a570e82017-01-14 16:23:30 -08001243 void DisableAutoClose() {
1244 auto_close_ = false;
1245 }
1246
Jeff Sharkey90aff262016-12-12 14:28:24 -07001247 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001248 void release() {
1249 value_ = -1;
1250 do_cleanup_ = false;
1251 cleanup_ = nullptr;
1252 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001253 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001254 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001255 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001256 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001257};
1258
Calin Juravle7a570e82017-01-14 16:23:30 -08001259// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001260Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1261 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001262
1263 // We don't create an image for secondary dex files.
1264 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001265 return Dex2oatFileWrapper();
1266 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001267
Calin Juravle7a570e82017-01-14 16:23:30 -08001268 const std::string image_path = create_image_filename(out_oat_path);
1269 if (image_path.empty()) {
1270 // Happens when the out_oat_path has an unknown extension.
1271 return Dex2oatFileWrapper();
1272 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001273
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001274 // In case there is a stale image, remove it now. Ignore any error.
1275 unlink(image_path.c_str());
1276
1277 // Not enabled, exit.
1278 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001279 return Dex2oatFileWrapper();
1280 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001281 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1282 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001283 return Dex2oatFileWrapper();
1284 }
1285 // Recreate is true since we do not want to modify a mapped image. If the app is
1286 // already running and we modify the image file, it can cause crashes (b/27493510).
1287 Dex2oatFileWrapper wrapper_fd(
1288 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1289 [image_path]() { unlink(image_path.c_str()); });
1290 if (wrapper_fd.get() < 0) {
1291 // Could not create application image file. Go on since we can compile without it.
1292 LOG(ERROR) << "installd could not create '" << image_path
1293 << "' for image file during dexopt";
1294 // If we have a valid image file path but no image fd, explicitly erase the image file.
1295 if (unlink(image_path.c_str()) < 0) {
1296 if (errno != ENOENT) {
1297 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1298 }
1299 }
1300 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001301 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001302 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1303 wrapper_fd.reset(-1);
1304 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001305
Calin Juravle7a570e82017-01-14 16:23:30 -08001306 return wrapper_fd;
1307}
1308
1309// Creates the dexopt swap file if necessary and return its fd.
1310// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001311unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001312 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001313 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001314 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001315 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001316 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001317 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001318 if (swap_fd.get() < 0) {
1319 // Could not create swap file. Optimistically go on and hope that we can compile
1320 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001321 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001322 } else {
1323 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001324 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001325 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1326 }
1327 }
1328 return swap_fd;
1329}
1330
1331// Opens the reference profiles if needed.
1332// 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 -08001333Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001334 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001335 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001336 // If we are not profile guided compilation, or we are compiling system server
1337 // do not bother to open the profiles; we won't be using them.
1338 if (!profile_guided || (pkgname[0] == '*')) {
1339 return Dex2oatFileWrapper();
1340 }
1341
1342 // If this is a secondary dex path which is public do not open the profile.
1343 // We cannot compile public secondary dex paths with profiles. That's because
1344 // it will expose how the dex files are used by their owner.
1345 //
1346 // Note that the PackageManager is responsible to set the is_public flag for
1347 // primary apks and we do not check it here. In some cases, e.g. when
1348 // compiling with a public profile from the .dm file the PackageManager will
1349 // set is_public toghether with the profile guided compilation.
1350 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001351 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001352 }
Calin Juravle114f0812017-03-08 19:05:07 -08001353
1354 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001355 std::string location;
1356 if (is_secondary_dex) {
1357 location = dex_path;
1358 } else {
1359 if (profile_name == nullptr) {
1360 // This path is taken for system server re-compilation lunched from ZygoteInit.
1361 return Dex2oatFileWrapper();
1362 } else {
1363 location = profile_name;
1364 }
1365 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001366 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1367 is_secondary_dex);
1368 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1369 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001370 };
1371 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001372}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001373
Calin Juravle7a570e82017-01-14 16:23:30 -08001374// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1375// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001376bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001377 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001378 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001379 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1380 CHECK(in_vdex_wrapper_fd != nullptr);
1381 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001382 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1383 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001384 char in_odex_path[PKG_PATH_MAX];
1385 int dexopt_action = abs(dexopt_needed);
1386 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001387 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001388
1389 // Infer the name of the output VDEX.
1390 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1391 if (out_vdex_path_str.empty()) {
1392 return false;
1393 }
1394
1395 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001396 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001397 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1398 const char* path = nullptr;
1399 if (is_odex_location) {
1400 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1401 path = in_odex_path;
1402 } else {
1403 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001404 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001405 }
1406 } else {
1407 path = out_oat_path;
1408 }
1409 in_vdex_path_str = create_vdex_filename(path);
1410 if (in_vdex_path_str.empty()) {
1411 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001412 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001413 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001414 // We can update in place when all these conditions are met:
1415 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1416 // on /system typically cannot be updated in place).
1417 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1418 // cannot be currently used by a running process.
1419 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1420 // different vdex files to operate.
1421 update_vdex_in_place =
1422 (in_vdex_path_str == out_vdex_path_str) &&
1423 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1424 !profile_guided;
1425 if (update_vdex_in_place) {
1426 // Open the file read-write to be able to update it.
1427 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1428 if (in_vdex_wrapper_fd->get() == -1) {
1429 // If we failed to open the file, we cannot update it in place.
1430 update_vdex_in_place = false;
1431 }
1432 } else {
1433 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1434 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001435 }
1436
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001437 // If we are updating the vdex in place, we do not need to recreate a vdex,
1438 // and can use the same existing one.
1439 if (update_vdex_in_place) {
1440 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1441 // have bogus stale vdex files.
1442 out_vdex_wrapper_fd->reset(
1443 in_vdex_wrapper_fd->get(),
1444 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1445 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1446 // wrapper).
1447 in_vdex_wrapper_fd->DisableAutoClose();
1448 } else {
1449 out_vdex_wrapper_fd->reset(
1450 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1451 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1452 if (out_vdex_wrapper_fd->get() < 0) {
1453 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1454 return false;
1455 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001456 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001457 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001458 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001459 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1460 return false;
1461 }
1462
1463 // If we got here we successfully opened the vdex files.
1464 return true;
1465}
1466
1467// Opens the output oat file for the given apk.
1468// If successful it stores the output path into out_oat_path and returns true.
1469Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001470 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1471 char* out_oat_path) {
1472 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001473 return Dex2oatFileWrapper();
1474 }
1475 const std::string out_oat_path_str(out_oat_path);
1476 Dex2oatFileWrapper wrapper_fd(
1477 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1478 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1479 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001480 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001481 } else if (!set_permissions_and_ownership(
1482 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001483 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1484 wrapper_fd.reset(-1);
1485 }
1486 return wrapper_fd;
1487}
1488
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001489// Creates RDONLY fds for oat and vdex files, if exist.
1490// Returns false if it fails to create oat out path for the given apk path.
1491// Note that the method returns true even if the files could not be opened.
1492bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1493 const std::string& oat_dir,
1494 const std::string& instruction_set,
1495 bool is_secondary_dex,
1496 unique_fd* oat_file_fd,
1497 unique_fd* vdex_file_fd) {
1498 char oat_path[PKG_PATH_MAX];
1499 if (!create_oat_out_path(apk_path.c_str(),
1500 instruction_set.c_str(),
1501 oat_dir.c_str(),
1502 is_secondary_dex,
1503 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001504 LOG(ERROR) << "Could not create oat out path for "
1505 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001506 return false;
1507 }
1508 oat_file_fd->reset(open(oat_path, O_RDONLY));
1509 if (oat_file_fd->get() < 0) {
1510 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1511 }
1512
1513 std::string vdex_filename = create_vdex_filename(oat_path);
1514 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1515 if (vdex_file_fd->get() < 0) {
1516 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1517 }
1518
1519 return true;
1520}
1521
Calin Juravle7a570e82017-01-14 16:23:30 -08001522// Updates the access times of out_oat_path based on those from apk_path.
1523void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1524 struct stat input_stat;
1525 memset(&input_stat, 0, sizeof(input_stat));
1526 if (stat(apk_path, &input_stat) != 0) {
1527 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1528 return;
1529 }
1530
1531 struct utimbuf ut;
1532 ut.actime = input_stat.st_atime;
1533 ut.modtime = input_stat.st_mtime;
1534 if (utime(out_oat_path, &ut) != 0) {
1535 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1536 }
1537}
1538
Calin Juravle80a21252017-01-17 14:43:25 -08001539// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001540// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1541// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1542// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001543class RunDexoptAnalyzer : public ExecVHelper {
1544 public:
1545 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001546 int vdex_fd,
1547 int oat_fd,
1548 int zip_fd,
1549 const std::string& instruction_set,
1550 const std::string& compiler_filter,
1551 bool profile_was_updated,
1552 bool downgrade,
1553 const char* class_loader_context,
1554 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001555 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001556
1557 // We always run the analyzer in the background job.
1558 const char* dexoptanalyzer_bin = select_execution_binary(
1559 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001560
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001561 std::string dex_file_arg = "--dex-file=" + dex_file;
1562 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1563 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1564 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1565 std::string isa_arg = "--isa=" + instruction_set;
1566 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1567 const char* assume_profile_changed = "--assume-profile-changed";
1568 const char* downgrade_flag = "--downgrade";
1569 std::string class_loader_context_arg = "--class-loader-context=";
1570 if (class_loader_context != nullptr) {
1571 class_loader_context_arg += class_loader_context;
1572 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001573 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1574 if (!class_loader_context_fds.empty()) {
1575 class_loader_context_fds_arg += class_loader_context_fds;
1576 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001577
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001578 // program name, dex file, isa, filter
1579 AddArg(dex_file_arg);
1580 AddArg(isa_arg);
1581 AddArg(compiler_filter_arg);
1582 if (oat_fd >= 0) {
1583 AddArg(oat_fd_arg);
1584 }
1585 if (vdex_fd >= 0) {
1586 AddArg(vdex_fd_arg);
1587 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001588 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001589 if (profile_was_updated) {
1590 AddArg(assume_profile_changed);
1591 }
1592 if (downgrade) {
1593 AddArg(downgrade_flag);
1594 }
1595 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001596 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001597 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001598 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001599 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001600 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001601
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001602 PrepareArgs(dexoptanalyzer_bin);
1603 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001604
1605 // Dexoptanalyzer mode which flattens the given class loader context and
1606 // prints a list of its dex files in that flattened order.
1607 RunDexoptAnalyzer(const char* class_loader_context) {
1608 CHECK(class_loader_context != nullptr);
1609
1610 // We always run the analyzer in the background job.
1611 const char* dexoptanalyzer_bin = select_execution_binary(
1612 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1613
1614 AddArg("--flatten-class-loader-context");
1615 AddArg(std::string("--class-loader-context=") + class_loader_context);
1616 PrepareArgs(dexoptanalyzer_bin);
1617 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001618};
Calin Juravle80a21252017-01-17 14:43:25 -08001619
1620// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001621static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001622 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001623 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001624 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001625 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001626 return false;
1627 }
Calin Juravle114f0812017-03-08 19:05:07 -08001628 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001629
Calin Juravle80a21252017-01-17 14:43:25 -08001630 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001631 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1632 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001633 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001634 return false;
1635 }
1636
1637 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001638 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001639
Calin Juravle7d765462017-09-04 15:57:10 -07001640 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001641 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001642 return false;
1643 }
1644
1645 return true;
1646}
1647
Calin Juravle7d765462017-09-04 15:57:10 -07001648// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1649// secondary dex files. This return codes are returned by the child process created for
1650// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001651
Andreas Gampe194fe422018-02-28 20:16:19 -08001652enum DexoptAnalyzerSkipCodes {
1653 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001654 // Specific errors are encoded in the name.
1655 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1656 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1657 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1658 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1659 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001660 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001661 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001662};
Calin Juravle7d765462017-09-04 15:57:10 -07001663
1664// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001665// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1666// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001667// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1668// of dexoptanalyzer.
1669static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001670 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001671 // The result values are defined in dexoptanalyzer.
1672 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001673 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001674 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001675 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001676 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001677 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001678 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001679 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001680 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001681 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1682 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001683 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1684 " Expected odex file status for secondary dex %s"
1685 " : dexoptanalyzer result=%d",
1686 dex_path.c_str(),
1687 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001688 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001689 }
1690
1691 // Use a second switch for enum switch-case analysis.
1692 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001693 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001694 // If the file does not exist there's no need for dexopt.
1695 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1696 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001697
1698 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1699 *error_msg = "Dexoptanalyzer path validation failed";
1700 return false;
1701 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1702 *error_msg = "Dexoptanalyzer open zip failed";
1703 return false;
1704 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1705 *error_msg = "Dexoptanalyzer dir preparation failed";
1706 return false;
1707 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1708 *error_msg = "Dexoptanalyzer open output failed";
1709 return false;
1710 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1711 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001712 return false;
1713 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001714
1715 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1716 dex_path.c_str(),
1717 result);
1718 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001719}
1720
Calin Juravle7d765462017-09-04 15:57:10 -07001721enum SecondaryDexAccess {
1722 kSecondaryDexAccessReadOk = 0,
1723 kSecondaryDexAccessDoesNotExist = 1,
1724 kSecondaryDexAccessPermissionError = 2,
1725 kSecondaryDexAccessIOError = 3
1726};
1727
1728static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1729 // Check if the path exists and can be read. If not, there's nothing to do.
1730 if (access(dex_path.c_str(), R_OK) == 0) {
1731 return kSecondaryDexAccessReadOk;
1732 } else {
1733 if (errno == ENOENT) {
1734 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1735 return kSecondaryDexAccessDoesNotExist;
1736 } else {
1737 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1738 return errno == EACCES
1739 ? kSecondaryDexAccessPermissionError
1740 : kSecondaryDexAccessIOError;
1741 }
1742 }
1743}
1744
1745static bool is_file_public(const std::string& filename) {
1746 struct stat file_stat;
1747 if (stat(filename.c_str(), &file_stat) == 0) {
1748 return (file_stat.st_mode & S_IROTH) != 0;
1749 }
1750 return false;
1751}
1752
1753// Create the oat file structure for the secondary dex 'dex_path' and assign
1754// the individual path component to the 'out_' parameters.
1755static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001756 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001757 size_t dirIndex = dex_path.rfind('/');
1758 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001759 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001760 return false;
1761 }
1762 // TODO(calin): we have similar computations in at lest 3 other places
1763 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1764 // using string append.
1765 std::string apk_dir = dex_path.substr(0, dirIndex);
1766 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1767 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1768
1769 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1770 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001771 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001772 return false;
1773 }
1774 return true;
1775}
1776
1777// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1778// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001779static bool validate_dexopt_storage_flags(int dexopt_flags,
1780 int* out_storage_flag,
1781 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001782 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1783 *out_storage_flag = FLAG_STORAGE_CE;
1784 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001785 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001786 return false;
1787 }
1788 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1789 *out_storage_flag = FLAG_STORAGE_DE;
1790 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001791 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001792 return false;
1793 }
1794 return true;
1795}
1796
David Brazdil4f6027a2019-03-19 11:44:21 +00001797static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1798 /* out */ std::vector<std::string>* context_dex_paths) {
1799 if (class_loader_context == nullptr) {
1800 return true;
1801 }
1802
1803 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1804
1805 // Pipe to get the hash result back from our child process.
1806 unique_fd pipe_read, pipe_write;
1807 if (!Pipe(&pipe_read, &pipe_write)) {
1808 PLOG(ERROR) << "Failed to create pipe";
1809 return false;
1810 }
1811
1812 pid_t pid = fork();
1813 if (pid == 0) {
1814 // child -- drop privileges before continuing.
1815 drop_capabilities(uid);
1816
1817 // Route stdout to `pipe_write`
1818 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1819 pipe_write.reset();
1820 pipe_read.reset();
1821
1822 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1823 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1824 }
1825
1826 /* parent */
1827 pipe_write.reset();
1828
1829 std::string str_dex_paths;
1830 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1831 PLOG(ERROR) << "Failed to read from pipe";
1832 return false;
1833 }
1834 pipe_read.reset();
1835
1836 int return_code = wait_child(pid);
1837 if (!WIFEXITED(return_code)) {
1838 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1839 return false;
1840 }
1841
1842 constexpr int kFlattenClassLoaderContextSuccess = 50;
1843 return_code = WEXITSTATUS(return_code);
1844 if (return_code != kFlattenClassLoaderContextSuccess) {
1845 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1846 return false;
1847 }
1848
1849 if (!str_dex_paths.empty()) {
1850 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1851 }
1852 return true;
1853}
1854
1855static int open_dex_paths(const std::vector<std::string>& dex_paths,
1856 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1857 for (const std::string& dex_path : dex_paths) {
1858 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1859 if (zip_fds->back().get() < 0) {
1860 *error_msg = StringPrintf(
1861 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1862 if (errno == ENOENT) {
1863 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1864 } else {
1865 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1866 }
1867 }
1868 }
1869 return 0;
1870}
1871
1872static std::string join_fds(const std::vector<unique_fd>& fds) {
1873 std::stringstream ss;
1874 bool is_first = true;
1875 for (const unique_fd& fd : fds) {
1876 if (is_first) {
1877 is_first = false;
1878 } else {
1879 ss << ":";
1880 }
1881 ss << fd.get();
1882 }
1883 return ss.str();
1884}
1885
Calin Juravlec9eab382017-01-25 01:17:17 -08001886// 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 -08001887// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1888// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001889// When returning true, the output parameters will be:
1890// - is_public_out: whether or not the oat file should not be made public
1891// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1892// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001893static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001894 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001895 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001896 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001897 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001898 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001899 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001900 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1901 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001902 return false;
1903 }
Calin Juravle7d765462017-09-04 15:57:10 -07001904 // Compute the oat dir as it's not easy to extract it from the child computation.
1905 char oat_path[PKG_PATH_MAX];
1906 char oat_dir[PKG_PATH_MAX];
1907 char oat_isa_dir[PKG_PATH_MAX];
1908 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001909 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1910 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001911 return false;
1912 }
Calin Juravle7d765462017-09-04 15:57:10 -07001913 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001914
Calin Juravle80a21252017-01-17 14:43:25 -08001915 pid_t pid = fork();
1916 if (pid == 0) {
1917 // child -- drop privileges before continuing.
1918 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001919
1920 // Validate the path structure.
1921 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1922 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001923 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001924 }
1925
1926 // Open the dex file.
1927 unique_fd zip_fd;
1928 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1929 if (zip_fd.get() < 0) {
1930 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001931 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001932 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001933 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001934 }
1935 }
1936
David Brazdil4f6027a2019-03-19 11:44:21 +00001937 // Open class loader context dex files.
1938 std::vector<unique_fd> context_zip_fds;
1939 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1940 if (open_dex_paths_rc != 0) {
1941 _exit(open_dex_paths_rc);
1942 }
1943
Calin Juravle7d765462017-09-04 15:57:10 -07001944 // Prepare the oat directories.
1945 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001946 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001947 }
1948
1949 // Open the vdex/oat files if any.
1950 unique_fd oat_file_fd;
1951 unique_fd vdex_file_fd;
1952 if (!maybe_open_oat_and_vdex_file(dex_path,
1953 *oat_dir_out,
1954 instruction_set,
1955 true /* is_secondary_dex */,
1956 &oat_file_fd,
1957 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001958 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001959 }
1960
1961 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001962 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1963 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001964
1965 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001966 // Note that we do not do it before the fork since opening the files is required to happen
1967 // after forking.
1968 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1969 vdex_file_fd.get(),
1970 oat_file_fd.get(),
1971 zip_fd.get(),
1972 instruction_set,
1973 compiler_filter, profile_was_updated,
1974 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001975 class_loader_context,
1976 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001977 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001978 }
1979
1980 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001981 int result = wait_child(pid);
1982 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001983 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1984 dex_path.c_str(),
1985 result);
1986 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001987 return false;
1988 }
1989 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001990 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001991 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1992 result,
1993 dexopt_needed_out,
1994 error_msg);
1995 if (!success) {
1996 LOG(ERROR) << *error_msg;
1997 }
Calin Juravle7d765462017-09-04 15:57:10 -07001998
1999 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2000
Calin Juravle80a21252017-01-17 14:43:25 -08002001 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002002 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2003 // makes the code simpler; force compilation is only needed during tests).
2004 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002005 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002006 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002007 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2008 }
2009
Calin Juravle7d765462017-09-04 15:57:10 -07002010 // Check if we should make the oat file public.
2011 // Note that if the dex file is not public the compiled code cannot be made public.
2012 // It is ok to check this flag outside in the parent process.
2013 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2014
Calin Juravle80a21252017-01-17 14:43:25 -08002015 return success;
2016}
2017
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002018static std::string format_dexopt_error(int status, const char* dex_path) {
2019 if (WIFEXITED(status)) {
2020 int int_code = WEXITSTATUS(status);
2021 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2022 if (code_name != nullptr) {
2023 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2024 }
2025 }
2026 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002027}
2028
Calin Juravlec9eab382017-01-25 01:17:17 -08002029int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002030 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002031 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002032 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002033 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002034 CHECK(pkgname != nullptr);
2035 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002036 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002037 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2038 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002039
Calin Juravled23dee72017-07-06 16:29:11 -07002040 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002041 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002042 return -1;
2043 }
2044
2045 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002046 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2047 class_loader_context);
2048 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002049 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002050 }
2051
Calin Juravleebc8a792017-04-04 20:21:05 -07002052 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002053 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2054 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2055 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002056 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002057 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002058 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002059 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002060 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002061
2062 // Check if we're dealing with a secondary dex file and if we need to compile it.
2063 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002064 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002065 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002066 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2067 *error_msg = "Failed acquiring context dex paths";
2068 return -1; // We had an error, logged in the process method.
2069 }
2070
Calin Juravlec9eab382017-01-25 01:17:17 -08002071 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002072 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002073 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002074 oat_dir = oat_dir_str.c_str();
2075 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2076 return 0; // Nothing to do, report success.
2077 }
2078 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002079 if (error_msg->empty()) { // TODO: Make this a CHECK.
2080 *error_msg = "Failed processing secondary.";
2081 }
Calin Juravle80a21252017-01-17 14:43:25 -08002082 return -1; // We had an error, logged in the process method.
2083 }
2084 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002085 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002086 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002087 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2088 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2089 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002090
2091 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002092 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002093 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002094 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2095 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002096 return -1;
2097 }
2098
David Brazdil4f6027a2019-03-19 11:44:21 +00002099 // Open class loader context dex files.
2100 std::vector<unique_fd> context_input_fds;
2101 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2102 LOG(ERROR) << *error_msg;
2103 return -1;
2104 }
2105
Calin Juravle7a570e82017-01-14 16:23:30 -08002106 // Create the output OAT file.
2107 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002108 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002109 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002110 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002111 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002112 return -1;
2113 }
2114
2115 // Open vdex files.
2116 Dex2oatFileWrapper in_vdex_fd;
2117 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002118 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2119 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002120 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002121 return -1;
2122 }
2123
Calin Juravlecb556e32017-04-04 20:22:50 -07002124 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2125 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2126 // fully inherit their parent context).
2127 // Note that for primary apk the oat files are created before, in a separate installd
2128 // call which also does the restorecon. TODO(calin): unify the paths.
2129 if (is_secondary_dex) {
2130 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2131 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002132 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2133 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002134 return -1;
2135 }
2136 }
2137
Jeff Sharkey90aff262016-12-12 14:28:24 -07002138 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002139 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002140
Calin Juravle7a570e82017-01-14 16:23:30 -08002141 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002142 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002143 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002144
liulvping61907742018-08-21 09:36:52 +08002145 if (reference_profile_fd.get() == -1) {
2146 // We don't create an app image without reference profile since there is no speedup from
2147 // loading it in that case and instead will be a small overhead.
2148 generate_app_image = false;
2149 }
2150
2151 // Create the app image file if needed.
2152 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2153 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2154
Calin Juravle62c5a372018-02-01 17:03:23 +00002155 unique_fd dex_metadata_fd;
2156 if (dex_metadata_path != nullptr) {
2157 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2158 if (dex_metadata_fd.get() < 0) {
2159 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2160 }
2161 }
2162
Andreas Gampe023b2242018-02-28 16:03:25 -08002163 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002164
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002165 RunDex2Oat runner(input_fd.get(),
2166 out_oat_fd.get(),
2167 in_vdex_fd.get(),
2168 out_vdex_fd.get(),
2169 image_fd.get(),
2170 dex_path,
2171 out_oat_path,
2172 swap_fd.get(),
2173 instruction_set,
2174 compiler_filter,
2175 debuggable,
2176 boot_complete,
2177 background_job_compile,
2178 reference_profile_fd.get(),
2179 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002180 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002181 target_sdk_version,
2182 enable_hidden_api_checks,
2183 generate_compact_dex,
2184 dex_metadata_fd.get(),
2185 compilation_reason);
2186
Jeff Sharkey90aff262016-12-12 14:28:24 -07002187 pid_t pid = fork();
2188 if (pid == 0) {
2189 /* child -- drop privileges before continuing */
2190 drop_capabilities(uid);
2191
Richard Uhler76cc0272016-12-08 10:46:35 +00002192 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002193 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002194 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002195 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002196 }
2197
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002198 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002199 } else {
2200 int res = wait_child(pid);
2201 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002202 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002203 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002204 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2205 << std::hex << std::setw(4) << res << ", process failed";
2206 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002207 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002208 }
2209 }
2210
Calin Juravlec9eab382017-01-25 01:17:17 -08002211 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002212
2213 // We've been successful, don't delete output.
2214 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002215 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002216 image_fd.SetCleanup(false);
2217 reference_profile_fd.SetCleanup(false);
2218
2219 return 0;
2220}
2221
Calin Juravlec9eab382017-01-25 01:17:17 -08002222// Try to remove the given directory. Log an error if the directory exists
2223// and is empty but could not be removed.
2224static bool rmdir_if_empty(const char* dir) {
2225 if (rmdir(dir) == 0) {
2226 return true;
2227 }
2228 if (errno == ENOENT || errno == ENOTEMPTY) {
2229 return true;
2230 }
2231 PLOG(ERROR) << "Failed to remove dir: " << dir;
2232 return false;
2233}
2234
2235// Try to unlink the given file. Log an error if the file exists and could not
2236// be unlinked.
2237static bool unlink_if_exists(const std::string& file) {
2238 if (unlink(file.c_str()) == 0) {
2239 return true;
2240 }
2241 if (errno == ENOENT) {
2242 return true;
2243
2244 }
2245 PLOG(ERROR) << "Could not unlink: " << file;
2246 return false;
2247}
2248
Calin Juravle7d765462017-09-04 15:57:10 -07002249enum ReconcileSecondaryDexResult {
2250 kReconcileSecondaryDexExists = 0,
2251 kReconcileSecondaryDexCleanedUp = 1,
2252 kReconcileSecondaryDexValidationError = 2,
2253 kReconcileSecondaryDexCleanUpError = 3,
2254 kReconcileSecondaryDexAccessIOError = 4,
2255};
Calin Juravlec9eab382017-01-25 01:17:17 -08002256
2257// Reconcile the secondary dex 'dex_path' and its generated oat files.
2258// Return true if all the parameters are valid and the secondary dex file was
2259// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2260// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2261// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2262// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2263// Return false if there were errors during processing. In this case
2264// out_secondary_dex_exists will be set to false.
2265bool reconcile_secondary_dex_file(const std::string& dex_path,
2266 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2267 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2268 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002269 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002270 if (isas.size() == 0) {
2271 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2272 return false;
2273 }
2274
Calin Juravle7d765462017-09-04 15:57:10 -07002275 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2276 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2277 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002278 return false;
2279 }
2280
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002281 // As a security measure we want to unlink art artifacts with the reduced capabilities
2282 // of the package user id. So we fork and drop capabilities in the child.
2283 pid_t pid = fork();
2284 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002285 /* child -- drop privileges before continuing */
2286 drop_capabilities(uid);
2287
2288 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Greg Kaiser8042c372019-03-26 06:23:19 -07002289 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002290 uid, storage_flag)) {
2291 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2292 _exit(kReconcileSecondaryDexValidationError);
2293 }
2294
2295 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2296 switch (access_check) {
2297 case kSecondaryDexAccessDoesNotExist:
2298 // File does not exist. Proceed with cleaning.
2299 break;
2300 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2301 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2302 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2303 default:
2304 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2305 _exit(kReconcileSecondaryDexValidationError);
2306 }
2307
2308 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002309 char oat_path[PKG_PATH_MAX];
2310 char oat_dir[PKG_PATH_MAX];
2311 char oat_isa_dir[PKG_PATH_MAX];
2312 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002313 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002314 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002315 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002316 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2317 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002318 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002319 }
Calin Juravle51314092017-05-18 15:33:05 -07002320
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002321 // Delete oat/vdex/art files.
2322 result = unlink_if_exists(oat_path) && result;
2323 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2324 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002325
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002326 // Delete profiles.
2327 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002328 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002329 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002330 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002331 result = unlink_if_exists(current_profile) && result;
2332 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002333
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002334 // We upgraded once the location of current profile for secondary dex files.
2335 // Check for any previous left-overs and remove them as well.
2336 std::string old_current_profile = dex_path + ".prof";
2337 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002338
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002339 // Try removing the directories as well, they might be empty.
2340 result = rmdir_if_empty(oat_isa_dir) && result;
2341 result = rmdir_if_empty(oat_dir) && result;
2342 }
Calin Juravle7d765462017-09-04 15:57:10 -07002343 if (!result) {
2344 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2345 }
2346 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002347 }
2348
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002349 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002350 if (!WIFEXITED(return_code)) {
2351 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2352 } else {
2353 return_code = WEXITSTATUS(return_code);
2354 }
2355
2356 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2357
2358 switch (return_code) {
2359 case kReconcileSecondaryDexCleanedUp:
2360 case kReconcileSecondaryDexValidationError:
2361 // If we couldn't validate assume the dex file does not exist.
2362 // This will purge the entry from the PM records.
2363 *out_secondary_dex_exists = false;
2364 return true;
2365 case kReconcileSecondaryDexExists:
2366 *out_secondary_dex_exists = true;
2367 return true;
2368 case kReconcileSecondaryDexAccessIOError:
2369 // We had an access IO error.
2370 // Return false so that we can try again.
2371 // The value of out_secondary_dex_exists does not matter in this case and by convention
2372 // is set to false.
2373 *out_secondary_dex_exists = false;
2374 return false;
2375 default:
2376 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2377 *out_secondary_dex_exists = false;
2378 return false;
2379 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002380}
2381
Alan Stokesa25d90c2017-10-16 10:56:00 +01002382// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2383// Returns true if all parameters are valid and the hash successfully computed and stored in
2384// out_secondary_dex_hash.
2385// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2386// the app.
2387// For any other errors (e.g. if any of the parameters are invalid) returns false.
2388bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2389 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2390 std::vector<uint8_t>* out_secondary_dex_hash) {
2391 out_secondary_dex_hash->clear();
2392
2393 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2394
2395 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2396 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2397 << storage_flag;
2398 return false;
2399 }
2400
2401 // Pipe to get the hash result back from our child process.
2402 unique_fd pipe_read, pipe_write;
2403 if (!Pipe(&pipe_read, &pipe_write)) {
2404 PLOG(ERROR) << "Failed to create pipe";
2405 return false;
2406 }
2407
2408 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2409 // access data the app itself can access.
2410 pid_t pid = fork();
2411 if (pid == 0) {
2412 // child -- drop privileges before continuing
2413 drop_capabilities(uid);
2414 pipe_read.reset();
2415
2416 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2417 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002418 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002419 }
2420
2421 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2422 if (fd == -1) {
2423 if (errno == EACCES || errno == ENOENT) {
2424 // Not treated as an error.
2425 _exit(0);
2426 }
2427 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002428 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002429 }
2430
2431 SHA256_CTX ctx;
2432 SHA256_Init(&ctx);
2433
2434 std::vector<uint8_t> buffer(65536);
2435 while (true) {
2436 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2437 if (bytes_read == 0) {
2438 break;
2439 } else if (bytes_read == -1) {
2440 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002441 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002442 }
2443
2444 SHA256_Update(&ctx, buffer.data(), bytes_read);
2445 }
2446
2447 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2448 SHA256_Final(hash.data(), &ctx);
2449 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002450 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002451 }
2452
2453 _exit(0);
2454 }
2455
2456 // parent
2457 pipe_write.reset();
2458
2459 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2460 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2461 out_secondary_dex_hash->clear();
2462 }
2463 return wait_child(pid) == 0;
2464}
2465
Jeff Sharkey90aff262016-12-12 14:28:24 -07002466// Helper for move_ab, so that we can have common failure-case cleanup.
2467static bool unlink_and_rename(const char* from, const char* to) {
2468 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2469 // return a failure.
2470 struct stat s;
2471 if (stat(to, &s) == 0) {
2472 if (!S_ISREG(s.st_mode)) {
2473 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2474 return false;
2475 }
2476 if (unlink(to) != 0) {
2477 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2478 return false;
2479 }
2480 } else {
2481 // This may be a permission problem. We could investigate the error code, but we'll just
2482 // let the rename failure do the work for us.
2483 }
2484
2485 // Try to rename "to" to "from."
2486 if (rename(from, to) != 0) {
2487 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2488 return false;
2489 }
2490 return true;
2491}
2492
2493// Move/rename a B artifact (from) to an A artifact (to).
2494static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2495 // Check whether B exists.
2496 {
2497 struct stat s;
2498 if (stat(b_path.c_str(), &s) != 0) {
2499 // Silently ignore for now. The service calling this isn't smart enough to understand
2500 // lack of artifacts at the moment.
2501 return false;
2502 }
2503 if (!S_ISREG(s.st_mode)) {
2504 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2505 // Try to unlink, but swallow errors.
2506 unlink(b_path.c_str());
2507 return false;
2508 }
2509 }
2510
2511 // Rename B to A.
2512 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2513 // Delete the b_path so we don't try again (or fail earlier).
2514 if (unlink(b_path.c_str()) != 0) {
2515 PLOG(ERROR) << "Could not unlink " << b_path;
2516 }
2517
2518 return false;
2519 }
2520
2521 return true;
2522}
2523
2524bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2525 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002526 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2527 if (slot_suffix.empty()) {
2528 return false;
2529 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002530
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002531 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2532 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2533 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002534 }
2535
2536 // Validate other inputs.
2537 if (validate_apk_path(apk_path) != 0) {
2538 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2539 return false;
2540 }
2541 if (validate_apk_path(oat_dir) != 0) {
2542 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2543 return false;
2544 }
2545
2546 char a_path[PKG_PATH_MAX];
2547 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2548 return false;
2549 }
2550 const std::string a_vdex_path = create_vdex_filename(a_path);
2551 const std::string a_image_path = create_image_filename(a_path);
2552
2553 // B path = A path + slot suffix.
2554 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2555 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2556 const std::string b_image_path = StringPrintf("%s.%s",
2557 a_image_path.c_str(),
2558 slot_suffix.c_str());
2559
2560 bool success = true;
2561 if (move_ab_path(b_path, a_path)) {
2562 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2563 // Note: we can live without an app image. As such, ignore failure to move the image file.
2564 // If we decide to require the app image, or the app image being moved correctly,
2565 // then change accordingly.
2566 constexpr bool kIgnoreAppImageFailure = true;
2567
2568 if (!a_image_path.empty()) {
2569 if (!move_ab_path(b_image_path, a_image_path)) {
2570 unlink(a_image_path.c_str());
2571 if (!kIgnoreAppImageFailure) {
2572 success = false;
2573 }
2574 }
2575 }
2576 } else {
2577 // Cleanup: delete B image, ignore errors.
2578 unlink(b_image_path.c_str());
2579 success = false;
2580 }
2581 } else {
2582 // Cleanup: delete B image, ignore errors.
2583 unlink(b_vdex_path.c_str());
2584 unlink(b_image_path.c_str());
2585 success = false;
2586 }
2587 return success;
2588}
2589
2590bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2591 // Delete the oat/odex file.
2592 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002593 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002594 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002595 return false;
2596 }
2597
2598 // In case of a permission failure report the issue. Otherwise just print a warning.
2599 auto unlink_and_check = [](const char* path) -> bool {
2600 int result = unlink(path);
2601 if (result != 0) {
2602 if (errno == EACCES || errno == EPERM) {
2603 PLOG(ERROR) << "Could not unlink " << path;
2604 return false;
2605 }
2606 PLOG(WARNING) << "Could not unlink " << path;
2607 }
2608 return true;
2609 };
2610
2611 // Delete the oat/odex file.
2612 bool return_value_oat = unlink_and_check(out_path);
2613
2614 // Derive and delete the app image.
2615 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2616
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002617 // Derive and delete the vdex file.
2618 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2619
Jeff Sharkey90aff262016-12-12 14:28:24 -07002620 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002621 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002622}
2623
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002624static bool is_absolute_path(const std::string& path) {
2625 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2626 LOG(ERROR) << "Invalid absolute path " << path;
2627 return false;
2628 } else {
2629 return true;
2630 }
2631}
2632
2633static bool is_valid_instruction_set(const std::string& instruction_set) {
2634 // TODO: add explicit whitelisting of instruction sets
2635 if (instruction_set.find('/') != std::string::npos) {
2636 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2637 return false;
2638 } else {
2639 return true;
2640 }
2641}
2642
2643bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2644 const char *apk_path, const char *instruction_set) {
2645 std::string oat_dir_ = oat_dir;
2646 std::string apk_path_ = apk_path;
2647 std::string instruction_set_ = instruction_set;
2648
2649 if (!is_absolute_path(oat_dir_)) return false;
2650 if (!is_absolute_path(apk_path_)) return false;
2651 if (!is_valid_instruction_set(instruction_set_)) return false;
2652
2653 std::string::size_type end = apk_path_.rfind('.');
2654 std::string::size_type start = apk_path_.rfind('/', end);
2655 if (end == std::string::npos || start == std::string::npos) {
2656 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2657 return false;
2658 }
2659
2660 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2661 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2662 const char* res = res_.c_str();
2663 if (strlen(res) >= PKG_PATH_MAX) {
2664 LOG(ERROR) << "Result too large";
2665 return false;
2666 } else {
2667 strlcpy(path, res, PKG_PATH_MAX);
2668 return true;
2669 }
2670}
2671
2672bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2673 const char *instruction_set) {
2674 std::string apk_path_ = apk_path;
2675 std::string instruction_set_ = instruction_set;
2676
2677 if (!is_absolute_path(apk_path_)) return false;
2678 if (!is_valid_instruction_set(instruction_set_)) return false;
2679
2680 std::string::size_type end = apk_path_.rfind('.');
2681 std::string::size_type start = apk_path_.rfind('/', end);
2682 if (end == std::string::npos || start == std::string::npos) {
2683 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2684 return false;
2685 }
2686
2687 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2688 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2689}
2690
2691bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2692 const char *instruction_set) {
2693 std::string src_ = src;
2694 std::string instruction_set_ = instruction_set;
2695
2696 if (!is_absolute_path(src_)) return false;
2697 if (!is_valid_instruction_set(instruction_set_)) return false;
2698
2699 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2700 if (*it == '/') {
2701 *it = '@';
2702 }
2703 }
2704
2705 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2706 + DALVIK_CACHE_POSTFIX;
2707 const char* res = res_.c_str();
2708 if (strlen(res) >= PKG_PATH_MAX) {
2709 LOG(ERROR) << "Result too large";
2710 return false;
2711 } else {
2712 strlcpy(path, res, PKG_PATH_MAX);
2713 return true;
2714 }
2715}
2716
Calin Juravle59f7ab82018-04-27 17:50:23 -07002717bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2718 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002719 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2720 for (const std::string& elem : classpaths_elems) {
2721 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2722 if (fd < 0) {
2723 PLOG(ERROR) << "Could not open classpath elem " << elem;
2724 return false;
2725 } else {
2726 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002727 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002728 }
2729 }
2730 return true;
2731}
2732
2733static bool create_app_profile_snapshot(int32_t app_id,
2734 const std::string& package_name,
2735 const std::string& profile_name,
2736 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002737 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2738
Calin Juravle824a64d2018-01-18 20:23:17 -08002739 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002740 if (snapshot_fd < 0) {
2741 return false;
2742 }
2743
2744 std::vector<unique_fd> profiles_fd;
2745 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002746 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2747 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002748 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2749 return false;
2750 }
2751
2752 profiles_fd.push_back(std::move(reference_profile_fd));
2753
Calin Juravle0d0a4922018-01-23 19:54:11 -08002754 // Open the class paths elements. These will be used to filter out profile data that does
2755 // not belong to the classpath during merge.
2756 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002757 std::vector<std::string> dex_locations;
2758 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002759 return false;
2760 }
2761
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002762 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002763 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002764 pid_t pid = fork();
2765 if (pid == 0) {
2766 /* child -- drop privileges before continuing */
2767 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002768 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002769 }
2770
2771 /* parent */
2772 int return_code = wait_child(pid);
2773 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002774 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002775 return false;
2776 }
2777
Calin Juravle78728f32019-11-08 17:55:46 -08002778 // Verify that profman finished successfully.
2779 int profman_code = WEXITSTATUS(return_code);
2780 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2781 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2782 << ":" << profman_code;
2783 return false;
2784 }
Calin Juravle29591732017-11-20 17:46:19 -08002785 return true;
2786}
2787
Calin Juravle0d0a4922018-01-23 19:54:11 -08002788static bool create_boot_image_profile_snapshot(const std::string& package_name,
2789 const std::string& profile_name,
2790 const std::string& classpath) {
2791 // The reference profile directory for the android package might not be prepared. Do it now.
2792 const std::string ref_profile_dir =
2793 create_primary_reference_profile_package_dir_path(package_name);
2794 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2795 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2796 return false;
2797 }
2798
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002799 // Return false for empty class path since it may otherwise return true below if profiles is
2800 // empty.
2801 if (classpath.empty()) {
2802 PLOG(ERROR) << "Class path is empty";
2803 return false;
2804 }
2805
Calin Juravle0d0a4922018-01-23 19:54:11 -08002806 // Open and create the snapshot profile.
2807 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2808
2809 // Collect all non empty profiles.
2810 // The collection will traverse all applications profiles and find the non empty files.
2811 // This has the potential of inspecting a large number of files and directories (depending
2812 // on the number of applications and users). So there is a slight increase in the chance
2813 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2814 // fail the snapshot and aggregate whatever profile we could open.
2815 //
2816 // The profile snapshot is a best effort based on available data it's ok if some data
2817 // from some apps is missing. It will be counter productive for the snapshot to fail
2818 // because we could not open or read some of the files.
2819 std::vector<std::string> profiles;
2820 if (!collect_profiles(&profiles)) {
2821 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2822 }
2823
2824 // If we have no profiles return early.
2825 if (profiles.empty()) {
2826 return true;
2827 }
2828
2829 // Open the classpath elements. These will be used to filter out profile data that does
2830 // not belong to the classpath during merge.
2831 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002832 std::vector<std::string> dex_locations;
2833 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002834 return false;
2835 }
2836
2837 // If we could not open any files from the classpath return an error.
2838 if (apk_fds.empty()) {
2839 LOG(ERROR) << "Could not open any of the classpath elements.";
2840 return false;
2841 }
2842
2843 // Aggregate the profiles in batches of kAggregationBatchSize.
2844 // We do this to avoid opening a huge a amount of files.
2845 static constexpr size_t kAggregationBatchSize = 10;
2846
Calin Juravle0d0a4922018-01-23 19:54:11 -08002847 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002848 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002849 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2850 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2851 if (fd.get() >= 0) {
2852 profiles_fd.push_back(std::move(fd));
2853 }
2854 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002855
2856 // We aggregate (read & write) into the same fd multiple times in a row.
2857 // We need to reset the cursor every time to ensure we read the whole file every time.
2858 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2859 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2860 return false;
2861 }
2862
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002863 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002864 args.SetupMerge(profiles_fd,
2865 snapshot_fd,
2866 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002867 dex_locations,
2868 /*for_snapshot=*/true,
2869 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002870 pid_t pid = fork();
2871 if (pid == 0) {
2872 /* child -- drop privileges before continuing */
2873 drop_capabilities(AID_SYSTEM);
2874
Calin Juravle59f7ab82018-04-27 17:50:23 -07002875 // The introduction of new access flags into boot jars causes them to
2876 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002877 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002878 }
2879
2880 /* parent */
2881 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002882
Calin Juravle0d0a4922018-01-23 19:54:11 -08002883 if (!WIFEXITED(return_code)) {
2884 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2885 return false;
2886 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002887
2888 // Verify that profman finished successfully.
2889 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002890 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2891 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2892 << ":" << profman_code;
2893 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002894 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002895 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002896
Calin Juravle0d0a4922018-01-23 19:54:11 -08002897 return true;
2898}
2899
2900bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2901 const std::string& profile_name, const std::string& classpath) {
2902 if (app_id == -1) {
2903 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2904 } else {
2905 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2906 }
2907}
2908
Calin Juravlec3b049e2018-01-18 22:32:58 -08002909bool prepare_app_profile(const std::string& package_name,
2910 userid_t user_id,
2911 appid_t app_id,
2912 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002913 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002914 const std::unique_ptr<std::string>& dex_metadata) {
2915 // Prepare the current profile.
2916 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2917 /*is_secondary_dex*/ false);
2918 uid_t uid = multiuser_get_uid(user_id, app_id);
2919 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2920 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2921 return false;
2922 }
2923
2924 // Check if we need to install the profile from the dex metadata.
2925 if (dex_metadata == nullptr) {
2926 return true;
2927 }
2928
2929 // We have a dex metdata. Merge the profile into the reference profile.
2930 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2931 /*read_write*/ true, /*is_secondary_dex*/ false);
2932 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2933 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002934 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2935 if (apk_fd < 0) {
2936 PLOG(ERROR) << "Could not open code path " << code_path;
2937 return false;
2938 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002939
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002940 RunProfman args;
2941 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2942 std::move(ref_profile_fd),
2943 std::move(apk_fd),
2944 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002945 pid_t pid = fork();
2946 if (pid == 0) {
2947 /* child -- drop privileges before continuing */
2948 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2949 drop_capabilities(app_shared_gid);
2950
Calin Juravlef63d4792018-01-30 17:43:34 +00002951 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002952 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002953 }
2954
2955 /* parent */
2956 int return_code = wait_child(pid);
2957 if (!WIFEXITED(return_code)) {
2958 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2959 return false;
2960 }
2961 return true;
2962}
2963
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002964} // namespace installd
2965} // namespace android