blob: 8cba7e413efd73d423de78a15861fd932938fda5 [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 Chartiercc66c442018-11-09 15:57:21 -0800306class RunDex2Oat : public ExecVHelper {
307 public:
308 RunDex2Oat(int zip_fd,
309 int oat_fd,
310 int input_vdex_fd,
311 int output_vdex_fd,
312 int image_fd,
313 const char* input_file_name,
314 const char* output_file_name,
315 int swap_fd,
316 const char* instruction_set,
317 const char* compiler_filter,
318 bool debuggable,
319 bool post_bootcomplete,
320 bool background_job_compile,
321 int profile_fd,
322 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000323 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800324 int target_sdk_version,
325 bool enable_hidden_api_checks,
326 bool generate_compact_dex,
327 int dex_metadata_fd,
328 const char* compilation_reason) {
329 // Get the relative path to the input file.
330 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700331
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800332 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
333 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700334
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800335 const char* threads_property = post_bootcomplete
336 ? "dalvik.vm.dex2oat-threads"
337 : "dalvik.vm.boot-dex2oat-threads";
338 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700339
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000340 std::string bootclasspath;
341 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
342 if (dex2oat_bootclasspath != nullptr) {
343 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
344 }
345 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
346 // BOOTCLASSPATH.
347
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800348 const std::string dex2oat_isa_features_key =
349 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
350 std::string instruction_set_features_arg =
351 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700352
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800353 const std::string dex2oat_isa_variant_key =
354 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
355 std::string instruction_set_variant_arg =
356 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700357
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800358 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700359
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800360 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
361 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
362 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700363
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800364 // If we are booting without the real /data, don't spend time compiling.
365 std::string vold_decrypt = GetProperty("vold.decrypt", "");
366 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
367 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700368
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800369 std::string resolve_startup_string_arg =
370 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
371 "--resolve-startup-const-strings=%s");
372 if (resolve_startup_string_arg.empty()) {
373 // If empty, fall back to system property.
374 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800375 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
376 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800377 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800378
379 const std::string image_block_size_arg =
380 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
381 "--max-image-block-size=%s");
382
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800383 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700384
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800385 std::string image_format_arg;
386 if (image_fd >= 0) {
387 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000388 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000389
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800390 std::string dex2oat_large_app_threshold_arg =
391 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000392
Calin Juravlef74a7372019-02-28 20:29:41 -0800393
394 const char* dex2oat_bin = select_execution_binary(
395 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000396
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800397 bool generate_minidebug_info = kEnableMinidebugInfo &&
398 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000399
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000400 std::string boot_image;
401 std::string use_apex_image =
402 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
403 ENABLE_APEX_IMAGE,
404 /*default_value=*/ "");
405 if (use_apex_image == "true") {
406 boot_image = StringPrintf("-Ximage:%s", kApexImage);
407 } else {
408 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
409 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000410
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800411 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
412 // use arraysize instead.
413 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
414 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
415 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
416 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
417 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
418 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
419 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
420 std::string dex2oat_compiler_filter_arg;
421 std::string dex2oat_swap_fd;
422 std::string dex2oat_image_fd;
423 std::string target_sdk_version_arg;
424 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000425 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800426 }
427 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000428 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800429 if (class_loader_context != nullptr) {
430 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
431 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000432 if (!class_loader_context_fds.empty()) {
433 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
434 class_loader_context_fds.c_str());
435 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800436 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000437
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800438 if (swap_fd >= 0) {
439 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
440 }
441 if (image_fd >= 0) {
442 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
443 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000444
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800445 // Compute compiler filter.
446 bool have_dex2oat_relocation_skip_flag = false;
447 if (skip_compilation) {
448 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
449 have_dex2oat_relocation_skip_flag = true;
450 } else if (compiler_filter != nullptr) {
451 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
452 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000453
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800454 if (dex2oat_compiler_filter_arg.empty()) {
455 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
456 "--compiler-filter=%s");
457 }
458
459 // Check whether all apps should be compiled debuggable.
460 if (!debuggable) {
461 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
462 }
463 std::string profile_arg;
464 if (profile_fd != -1) {
465 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
466 }
467
468 // Get the directory of the apk to pass as a base classpath directory.
469 std::string base_dir;
470 std::string apk_dir(input_file_name);
471 unsigned long dir_index = apk_dir.rfind('/');
472 bool has_base_dir = dir_index != std::string::npos;
473 if (has_base_dir) {
474 apk_dir = apk_dir.substr(0, dir_index);
475 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
476 }
477
478 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
479
480 std::string compilation_reason_arg = compilation_reason == nullptr
481 ? ""
482 : std::string("--compilation-reason=") + compilation_reason;
483
484 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
485
486 // Disable cdex if update input vdex is true since this combination of options is not
487 // supported.
488 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
489
490 AddArg(zip_fd_arg);
491 AddArg(zip_location_arg);
492 AddArg(input_vdex_fd_arg);
493 AddArg(output_vdex_fd_arg);
494 AddArg(oat_fd_arg);
495 AddArg(oat_location_arg);
496 AddArg(instruction_set_arg);
497
498 AddArg(instruction_set_variant_arg);
499 AddArg(instruction_set_features_arg);
500
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000501 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000502 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800503 AddRuntimeArg(dex2oat_Xms_arg);
504 AddRuntimeArg(dex2oat_Xmx_arg);
505
506 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800507 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800508 AddArg(dex2oat_compiler_filter_arg);
509 AddArg(dex2oat_threads_arg);
510 AddArg(dex2oat_swap_fd);
511 AddArg(dex2oat_image_fd);
512
513 if (generate_debug_info) {
514 AddArg("--generate-debug-info");
515 }
516 if (debuggable) {
517 AddArg("--debuggable");
518 }
519 AddArg(image_format_arg);
520 AddArg(dex2oat_large_app_threshold_arg);
521
522 if (have_dex2oat_relocation_skip_flag) {
523 AddRuntimeArg(dex2oat_norelocation);
524 }
525 AddArg(profile_arg);
526 AddArg(base_dir);
527 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000528 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800529 if (generate_minidebug_info) {
530 AddArg(kMinidebugDex2oatFlag);
531 }
532 if (disable_cdex) {
533 AddArg(kDisableCompactDexFlag);
534 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000535 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800536 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100537 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800538 }
539
540 if (dex_metadata_fd > -1) {
541 AddArg(dex_metadata_fd_arg);
542 }
543
544 AddArg(compilation_reason_arg);
545
546 // Do not add args after dex2oat_flags, they should override others for debugging.
547 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
548
549 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000550 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800551};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552
553/*
554 * Whether dexopt should use a swap file when compiling an APK.
555 *
556 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
557 * itself, anyways).
558 *
559 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
560 *
561 * Otherwise, return true if this is a low-mem device.
562 *
563 * Otherwise, return default value.
564 */
565static bool kAlwaysProvideSwapFile = false;
566static bool kDefaultProvideSwapFile = true;
567
568static bool ShouldUseSwapFileForDexopt() {
569 if (kAlwaysProvideSwapFile) {
570 return true;
571 }
572
573 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700574 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
575 if (!dex2oat_prop_buf.empty()) {
576 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700577 }
578
579 // Shortcut for default value. This is an implementation optimization for the process sketched
580 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
581 // as low-mem is never returning false. The compiler will optimize this away if it can.
582 if (kDefaultProvideSwapFile) {
583 return true;
584 }
585
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700586 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700587 return true;
588 }
589
590 // Default value must be false here.
591 return kDefaultProvideSwapFile;
592}
593
Richard Uhler76cc0272016-12-08 10:46:35 +0000594static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700595 if (set_to_bg) {
596 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800597 PLOG(ERROR) << "set_sched_policy failed";
598 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700599 }
600 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800601 PLOG(ERROR) << "setpriority failed";
602 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700603 }
604 }
605}
606
Calin Juravle29591732017-11-20 17:46:19 -0800607static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
608 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800609 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800610 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800611 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800612 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800613 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 }
Calin Juravle114f0812017-03-08 19:05:07 -0800615 // Profiles should belong to the app; make sure of that by giving ownership to
616 // the app uid. If we cannot do that, there's no point in returning the fd
617 // since dex2oat/profman will fail with SElinux denials.
618 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000619 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800620 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800621 }
Calin Juravle29591732017-11-20 17:46:19 -0800622 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800623}
624
Calin Juravle29591732017-11-20 17:46:19 -0800625static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800626 // Do not follow symlinks when opening a profile:
627 // - primary profiles should not contain symlinks in their paths
628 // - secondary dex paths should have been already resolved and validated
629 flags |= O_NOFOLLOW;
630
Calin Juravle29591732017-11-20 17:46:19 -0800631 // Check if we need to create the profile
632 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
633 unique_fd fd;
634 if ((flags & O_CREAT) != 0) {
635 fd = create_profile(uid, profile, flags);
636 } else {
637 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
638 }
639
Calin Juravle114f0812017-03-08 19:05:07 -0800640 if (fd.get() < 0) {
641 if (errno != ENOENT) {
642 // Profiles might be missing for various reasons. For example, in a
643 // multi-user environment, the profile directory for one user can be created
644 // after we start a merge. In this case the current profile for that user
645 // will not be found.
646 // Also, the secondary dex profiles might be deleted by the app at any time,
647 // so we can't we need to prepare if they are missing.
648 PLOG(ERROR) << "Failed to open profile " << profile;
649 }
650 return invalid_unique_fd();
651 }
652
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 return fd;
654}
655
Calin Juravle824a64d2018-01-18 20:23:17 -0800656static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
657 const std::string& location, bool is_secondary_dex) {
658 std::string profile = create_current_profile_path(user, package_name, location,
659 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800660 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800661}
662
Calin Juravle824a64d2018-01-18 20:23:17 -0800663static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
664 const std::string& location, bool read_write, bool is_secondary_dex) {
665 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800666 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
667}
668
669static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800670 const std::string& location) {
671 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800672 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800673}
674
Calin Juravle824a64d2018-01-18 20:23:17 -0800675static void open_profile_files(uid_t uid, const std::string& package_name,
676 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800677 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700678 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800679 *reference_profile_fd = open_reference_profile(uid, package_name, location,
680 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700681
Calin Juravle114f0812017-03-08 19:05:07 -0800682 // For secondary dex files, we don't really need the user but we use it for sanity checks.
683 // Note: the user owning the dex file should be the current user.
684 std::vector<userid_t> users;
685 if (is_secondary_dex){
686 users.push_back(multiuser_get_user_id(uid));
687 } else {
688 users = get_known_users(/*volume_uuid*/ nullptr);
689 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800691 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
692 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700693 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800694 if (profile_fd.get() >= 0) {
695 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700696 }
697 }
698}
699
Jeff Sharkey90aff262016-12-12 14:28:24 -0700700static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
701static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
702static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
703static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
704static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
705
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800706class RunProfman : public ExecVHelper {
707 public:
708 void SetupArgs(const std::vector<unique_fd>& profile_fds,
709 const unique_fd& reference_profile_fd,
710 const std::vector<unique_fd>& apk_fds,
711 const std::vector<std::string>& dex_locations,
Calin Juravle9d250172019-09-27 13:22:41 -0700712 bool copy_and_update) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800713
714 // TODO(calin): Assume for now we run in the bg compile job (which is in
715 // most of the invocation). With the current data flow, is not very easy or
716 // clean to discover this in RunProfman (it will require quite a messy refactoring).
717 const char* profman_bin = select_execution_binary(
718 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700719
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800720 if (copy_and_update) {
721 CHECK_EQ(1u, profile_fds.size());
722 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000723 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800724 if (reference_profile_fd != -1) {
725 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000726 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800727
728 for (const unique_fd& fd : profile_fds) {
729 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
730 }
731
732 for (const unique_fd& fd : apk_fds) {
733 AddArg("--apk-fd=" + std::to_string(fd.get()));
734 }
735
736 for (const std::string& dex_location : dex_locations) {
737 AddArg("--dex-location=" + dex_location);
738 }
739
740 if (copy_and_update) {
741 AddArg("--copy-and-update-profile-key");
742 }
743
744 // Do not add after dex2oat_flags, they should override others for debugging.
745 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800746 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800748 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
749 const unique_fd& reference_profile_fd,
750 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle9d250172019-09-27 13:22:41 -0700751 const std::vector<std::string>& dex_locations = std::vector<std::string>()) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800752 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800753 reference_profile_fd,
754 apk_fds,
755 dex_locations,
Calin Juravle9d250172019-09-27 13:22:41 -0700756 /*copy_and_update=*/false);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800757 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700758
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800759 void SetupCopyAndUpdate(unique_fd&& profile_fd,
760 unique_fd&& reference_profile_fd,
761 unique_fd&& apk_fd,
762 const std::string& dex_location) {
763 // The fds need to stay open longer than the scope of the function, so put them into a local
764 // variable vector.
765 profiles_fd_.push_back(std::move(profile_fd));
766 apk_fds_.push_back(std::move(apk_fd));
767 reference_profile_fd_ = std::move(reference_profile_fd);
768 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800769 SetupArgs(profiles_fd_,
770 reference_profile_fd_,
771 apk_fds_,
772 dex_locations,
Calin Juravle9d250172019-09-27 13:22:41 -0700773 /*copy_and_update=*/true);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800774 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000775
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800776 void SetupDump(const std::vector<unique_fd>& profiles_fd,
777 const unique_fd& reference_profile_fd,
778 const std::vector<std::string>& dex_locations,
779 const std::vector<unique_fd>& apk_fds,
780 const unique_fd& output_fd) {
781 AddArg("--dump-only");
782 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800783 SetupArgs(profiles_fd,
784 reference_profile_fd,
785 apk_fds,
786 dex_locations,
Calin Juravle9d250172019-09-27 13:22:41 -0700787 /*copy_and_update=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800788 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000789
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800790 void Exec() {
791 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
792 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000793
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800794 private:
795 unique_fd reference_profile_fd_;
796 std::vector<unique_fd> profiles_fd_;
797 std::vector<unique_fd> apk_fds_;
798};
Mathieu Chartier31636522018-11-09 23:53:07 +0000799
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800800
Calin Juravlef63d4792018-01-30 17:43:34 +0000801
Jeff Sharkey90aff262016-12-12 14:28:24 -0700802// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800803// The location is the package name for primary apks or the dex path for secondary dex files.
804// Returns true if there is enough information in the current profiles that makes it
805// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806// If the return value is true all the current profiles would have been merged into
807// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800808static bool analyze_profiles(uid_t uid, const std::string& package_name,
809 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800810 std::vector<unique_fd> profiles_fd;
811 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800812 open_profile_files(uid, package_name, location, is_secondary_dex,
813 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800814 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700815 // Skip profile guided compilation because no profiles were found.
816 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 return false;
818 }
819
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800820 RunProfman profman_merge;
821 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700822 pid_t pid = fork();
823 if (pid == 0) {
824 /* child -- drop privileges before continuing */
825 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800826 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827 }
828 /* parent */
829 int return_code = wait_child(pid);
830 bool need_to_compile = false;
831 bool should_clear_current_profiles = false;
832 bool should_clear_reference_profile = false;
833 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800834 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700835 } else {
836 return_code = WEXITSTATUS(return_code);
837 switch (return_code) {
838 case PROFMAN_BIN_RETURN_CODE_COMPILE:
839 need_to_compile = true;
840 should_clear_current_profiles = true;
841 should_clear_reference_profile = false;
842 break;
843 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
844 need_to_compile = false;
845 should_clear_current_profiles = false;
846 should_clear_reference_profile = false;
847 break;
848 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800849 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 need_to_compile = false;
851 should_clear_current_profiles = true;
852 should_clear_reference_profile = true;
853 break;
854 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
855 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
856 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800857 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700858 need_to_compile = false;
859 should_clear_current_profiles = false;
860 should_clear_reference_profile = false;
861 break;
862 default:
863 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800864 LOG(WARNING) << "Unknown error code while processing profiles for location "
865 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700866 need_to_compile = false;
867 should_clear_current_profiles = true;
868 should_clear_reference_profile = true;
869 break;
870 }
871 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800872
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800874 if (is_secondary_dex) {
875 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800876 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
877 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800878 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800879 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800880 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700881 }
882 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800883 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 }
885 return need_to_compile;
886}
887
Calin Juravle114f0812017-03-08 19:05:07 -0800888// Decides if profile guided compilation is needed or not based on existing profiles.
889// The analysis is done for the primary apks of the given package.
890// Returns true if there is enough information in the current profiles that makes it
891// worth to recompile the package.
892// If the return value is true all the current profiles would have been merged into
893// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800894bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
895 const std::string& profile_name) {
896 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800897}
898
Calin Juravle408cd4a2018-01-20 23:34:18 -0800899bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
900 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800901 std::vector<unique_fd> profile_fds;
902 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800903 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
904 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700905
Calin Juravle408cd4a2018-01-20 23:34:18 -0800906 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800907 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700908
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800909 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910 const bool has_profiles = !profile_fds.empty();
911
912 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800913 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700914 return false;
915 }
916
Calin Juravle114f0812017-03-08 19:05:07 -0800917 unique_fd output_fd(open(out_file_name.c_str(),
918 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700919 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800920 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700921 return false;
922 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800923
Jeff Sharkey90aff262016-12-12 14:28:24 -0700924 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800925 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800926 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
927 if (apk_fd == -1) {
928 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
929 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700930 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800931 dex_locations.push_back(get_location_from_path(code_path.c_str()));
932 apk_fds.push_back(std::move(apk_fd));
933
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800935 RunProfman profman_dump;
936 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937 pid_t pid = fork();
938 if (pid == 0) {
939 /* child -- drop privileges before continuing */
940 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800941 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700942 }
943 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700944 int return_code = wait_child(pid);
945 if (!WIFEXITED(return_code)) {
946 LOG(WARNING) << "profman failed for package " << pkgname << ": "
947 << return_code;
948 return false;
949 }
950 return true;
951}
952
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700953bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800954 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700955 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
956 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800957 package_name,
958 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700959 /*read_write*/ true,
960 /*secondary*/ false));
961 if (in_fd.get() < 0) {
962 PLOG(WARNING) << "Could not open profile " << system_profile;
963 return false;
964 }
965 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800966 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700967 return false;
968 }
969
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700970 // As a security measure we want to write the profile information with the reduced capabilities
971 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700972 pid_t pid = fork();
973 if (pid == 0) {
974 /* child -- drop privileges before continuing */
975 drop_capabilities(packageUid);
976
977 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
978 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800979 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700980 }
981 // This implies that the app owning this profile is running
982 // (and has acquired the lock).
983 //
984 // The app never acquires the lock for the reference profiles of primary apks.
985 // Only dex2oat from installd will do that. Since installd is single threaded
986 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800987 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700988 return false;
989 }
990
991 bool truncated = ftruncate(out_fd.get(), 0) == 0;
992 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800993 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700994 }
995
996 // Copy over data.
997 static constexpr size_t kBufferSize = 4 * 1024;
998 char buffer[kBufferSize];
999 while (true) {
1000 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1001 if (bytes == 0) {
1002 break;
1003 }
1004 write(out_fd.get(), buffer, bytes);
1005 }
1006 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001007 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001008 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001009 // Use _exit since we don't want to run the global destructors in the child.
1010 // b/62597429
1011 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001012 }
1013 /* parent */
1014 int return_code = wait_child(pid);
1015 return return_code == 0;
1016}
1017
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1019 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1020 if (EndsWith(oat_path, ".dex")) {
1021 std::string new_path = oat_path;
1022 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001023 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001024 return new_path;
1025 }
1026
1027 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1028 // case (where the base name will have an extension for the B artifact).
1029 size_t odex_pos = oat_path.rfind(".odex");
1030 if (odex_pos != std::string::npos) {
1031 std::string new_path = oat_path;
1032 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1033 CHECK_NE(new_path.find(new_ext), std::string::npos);
1034 return new_path;
1035 }
1036
1037 // Don't know how to handle this.
1038 return "";
1039}
1040
1041// Translate the given oat path to an art (app image) path. An empty string
1042// denotes an error.
1043static std::string create_image_filename(const std::string& oat_path) {
1044 return replace_file_extension(oat_path, ".art");
1045}
1046
1047// Translate the given oat path to a vdex path. An empty string denotes an error.
1048static std::string create_vdex_filename(const std::string& oat_path) {
1049 return replace_file_extension(oat_path, ".vdex");
1050}
1051
Jeff Sharkey90aff262016-12-12 14:28:24 -07001052static int open_output_file(const char* file_name, bool recreate, int permissions) {
1053 int flags = O_RDWR | O_CREAT;
1054 if (recreate) {
1055 if (unlink(file_name) < 0) {
1056 if (errno != ENOENT) {
1057 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1058 }
1059 }
1060 flags |= O_EXCL;
1061 }
1062 return open(file_name, flags, permissions);
1063}
1064
Calin Juravle2289c0a2017-02-15 12:44:14 -08001065static bool set_permissions_and_ownership(
1066 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1067 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1068 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001069 if (fchmod(fd,
1070 S_IRUSR|S_IWUSR|S_IRGRP |
1071 (is_public ? S_IROTH : 0)) < 0) {
1072 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1073 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001074 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001075 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1076 return false;
1077 }
1078 return true;
1079}
1080
1081static bool IsOutputDalvikCache(const char* oat_dir) {
1082 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1083 // into '!'. Play it safe by handling it both.
1084 // TODO: ensure we never get null.
1085 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1086 return oat_dir == nullptr || oat_dir[0] == '!';
1087}
1088
Calin Juravled23dee72017-07-06 16:29:11 -07001089// Best-effort check whether we can fit the the path into our buffers.
1090// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1091// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1092// extension to the cache path (5 bytes).
1093// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1094static bool validate_dex_path_size(const std::string& dex_path) {
1095 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1096 LOG(ERROR) << "dex_path too long: " << dex_path;
1097 return false;
1098 }
1099 return true;
1100}
1101
Jeff Sharkey90aff262016-12-12 14:28:24 -07001102static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001103 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001104 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001105 return false;
1106 }
1107
1108 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001109 // Oat dirs for secondary dex files are already validated.
1110 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001111 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1112 return false;
1113 }
1114 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1115 return false;
1116 }
1117 } else {
1118 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1119 return false;
1120 }
1121 }
1122 return true;
1123}
1124
1125// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1126// on destruction. It will also run the given cleanup (unless told not to) after closing.
1127//
1128// Usage example:
1129//
Calin Juravle7a570e82017-01-14 16:23:30 -08001130// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131// [name]() {
1132// unlink(name.c_str());
1133// });
1134// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1135// wrapper if captured as a reference.
1136//
1137// if (file.get() == -1) {
1138// // Error opening...
1139// }
1140//
1141// ...
1142// if (error) {
1143// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1144// // and delete the file (after the fd is closed).
1145// return -1;
1146// }
1147//
1148// (Success case)
1149// file.SetCleanup(false);
1150// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1151// // (leaving the file around; after the fd is closed).
1152//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001153class Dex2oatFileWrapper {
1154 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001155 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001156 }
1157
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1159 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1160
1161 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1162 value_ = other.value_;
1163 cleanup_ = other.cleanup_;
1164 do_cleanup_ = other.do_cleanup_;
1165 auto_close_ = other.auto_close_;
1166 other.release();
1167 }
1168
1169 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1170 value_ = other.value_;
1171 cleanup_ = other.cleanup_;
1172 do_cleanup_ = other.do_cleanup_;
1173 auto_close_ = other.auto_close_;
1174 other.release();
1175 return *this;
1176 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177
1178 ~Dex2oatFileWrapper() {
1179 reset(-1);
1180 }
1181
1182 int get() {
1183 return value_;
1184 }
1185
1186 void SetCleanup(bool cleanup) {
1187 do_cleanup_ = cleanup;
1188 }
1189
1190 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001191 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001192 close(value_);
1193 }
1194 if (do_cleanup_ && cleanup_ != nullptr) {
1195 cleanup_();
1196 }
1197
1198 value_ = new_value;
1199 }
1200
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 void reset(int new_value, std::function<void ()> new_cleanup) {
1202 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001203 close(value_);
1204 }
1205 if (do_cleanup_ && cleanup_ != nullptr) {
1206 cleanup_();
1207 }
1208
1209 value_ = new_value;
1210 cleanup_ = new_cleanup;
1211 }
1212
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 void DisableAutoClose() {
1214 auto_close_ = false;
1215 }
1216
Jeff Sharkey90aff262016-12-12 14:28:24 -07001217 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001218 void release() {
1219 value_ = -1;
1220 do_cleanup_ = false;
1221 cleanup_ = nullptr;
1222 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001223 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001224 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001225 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001226 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001227};
1228
Calin Juravle7a570e82017-01-14 16:23:30 -08001229// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001230Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1231 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001232
1233 // We don't create an image for secondary dex files.
1234 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001235 return Dex2oatFileWrapper();
1236 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001237
Calin Juravle7a570e82017-01-14 16:23:30 -08001238 const std::string image_path = create_image_filename(out_oat_path);
1239 if (image_path.empty()) {
1240 // Happens when the out_oat_path has an unknown extension.
1241 return Dex2oatFileWrapper();
1242 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001243
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001244 // In case there is a stale image, remove it now. Ignore any error.
1245 unlink(image_path.c_str());
1246
1247 // Not enabled, exit.
1248 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001249 return Dex2oatFileWrapper();
1250 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001251 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1252 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001253 return Dex2oatFileWrapper();
1254 }
1255 // Recreate is true since we do not want to modify a mapped image. If the app is
1256 // already running and we modify the image file, it can cause crashes (b/27493510).
1257 Dex2oatFileWrapper wrapper_fd(
1258 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1259 [image_path]() { unlink(image_path.c_str()); });
1260 if (wrapper_fd.get() < 0) {
1261 // Could not create application image file. Go on since we can compile without it.
1262 LOG(ERROR) << "installd could not create '" << image_path
1263 << "' for image file during dexopt";
1264 // If we have a valid image file path but no image fd, explicitly erase the image file.
1265 if (unlink(image_path.c_str()) < 0) {
1266 if (errno != ENOENT) {
1267 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1268 }
1269 }
1270 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001271 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001272 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1273 wrapper_fd.reset(-1);
1274 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001275
Calin Juravle7a570e82017-01-14 16:23:30 -08001276 return wrapper_fd;
1277}
1278
1279// Creates the dexopt swap file if necessary and return its fd.
1280// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001281unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001282 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001283 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001284 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001285 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001286 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001287 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001288 if (swap_fd.get() < 0) {
1289 // Could not create swap file. Optimistically go on and hope that we can compile
1290 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001291 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001292 } else {
1293 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001294 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001295 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1296 }
1297 }
1298 return swap_fd;
1299}
1300
1301// Opens the reference profiles if needed.
1302// 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 -08001303Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001304 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001305 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001306 // If we are not profile guided compilation, or we are compiling system server
1307 // do not bother to open the profiles; we won't be using them.
1308 if (!profile_guided || (pkgname[0] == '*')) {
1309 return Dex2oatFileWrapper();
1310 }
1311
1312 // If this is a secondary dex path which is public do not open the profile.
1313 // We cannot compile public secondary dex paths with profiles. That's because
1314 // it will expose how the dex files are used by their owner.
1315 //
1316 // Note that the PackageManager is responsible to set the is_public flag for
1317 // primary apks and we do not check it here. In some cases, e.g. when
1318 // compiling with a public profile from the .dm file the PackageManager will
1319 // set is_public toghether with the profile guided compilation.
1320 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001321 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001322 }
Calin Juravle114f0812017-03-08 19:05:07 -08001323
1324 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001325 std::string location;
1326 if (is_secondary_dex) {
1327 location = dex_path;
1328 } else {
1329 if (profile_name == nullptr) {
1330 // This path is taken for system server re-compilation lunched from ZygoteInit.
1331 return Dex2oatFileWrapper();
1332 } else {
1333 location = profile_name;
1334 }
1335 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001336 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1337 is_secondary_dex);
1338 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1339 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001340 };
1341 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001342}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001343
Calin Juravle7a570e82017-01-14 16:23:30 -08001344// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1345// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001346bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001347 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001348 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001349 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1350 CHECK(in_vdex_wrapper_fd != nullptr);
1351 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001352 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1353 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001354 char in_odex_path[PKG_PATH_MAX];
1355 int dexopt_action = abs(dexopt_needed);
1356 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001357 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001358
1359 // Infer the name of the output VDEX.
1360 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1361 if (out_vdex_path_str.empty()) {
1362 return false;
1363 }
1364
1365 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001366 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001367 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1368 const char* path = nullptr;
1369 if (is_odex_location) {
1370 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1371 path = in_odex_path;
1372 } else {
1373 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001374 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001375 }
1376 } else {
1377 path = out_oat_path;
1378 }
1379 in_vdex_path_str = create_vdex_filename(path);
1380 if (in_vdex_path_str.empty()) {
1381 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001382 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001383 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001384 // We can update in place when all these conditions are met:
1385 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1386 // on /system typically cannot be updated in place).
1387 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1388 // cannot be currently used by a running process.
1389 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1390 // different vdex files to operate.
1391 update_vdex_in_place =
1392 (in_vdex_path_str == out_vdex_path_str) &&
1393 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1394 !profile_guided;
1395 if (update_vdex_in_place) {
1396 // Open the file read-write to be able to update it.
1397 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1398 if (in_vdex_wrapper_fd->get() == -1) {
1399 // If we failed to open the file, we cannot update it in place.
1400 update_vdex_in_place = false;
1401 }
1402 } else {
1403 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1404 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001405 }
1406
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001407 // If we are updating the vdex in place, we do not need to recreate a vdex,
1408 // and can use the same existing one.
1409 if (update_vdex_in_place) {
1410 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1411 // have bogus stale vdex files.
1412 out_vdex_wrapper_fd->reset(
1413 in_vdex_wrapper_fd->get(),
1414 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1415 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1416 // wrapper).
1417 in_vdex_wrapper_fd->DisableAutoClose();
1418 } else {
1419 out_vdex_wrapper_fd->reset(
1420 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1421 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1422 if (out_vdex_wrapper_fd->get() < 0) {
1423 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1424 return false;
1425 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001426 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001427 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001428 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001429 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1430 return false;
1431 }
1432
1433 // If we got here we successfully opened the vdex files.
1434 return true;
1435}
1436
1437// Opens the output oat file for the given apk.
1438// If successful it stores the output path into out_oat_path and returns true.
1439Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001440 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1441 char* out_oat_path) {
1442 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001443 return Dex2oatFileWrapper();
1444 }
1445 const std::string out_oat_path_str(out_oat_path);
1446 Dex2oatFileWrapper wrapper_fd(
1447 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1448 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1449 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001450 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001451 } else if (!set_permissions_and_ownership(
1452 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001453 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1454 wrapper_fd.reset(-1);
1455 }
1456 return wrapper_fd;
1457}
1458
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001459// Creates RDONLY fds for oat and vdex files, if exist.
1460// Returns false if it fails to create oat out path for the given apk path.
1461// Note that the method returns true even if the files could not be opened.
1462bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1463 const std::string& oat_dir,
1464 const std::string& instruction_set,
1465 bool is_secondary_dex,
1466 unique_fd* oat_file_fd,
1467 unique_fd* vdex_file_fd) {
1468 char oat_path[PKG_PATH_MAX];
1469 if (!create_oat_out_path(apk_path.c_str(),
1470 instruction_set.c_str(),
1471 oat_dir.c_str(),
1472 is_secondary_dex,
1473 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001474 LOG(ERROR) << "Could not create oat out path for "
1475 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001476 return false;
1477 }
1478 oat_file_fd->reset(open(oat_path, O_RDONLY));
1479 if (oat_file_fd->get() < 0) {
1480 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1481 }
1482
1483 std::string vdex_filename = create_vdex_filename(oat_path);
1484 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1485 if (vdex_file_fd->get() < 0) {
1486 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1487 }
1488
1489 return true;
1490}
1491
Calin Juravle7a570e82017-01-14 16:23:30 -08001492// Updates the access times of out_oat_path based on those from apk_path.
1493void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1494 struct stat input_stat;
1495 memset(&input_stat, 0, sizeof(input_stat));
1496 if (stat(apk_path, &input_stat) != 0) {
1497 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1498 return;
1499 }
1500
1501 struct utimbuf ut;
1502 ut.actime = input_stat.st_atime;
1503 ut.modtime = input_stat.st_mtime;
1504 if (utime(out_oat_path, &ut) != 0) {
1505 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1506 }
1507}
1508
Calin Juravle80a21252017-01-17 14:43:25 -08001509// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001510// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1511// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1512// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001513class RunDexoptAnalyzer : public ExecVHelper {
1514 public:
1515 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001516 int vdex_fd,
1517 int oat_fd,
1518 int zip_fd,
1519 const std::string& instruction_set,
1520 const std::string& compiler_filter,
1521 bool profile_was_updated,
1522 bool downgrade,
1523 const char* class_loader_context,
1524 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001525 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001526
1527 // We always run the analyzer in the background job.
1528 const char* dexoptanalyzer_bin = select_execution_binary(
1529 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001530
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001531 std::string dex_file_arg = "--dex-file=" + dex_file;
1532 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1533 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1534 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1535 std::string isa_arg = "--isa=" + instruction_set;
1536 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1537 const char* assume_profile_changed = "--assume-profile-changed";
1538 const char* downgrade_flag = "--downgrade";
1539 std::string class_loader_context_arg = "--class-loader-context=";
1540 if (class_loader_context != nullptr) {
1541 class_loader_context_arg += class_loader_context;
1542 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001543 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1544 if (!class_loader_context_fds.empty()) {
1545 class_loader_context_fds_arg += class_loader_context_fds;
1546 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001547
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001548 // program name, dex file, isa, filter
1549 AddArg(dex_file_arg);
1550 AddArg(isa_arg);
1551 AddArg(compiler_filter_arg);
1552 if (oat_fd >= 0) {
1553 AddArg(oat_fd_arg);
1554 }
1555 if (vdex_fd >= 0) {
1556 AddArg(vdex_fd_arg);
1557 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001558 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001559 if (profile_was_updated) {
1560 AddArg(assume_profile_changed);
1561 }
1562 if (downgrade) {
1563 AddArg(downgrade_flag);
1564 }
1565 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001566 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001567 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001568 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001569 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001570 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001571
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001572 PrepareArgs(dexoptanalyzer_bin);
1573 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001574
1575 // Dexoptanalyzer mode which flattens the given class loader context and
1576 // prints a list of its dex files in that flattened order.
1577 RunDexoptAnalyzer(const char* class_loader_context) {
1578 CHECK(class_loader_context != nullptr);
1579
1580 // We always run the analyzer in the background job.
1581 const char* dexoptanalyzer_bin = select_execution_binary(
1582 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1583
1584 AddArg("--flatten-class-loader-context");
1585 AddArg(std::string("--class-loader-context=") + class_loader_context);
1586 PrepareArgs(dexoptanalyzer_bin);
1587 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001588};
Calin Juravle80a21252017-01-17 14:43:25 -08001589
1590// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001591static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001592 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001593 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001594 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001595 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001596 return false;
1597 }
Calin Juravle114f0812017-03-08 19:05:07 -08001598 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001599
Calin Juravle80a21252017-01-17 14:43:25 -08001600 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001601 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1602 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001603 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001604 return false;
1605 }
1606
1607 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001608 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001609
Calin Juravle7d765462017-09-04 15:57:10 -07001610 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001611 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001612 return false;
1613 }
1614
1615 return true;
1616}
1617
Calin Juravle7d765462017-09-04 15:57:10 -07001618// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1619// secondary dex files. This return codes are returned by the child process created for
1620// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001621
Andreas Gampe194fe422018-02-28 20:16:19 -08001622enum DexoptAnalyzerSkipCodes {
1623 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001624 // Specific errors are encoded in the name.
1625 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1626 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1627 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1628 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1629 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001630 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001631 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001632};
Calin Juravle7d765462017-09-04 15:57:10 -07001633
1634// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001635// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1636// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001637// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1638// of dexoptanalyzer.
1639static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001640 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001641 // The result values are defined in dexoptanalyzer.
1642 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001643 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001644 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001645 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001646 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001647 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001648 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001649 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001650 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001651 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1652 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001653 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1654 " Expected odex file status for secondary dex %s"
1655 " : dexoptanalyzer result=%d",
1656 dex_path.c_str(),
1657 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001658 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001659 }
1660
1661 // Use a second switch for enum switch-case analysis.
1662 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001663 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001664 // If the file does not exist there's no need for dexopt.
1665 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1666 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001667
1668 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1669 *error_msg = "Dexoptanalyzer path validation failed";
1670 return false;
1671 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1672 *error_msg = "Dexoptanalyzer open zip failed";
1673 return false;
1674 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1675 *error_msg = "Dexoptanalyzer dir preparation failed";
1676 return false;
1677 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1678 *error_msg = "Dexoptanalyzer open output failed";
1679 return false;
1680 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1681 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001682 return false;
1683 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001684
1685 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1686 dex_path.c_str(),
1687 result);
1688 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001689}
1690
Calin Juravle7d765462017-09-04 15:57:10 -07001691enum SecondaryDexAccess {
1692 kSecondaryDexAccessReadOk = 0,
1693 kSecondaryDexAccessDoesNotExist = 1,
1694 kSecondaryDexAccessPermissionError = 2,
1695 kSecondaryDexAccessIOError = 3
1696};
1697
1698static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1699 // Check if the path exists and can be read. If not, there's nothing to do.
1700 if (access(dex_path.c_str(), R_OK) == 0) {
1701 return kSecondaryDexAccessReadOk;
1702 } else {
1703 if (errno == ENOENT) {
1704 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1705 return kSecondaryDexAccessDoesNotExist;
1706 } else {
1707 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1708 return errno == EACCES
1709 ? kSecondaryDexAccessPermissionError
1710 : kSecondaryDexAccessIOError;
1711 }
1712 }
1713}
1714
1715static bool is_file_public(const std::string& filename) {
1716 struct stat file_stat;
1717 if (stat(filename.c_str(), &file_stat) == 0) {
1718 return (file_stat.st_mode & S_IROTH) != 0;
1719 }
1720 return false;
1721}
1722
1723// Create the oat file structure for the secondary dex 'dex_path' and assign
1724// the individual path component to the 'out_' parameters.
1725static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001726 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001727 size_t dirIndex = dex_path.rfind('/');
1728 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001729 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001730 return false;
1731 }
1732 // TODO(calin): we have similar computations in at lest 3 other places
1733 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1734 // using string append.
1735 std::string apk_dir = dex_path.substr(0, dirIndex);
1736 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1737 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1738
1739 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1740 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001741 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001742 return false;
1743 }
1744 return true;
1745}
1746
1747// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1748// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001749static bool validate_dexopt_storage_flags(int dexopt_flags,
1750 int* out_storage_flag,
1751 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001752 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1753 *out_storage_flag = FLAG_STORAGE_CE;
1754 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001755 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001756 return false;
1757 }
1758 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1759 *out_storage_flag = FLAG_STORAGE_DE;
1760 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001761 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001762 return false;
1763 }
1764 return true;
1765}
1766
David Brazdil4f6027a2019-03-19 11:44:21 +00001767static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1768 /* out */ std::vector<std::string>* context_dex_paths) {
1769 if (class_loader_context == nullptr) {
1770 return true;
1771 }
1772
1773 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1774
1775 // Pipe to get the hash result back from our child process.
1776 unique_fd pipe_read, pipe_write;
1777 if (!Pipe(&pipe_read, &pipe_write)) {
1778 PLOG(ERROR) << "Failed to create pipe";
1779 return false;
1780 }
1781
1782 pid_t pid = fork();
1783 if (pid == 0) {
1784 // child -- drop privileges before continuing.
1785 drop_capabilities(uid);
1786
1787 // Route stdout to `pipe_write`
1788 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1789 pipe_write.reset();
1790 pipe_read.reset();
1791
1792 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1793 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1794 }
1795
1796 /* parent */
1797 pipe_write.reset();
1798
1799 std::string str_dex_paths;
1800 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1801 PLOG(ERROR) << "Failed to read from pipe";
1802 return false;
1803 }
1804 pipe_read.reset();
1805
1806 int return_code = wait_child(pid);
1807 if (!WIFEXITED(return_code)) {
1808 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1809 return false;
1810 }
1811
1812 constexpr int kFlattenClassLoaderContextSuccess = 50;
1813 return_code = WEXITSTATUS(return_code);
1814 if (return_code != kFlattenClassLoaderContextSuccess) {
1815 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1816 return false;
1817 }
1818
1819 if (!str_dex_paths.empty()) {
1820 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1821 }
1822 return true;
1823}
1824
1825static int open_dex_paths(const std::vector<std::string>& dex_paths,
1826 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1827 for (const std::string& dex_path : dex_paths) {
1828 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1829 if (zip_fds->back().get() < 0) {
1830 *error_msg = StringPrintf(
1831 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1832 if (errno == ENOENT) {
1833 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1834 } else {
1835 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1836 }
1837 }
1838 }
1839 return 0;
1840}
1841
1842static std::string join_fds(const std::vector<unique_fd>& fds) {
1843 std::stringstream ss;
1844 bool is_first = true;
1845 for (const unique_fd& fd : fds) {
1846 if (is_first) {
1847 is_first = false;
1848 } else {
1849 ss << ":";
1850 }
1851 ss << fd.get();
1852 }
1853 return ss.str();
1854}
1855
Calin Juravlec9eab382017-01-25 01:17:17 -08001856// 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 -08001857// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1858// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001859// When returning true, the output parameters will be:
1860// - is_public_out: whether or not the oat file should not be made public
1861// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1862// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001863static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001864 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001865 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001866 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001867 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001868 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001869 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001870 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1871 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001872 return false;
1873 }
Calin Juravle7d765462017-09-04 15:57:10 -07001874 // Compute the oat dir as it's not easy to extract it from the child computation.
1875 char oat_path[PKG_PATH_MAX];
1876 char oat_dir[PKG_PATH_MAX];
1877 char oat_isa_dir[PKG_PATH_MAX];
1878 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001879 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1880 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001881 return false;
1882 }
Calin Juravle7d765462017-09-04 15:57:10 -07001883 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001884
Calin Juravle80a21252017-01-17 14:43:25 -08001885 pid_t pid = fork();
1886 if (pid == 0) {
1887 // child -- drop privileges before continuing.
1888 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001889
1890 // Validate the path structure.
1891 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1892 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001893 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001894 }
1895
1896 // Open the dex file.
1897 unique_fd zip_fd;
1898 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1899 if (zip_fd.get() < 0) {
1900 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001901 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001902 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001903 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001904 }
1905 }
1906
David Brazdil4f6027a2019-03-19 11:44:21 +00001907 // Open class loader context dex files.
1908 std::vector<unique_fd> context_zip_fds;
1909 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1910 if (open_dex_paths_rc != 0) {
1911 _exit(open_dex_paths_rc);
1912 }
1913
Calin Juravle7d765462017-09-04 15:57:10 -07001914 // Prepare the oat directories.
1915 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001916 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001917 }
1918
1919 // Open the vdex/oat files if any.
1920 unique_fd oat_file_fd;
1921 unique_fd vdex_file_fd;
1922 if (!maybe_open_oat_and_vdex_file(dex_path,
1923 *oat_dir_out,
1924 instruction_set,
1925 true /* is_secondary_dex */,
1926 &oat_file_fd,
1927 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001928 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001929 }
1930
1931 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001932 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1933 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001934
1935 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001936 // Note that we do not do it before the fork since opening the files is required to happen
1937 // after forking.
1938 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1939 vdex_file_fd.get(),
1940 oat_file_fd.get(),
1941 zip_fd.get(),
1942 instruction_set,
1943 compiler_filter, profile_was_updated,
1944 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001945 class_loader_context,
1946 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001947 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001948 }
1949
1950 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001951 int result = wait_child(pid);
1952 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001953 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1954 dex_path.c_str(),
1955 result);
1956 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001957 return false;
1958 }
1959 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001960 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001961 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1962 result,
1963 dexopt_needed_out,
1964 error_msg);
1965 if (!success) {
1966 LOG(ERROR) << *error_msg;
1967 }
Calin Juravle7d765462017-09-04 15:57:10 -07001968
1969 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1970
Calin Juravle80a21252017-01-17 14:43:25 -08001971 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001972 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1973 // makes the code simpler; force compilation is only needed during tests).
1974 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001975 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001976 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001977 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1978 }
1979
Calin Juravle7d765462017-09-04 15:57:10 -07001980 // Check if we should make the oat file public.
1981 // Note that if the dex file is not public the compiled code cannot be made public.
1982 // It is ok to check this flag outside in the parent process.
1983 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1984
Calin Juravle80a21252017-01-17 14:43:25 -08001985 return success;
1986}
1987
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001988static std::string format_dexopt_error(int status, const char* dex_path) {
1989 if (WIFEXITED(status)) {
1990 int int_code = WEXITSTATUS(status);
1991 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1992 if (code_name != nullptr) {
1993 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1994 }
1995 }
1996 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001997}
1998
Calin Juravlec9eab382017-01-25 01:17:17 -08001999int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002000 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002001 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002002 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002003 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002004 CHECK(pkgname != nullptr);
2005 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002006 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002007 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2008 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002009
Calin Juravled23dee72017-07-06 16:29:11 -07002010 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002011 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002012 return -1;
2013 }
2014
2015 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002016 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2017 class_loader_context);
2018 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002019 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002020 }
2021
Calin Juravleebc8a792017-04-04 20:21:05 -07002022 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002023 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2024 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2025 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002026 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002027 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002028 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002029 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002030 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002031
2032 // Check if we're dealing with a secondary dex file and if we need to compile it.
2033 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002034 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002035 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002036 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2037 *error_msg = "Failed acquiring context dex paths";
2038 return -1; // We had an error, logged in the process method.
2039 }
2040
Calin Juravlec9eab382017-01-25 01:17:17 -08002041 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002042 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002043 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002044 oat_dir = oat_dir_str.c_str();
2045 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2046 return 0; // Nothing to do, report success.
2047 }
2048 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002049 if (error_msg->empty()) { // TODO: Make this a CHECK.
2050 *error_msg = "Failed processing secondary.";
2051 }
Calin Juravle80a21252017-01-17 14:43:25 -08002052 return -1; // We had an error, logged in the process method.
2053 }
2054 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002055 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002056 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002057 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2058 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2059 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002060
2061 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002062 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002063 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002064 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2065 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002066 return -1;
2067 }
2068
David Brazdil4f6027a2019-03-19 11:44:21 +00002069 // Open class loader context dex files.
2070 std::vector<unique_fd> context_input_fds;
2071 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2072 LOG(ERROR) << *error_msg;
2073 return -1;
2074 }
2075
Calin Juravle7a570e82017-01-14 16:23:30 -08002076 // Create the output OAT file.
2077 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002078 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002079 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002080 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002081 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002082 return -1;
2083 }
2084
2085 // Open vdex files.
2086 Dex2oatFileWrapper in_vdex_fd;
2087 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002088 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2089 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002090 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002091 return -1;
2092 }
2093
Calin Juravlecb556e32017-04-04 20:22:50 -07002094 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2095 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2096 // fully inherit their parent context).
2097 // Note that for primary apk the oat files are created before, in a separate installd
2098 // call which also does the restorecon. TODO(calin): unify the paths.
2099 if (is_secondary_dex) {
2100 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2101 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002102 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2103 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002104 return -1;
2105 }
2106 }
2107
Jeff Sharkey90aff262016-12-12 14:28:24 -07002108 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002109 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002110
Calin Juravle7a570e82017-01-14 16:23:30 -08002111 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002112 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002113 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002114
liulvping61907742018-08-21 09:36:52 +08002115 if (reference_profile_fd.get() == -1) {
2116 // We don't create an app image without reference profile since there is no speedup from
2117 // loading it in that case and instead will be a small overhead.
2118 generate_app_image = false;
2119 }
2120
2121 // Create the app image file if needed.
2122 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2123 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2124
Calin Juravle62c5a372018-02-01 17:03:23 +00002125 unique_fd dex_metadata_fd;
2126 if (dex_metadata_path != nullptr) {
2127 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2128 if (dex_metadata_fd.get() < 0) {
2129 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2130 }
2131 }
2132
Andreas Gampe023b2242018-02-28 16:03:25 -08002133 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002134
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002135 RunDex2Oat runner(input_fd.get(),
2136 out_oat_fd.get(),
2137 in_vdex_fd.get(),
2138 out_vdex_fd.get(),
2139 image_fd.get(),
2140 dex_path,
2141 out_oat_path,
2142 swap_fd.get(),
2143 instruction_set,
2144 compiler_filter,
2145 debuggable,
2146 boot_complete,
2147 background_job_compile,
2148 reference_profile_fd.get(),
2149 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002150 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002151 target_sdk_version,
2152 enable_hidden_api_checks,
2153 generate_compact_dex,
2154 dex_metadata_fd.get(),
2155 compilation_reason);
2156
Jeff Sharkey90aff262016-12-12 14:28:24 -07002157 pid_t pid = fork();
2158 if (pid == 0) {
2159 /* child -- drop privileges before continuing */
2160 drop_capabilities(uid);
2161
Richard Uhler76cc0272016-12-08 10:46:35 +00002162 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002163 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002164 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002165 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002166 }
2167
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002168 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002169 } else {
2170 int res = wait_child(pid);
2171 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002172 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002173 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002174 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2175 << std::hex << std::setw(4) << res << ", process failed";
2176 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002177 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002178 }
2179 }
2180
Calin Juravlec9eab382017-01-25 01:17:17 -08002181 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002182
2183 // We've been successful, don't delete output.
2184 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002185 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002186 image_fd.SetCleanup(false);
2187 reference_profile_fd.SetCleanup(false);
2188
2189 return 0;
2190}
2191
Calin Juravlec9eab382017-01-25 01:17:17 -08002192// Try to remove the given directory. Log an error if the directory exists
2193// and is empty but could not be removed.
2194static bool rmdir_if_empty(const char* dir) {
2195 if (rmdir(dir) == 0) {
2196 return true;
2197 }
2198 if (errno == ENOENT || errno == ENOTEMPTY) {
2199 return true;
2200 }
2201 PLOG(ERROR) << "Failed to remove dir: " << dir;
2202 return false;
2203}
2204
2205// Try to unlink the given file. Log an error if the file exists and could not
2206// be unlinked.
2207static bool unlink_if_exists(const std::string& file) {
2208 if (unlink(file.c_str()) == 0) {
2209 return true;
2210 }
2211 if (errno == ENOENT) {
2212 return true;
2213
2214 }
2215 PLOG(ERROR) << "Could not unlink: " << file;
2216 return false;
2217}
2218
Calin Juravle7d765462017-09-04 15:57:10 -07002219enum ReconcileSecondaryDexResult {
2220 kReconcileSecondaryDexExists = 0,
2221 kReconcileSecondaryDexCleanedUp = 1,
2222 kReconcileSecondaryDexValidationError = 2,
2223 kReconcileSecondaryDexCleanUpError = 3,
2224 kReconcileSecondaryDexAccessIOError = 4,
2225};
Calin Juravlec9eab382017-01-25 01:17:17 -08002226
2227// Reconcile the secondary dex 'dex_path' and its generated oat files.
2228// Return true if all the parameters are valid and the secondary dex file was
2229// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2230// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2231// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2232// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2233// Return false if there were errors during processing. In this case
2234// out_secondary_dex_exists will be set to false.
2235bool reconcile_secondary_dex_file(const std::string& dex_path,
2236 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2237 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2238 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002239 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002240 if (isas.size() == 0) {
2241 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2242 return false;
2243 }
2244
Calin Juravle7d765462017-09-04 15:57:10 -07002245 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2246 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2247 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002248 return false;
2249 }
2250
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002251 // As a security measure we want to unlink art artifacts with the reduced capabilities
2252 // of the package user id. So we fork and drop capabilities in the child.
2253 pid_t pid = fork();
2254 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002255 /* child -- drop privileges before continuing */
2256 drop_capabilities(uid);
2257
2258 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Greg Kaiser8042c372019-03-26 06:23:19 -07002259 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002260 uid, storage_flag)) {
2261 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2262 _exit(kReconcileSecondaryDexValidationError);
2263 }
2264
2265 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2266 switch (access_check) {
2267 case kSecondaryDexAccessDoesNotExist:
2268 // File does not exist. Proceed with cleaning.
2269 break;
2270 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2271 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2272 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2273 default:
2274 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2275 _exit(kReconcileSecondaryDexValidationError);
2276 }
2277
2278 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002279 char oat_path[PKG_PATH_MAX];
2280 char oat_dir[PKG_PATH_MAX];
2281 char oat_isa_dir[PKG_PATH_MAX];
2282 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002283 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002284 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002285 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002286 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2287 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002288 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002289 }
Calin Juravle51314092017-05-18 15:33:05 -07002290
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002291 // Delete oat/vdex/art files.
2292 result = unlink_if_exists(oat_path) && result;
2293 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2294 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002295
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002296 // Delete profiles.
2297 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002298 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002299 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002300 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002301 result = unlink_if_exists(current_profile) && result;
2302 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002303
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002304 // We upgraded once the location of current profile for secondary dex files.
2305 // Check for any previous left-overs and remove them as well.
2306 std::string old_current_profile = dex_path + ".prof";
2307 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002308
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002309 // Try removing the directories as well, they might be empty.
2310 result = rmdir_if_empty(oat_isa_dir) && result;
2311 result = rmdir_if_empty(oat_dir) && result;
2312 }
Calin Juravle7d765462017-09-04 15:57:10 -07002313 if (!result) {
2314 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2315 }
2316 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002317 }
2318
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002319 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002320 if (!WIFEXITED(return_code)) {
2321 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2322 } else {
2323 return_code = WEXITSTATUS(return_code);
2324 }
2325
2326 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2327
2328 switch (return_code) {
2329 case kReconcileSecondaryDexCleanedUp:
2330 case kReconcileSecondaryDexValidationError:
2331 // If we couldn't validate assume the dex file does not exist.
2332 // This will purge the entry from the PM records.
2333 *out_secondary_dex_exists = false;
2334 return true;
2335 case kReconcileSecondaryDexExists:
2336 *out_secondary_dex_exists = true;
2337 return true;
2338 case kReconcileSecondaryDexAccessIOError:
2339 // We had an access IO error.
2340 // Return false so that we can try again.
2341 // The value of out_secondary_dex_exists does not matter in this case and by convention
2342 // is set to false.
2343 *out_secondary_dex_exists = false;
2344 return false;
2345 default:
2346 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2347 *out_secondary_dex_exists = false;
2348 return false;
2349 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002350}
2351
Alan Stokesa25d90c2017-10-16 10:56:00 +01002352// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2353// Returns true if all parameters are valid and the hash successfully computed and stored in
2354// out_secondary_dex_hash.
2355// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2356// the app.
2357// For any other errors (e.g. if any of the parameters are invalid) returns false.
2358bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2359 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2360 std::vector<uint8_t>* out_secondary_dex_hash) {
2361 out_secondary_dex_hash->clear();
2362
2363 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2364
2365 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2366 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2367 << storage_flag;
2368 return false;
2369 }
2370
2371 // Pipe to get the hash result back from our child process.
2372 unique_fd pipe_read, pipe_write;
2373 if (!Pipe(&pipe_read, &pipe_write)) {
2374 PLOG(ERROR) << "Failed to create pipe";
2375 return false;
2376 }
2377
2378 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2379 // access data the app itself can access.
2380 pid_t pid = fork();
2381 if (pid == 0) {
2382 // child -- drop privileges before continuing
2383 drop_capabilities(uid);
2384 pipe_read.reset();
2385
2386 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2387 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002388 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002389 }
2390
2391 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2392 if (fd == -1) {
2393 if (errno == EACCES || errno == ENOENT) {
2394 // Not treated as an error.
2395 _exit(0);
2396 }
2397 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002398 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002399 }
2400
2401 SHA256_CTX ctx;
2402 SHA256_Init(&ctx);
2403
2404 std::vector<uint8_t> buffer(65536);
2405 while (true) {
2406 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2407 if (bytes_read == 0) {
2408 break;
2409 } else if (bytes_read == -1) {
2410 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002411 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002412 }
2413
2414 SHA256_Update(&ctx, buffer.data(), bytes_read);
2415 }
2416
2417 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2418 SHA256_Final(hash.data(), &ctx);
2419 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002420 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002421 }
2422
2423 _exit(0);
2424 }
2425
2426 // parent
2427 pipe_write.reset();
2428
2429 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2430 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2431 out_secondary_dex_hash->clear();
2432 }
2433 return wait_child(pid) == 0;
2434}
2435
Jeff Sharkey90aff262016-12-12 14:28:24 -07002436// Helper for move_ab, so that we can have common failure-case cleanup.
2437static bool unlink_and_rename(const char* from, const char* to) {
2438 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2439 // return a failure.
2440 struct stat s;
2441 if (stat(to, &s) == 0) {
2442 if (!S_ISREG(s.st_mode)) {
2443 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2444 return false;
2445 }
2446 if (unlink(to) != 0) {
2447 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2448 return false;
2449 }
2450 } else {
2451 // This may be a permission problem. We could investigate the error code, but we'll just
2452 // let the rename failure do the work for us.
2453 }
2454
2455 // Try to rename "to" to "from."
2456 if (rename(from, to) != 0) {
2457 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2458 return false;
2459 }
2460 return true;
2461}
2462
2463// Move/rename a B artifact (from) to an A artifact (to).
2464static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2465 // Check whether B exists.
2466 {
2467 struct stat s;
2468 if (stat(b_path.c_str(), &s) != 0) {
2469 // Silently ignore for now. The service calling this isn't smart enough to understand
2470 // lack of artifacts at the moment.
2471 return false;
2472 }
2473 if (!S_ISREG(s.st_mode)) {
2474 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2475 // Try to unlink, but swallow errors.
2476 unlink(b_path.c_str());
2477 return false;
2478 }
2479 }
2480
2481 // Rename B to A.
2482 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2483 // Delete the b_path so we don't try again (or fail earlier).
2484 if (unlink(b_path.c_str()) != 0) {
2485 PLOG(ERROR) << "Could not unlink " << b_path;
2486 }
2487
2488 return false;
2489 }
2490
2491 return true;
2492}
2493
2494bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2495 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002496 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2497 if (slot_suffix.empty()) {
2498 return false;
2499 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002500
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002501 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2502 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2503 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002504 }
2505
2506 // Validate other inputs.
2507 if (validate_apk_path(apk_path) != 0) {
2508 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2509 return false;
2510 }
2511 if (validate_apk_path(oat_dir) != 0) {
2512 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2513 return false;
2514 }
2515
2516 char a_path[PKG_PATH_MAX];
2517 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2518 return false;
2519 }
2520 const std::string a_vdex_path = create_vdex_filename(a_path);
2521 const std::string a_image_path = create_image_filename(a_path);
2522
2523 // B path = A path + slot suffix.
2524 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2525 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2526 const std::string b_image_path = StringPrintf("%s.%s",
2527 a_image_path.c_str(),
2528 slot_suffix.c_str());
2529
2530 bool success = true;
2531 if (move_ab_path(b_path, a_path)) {
2532 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2533 // Note: we can live without an app image. As such, ignore failure to move the image file.
2534 // If we decide to require the app image, or the app image being moved correctly,
2535 // then change accordingly.
2536 constexpr bool kIgnoreAppImageFailure = true;
2537
2538 if (!a_image_path.empty()) {
2539 if (!move_ab_path(b_image_path, a_image_path)) {
2540 unlink(a_image_path.c_str());
2541 if (!kIgnoreAppImageFailure) {
2542 success = false;
2543 }
2544 }
2545 }
2546 } else {
2547 // Cleanup: delete B image, ignore errors.
2548 unlink(b_image_path.c_str());
2549 success = false;
2550 }
2551 } else {
2552 // Cleanup: delete B image, ignore errors.
2553 unlink(b_vdex_path.c_str());
2554 unlink(b_image_path.c_str());
2555 success = false;
2556 }
2557 return success;
2558}
2559
2560bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2561 // Delete the oat/odex file.
2562 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002563 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002564 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002565 return false;
2566 }
2567
2568 // In case of a permission failure report the issue. Otherwise just print a warning.
2569 auto unlink_and_check = [](const char* path) -> bool {
2570 int result = unlink(path);
2571 if (result != 0) {
2572 if (errno == EACCES || errno == EPERM) {
2573 PLOG(ERROR) << "Could not unlink " << path;
2574 return false;
2575 }
2576 PLOG(WARNING) << "Could not unlink " << path;
2577 }
2578 return true;
2579 };
2580
2581 // Delete the oat/odex file.
2582 bool return_value_oat = unlink_and_check(out_path);
2583
2584 // Derive and delete the app image.
2585 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2586
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002587 // Derive and delete the vdex file.
2588 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2589
Jeff Sharkey90aff262016-12-12 14:28:24 -07002590 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002591 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002592}
2593
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002594static bool is_absolute_path(const std::string& path) {
2595 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2596 LOG(ERROR) << "Invalid absolute path " << path;
2597 return false;
2598 } else {
2599 return true;
2600 }
2601}
2602
2603static bool is_valid_instruction_set(const std::string& instruction_set) {
2604 // TODO: add explicit whitelisting of instruction sets
2605 if (instruction_set.find('/') != std::string::npos) {
2606 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2607 return false;
2608 } else {
2609 return true;
2610 }
2611}
2612
2613bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2614 const char *apk_path, const char *instruction_set) {
2615 std::string oat_dir_ = oat_dir;
2616 std::string apk_path_ = apk_path;
2617 std::string instruction_set_ = instruction_set;
2618
2619 if (!is_absolute_path(oat_dir_)) return false;
2620 if (!is_absolute_path(apk_path_)) return false;
2621 if (!is_valid_instruction_set(instruction_set_)) return false;
2622
2623 std::string::size_type end = apk_path_.rfind('.');
2624 std::string::size_type start = apk_path_.rfind('/', end);
2625 if (end == std::string::npos || start == std::string::npos) {
2626 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2627 return false;
2628 }
2629
2630 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2631 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2632 const char* res = res_.c_str();
2633 if (strlen(res) >= PKG_PATH_MAX) {
2634 LOG(ERROR) << "Result too large";
2635 return false;
2636 } else {
2637 strlcpy(path, res, PKG_PATH_MAX);
2638 return true;
2639 }
2640}
2641
2642bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2643 const char *instruction_set) {
2644 std::string apk_path_ = apk_path;
2645 std::string instruction_set_ = instruction_set;
2646
2647 if (!is_absolute_path(apk_path_)) return false;
2648 if (!is_valid_instruction_set(instruction_set_)) return false;
2649
2650 std::string::size_type end = apk_path_.rfind('.');
2651 std::string::size_type start = apk_path_.rfind('/', end);
2652 if (end == std::string::npos || start == std::string::npos) {
2653 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2654 return false;
2655 }
2656
2657 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2658 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2659}
2660
2661bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2662 const char *instruction_set) {
2663 std::string src_ = src;
2664 std::string instruction_set_ = instruction_set;
2665
2666 if (!is_absolute_path(src_)) return false;
2667 if (!is_valid_instruction_set(instruction_set_)) return false;
2668
2669 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2670 if (*it == '/') {
2671 *it = '@';
2672 }
2673 }
2674
2675 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2676 + DALVIK_CACHE_POSTFIX;
2677 const char* res = res_.c_str();
2678 if (strlen(res) >= PKG_PATH_MAX) {
2679 LOG(ERROR) << "Result too large";
2680 return false;
2681 } else {
2682 strlcpy(path, res, PKG_PATH_MAX);
2683 return true;
2684 }
2685}
2686
Calin Juravle59f7ab82018-04-27 17:50:23 -07002687bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2688 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002689 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2690 for (const std::string& elem : classpaths_elems) {
2691 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2692 if (fd < 0) {
2693 PLOG(ERROR) << "Could not open classpath elem " << elem;
2694 return false;
2695 } else {
2696 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002697 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002698 }
2699 }
2700 return true;
2701}
2702
2703static bool create_app_profile_snapshot(int32_t app_id,
2704 const std::string& package_name,
2705 const std::string& profile_name,
2706 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002707 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2708
Calin Juravle824a64d2018-01-18 20:23:17 -08002709 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002710 if (snapshot_fd < 0) {
2711 return false;
2712 }
2713
2714 std::vector<unique_fd> profiles_fd;
2715 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002716 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2717 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002718 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2719 return false;
2720 }
2721
2722 profiles_fd.push_back(std::move(reference_profile_fd));
2723
Calin Juravle0d0a4922018-01-23 19:54:11 -08002724 // Open the class paths elements. These will be used to filter out profile data that does
2725 // not belong to the classpath during merge.
2726 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002727 std::vector<std::string> dex_locations;
2728 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002729 return false;
2730 }
2731
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002732 RunProfman args;
2733 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002734 pid_t pid = fork();
2735 if (pid == 0) {
2736 /* child -- drop privileges before continuing */
2737 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002738 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002739 }
2740
2741 /* parent */
2742 int return_code = wait_child(pid);
2743 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002744 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002745 return false;
2746 }
2747
2748 return true;
2749}
2750
Calin Juravle0d0a4922018-01-23 19:54:11 -08002751static bool create_boot_image_profile_snapshot(const std::string& package_name,
2752 const std::string& profile_name,
2753 const std::string& classpath) {
2754 // The reference profile directory for the android package might not be prepared. Do it now.
2755 const std::string ref_profile_dir =
2756 create_primary_reference_profile_package_dir_path(package_name);
2757 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2758 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2759 return false;
2760 }
2761
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002762 // Return false for empty class path since it may otherwise return true below if profiles is
2763 // empty.
2764 if (classpath.empty()) {
2765 PLOG(ERROR) << "Class path is empty";
2766 return false;
2767 }
2768
Calin Juravle0d0a4922018-01-23 19:54:11 -08002769 // Open and create the snapshot profile.
2770 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2771
2772 // Collect all non empty profiles.
2773 // The collection will traverse all applications profiles and find the non empty files.
2774 // This has the potential of inspecting a large number of files and directories (depending
2775 // on the number of applications and users). So there is a slight increase in the chance
2776 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2777 // fail the snapshot and aggregate whatever profile we could open.
2778 //
2779 // The profile snapshot is a best effort based on available data it's ok if some data
2780 // from some apps is missing. It will be counter productive for the snapshot to fail
2781 // because we could not open or read some of the files.
2782 std::vector<std::string> profiles;
2783 if (!collect_profiles(&profiles)) {
2784 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2785 }
2786
2787 // If we have no profiles return early.
2788 if (profiles.empty()) {
2789 return true;
2790 }
2791
2792 // Open the classpath elements. These will be used to filter out profile data that does
2793 // not belong to the classpath during merge.
2794 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002795 std::vector<std::string> dex_locations;
2796 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002797 return false;
2798 }
2799
2800 // If we could not open any files from the classpath return an error.
2801 if (apk_fds.empty()) {
2802 LOG(ERROR) << "Could not open any of the classpath elements.";
2803 return false;
2804 }
2805
2806 // Aggregate the profiles in batches of kAggregationBatchSize.
2807 // We do this to avoid opening a huge a amount of files.
2808 static constexpr size_t kAggregationBatchSize = 10;
2809
2810 std::vector<unique_fd> profiles_fd;
2811 for (size_t i = 0; i < profiles.size(); ) {
2812 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2813 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2814 if (fd.get() >= 0) {
2815 profiles_fd.push_back(std::move(fd));
2816 }
2817 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002818 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002819 args.SetupMerge(profiles_fd,
2820 snapshot_fd,
2821 apk_fds,
Calin Juravle9d250172019-09-27 13:22:41 -07002822 dex_locations);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002823 pid_t pid = fork();
2824 if (pid == 0) {
2825 /* child -- drop privileges before continuing */
2826 drop_capabilities(AID_SYSTEM);
2827
Calin Juravle59f7ab82018-04-27 17:50:23 -07002828 // The introduction of new access flags into boot jars causes them to
2829 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002830 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002831 }
2832
2833 /* parent */
2834 int return_code = wait_child(pid);
2835 if (!WIFEXITED(return_code)) {
2836 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2837 return false;
2838 }
2839 return true;
2840 }
2841 return true;
2842}
2843
2844bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2845 const std::string& profile_name, const std::string& classpath) {
2846 if (app_id == -1) {
2847 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2848 } else {
2849 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2850 }
2851}
2852
Calin Juravlec3b049e2018-01-18 22:32:58 -08002853bool prepare_app_profile(const std::string& package_name,
2854 userid_t user_id,
2855 appid_t app_id,
2856 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002857 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002858 const std::unique_ptr<std::string>& dex_metadata) {
2859 // Prepare the current profile.
2860 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2861 /*is_secondary_dex*/ false);
2862 uid_t uid = multiuser_get_uid(user_id, app_id);
2863 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2864 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2865 return false;
2866 }
2867
2868 // Check if we need to install the profile from the dex metadata.
2869 if (dex_metadata == nullptr) {
2870 return true;
2871 }
2872
2873 // We have a dex metdata. Merge the profile into the reference profile.
2874 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2875 /*read_write*/ true, /*is_secondary_dex*/ false);
2876 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2877 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002878 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2879 if (apk_fd < 0) {
2880 PLOG(ERROR) << "Could not open code path " << code_path;
2881 return false;
2882 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002883
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002884 RunProfman args;
2885 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2886 std::move(ref_profile_fd),
2887 std::move(apk_fd),
2888 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002889 pid_t pid = fork();
2890 if (pid == 0) {
2891 /* child -- drop privileges before continuing */
2892 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2893 drop_capabilities(app_shared_gid);
2894
Calin Juravlef63d4792018-01-30 17:43:34 +00002895 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002896 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002897 }
2898
2899 /* parent */
2900 int return_code = wait_child(pid);
2901 if (!WIFEXITED(return_code)) {
2902 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2903 return false;
2904 }
2905 return true;
2906}
2907
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002908} // namespace installd
2909} // namespace android