blob: ffd11915016a65e4bc4aa939da424f56cd06774e [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;
Alan Stokesa25d90c2017-10-16 10:56:00 +010061using android::base::ReadFully;
62using android::base::StringPrintf;
63using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080064using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070065
66namespace android {
67namespace installd {
68
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070069// Should minidebug info be included in compiled artifacts? Even if this value is
70// "true," usage might still be conditional to other constraints, e.g., system
71// property overrides.
72static constexpr bool kEnableMinidebugInfo = true;
73
74static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
75static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
76static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080077static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070078
Andreas Gampefa2dadd2018-02-28 19:52:47 -080079
Calin Juravle114f0812017-03-08 19:05:07 -080080// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
81struct FreeDelete {
82 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
83 void operator()(const void* ptr) const {
84 free(const_cast<void*>(ptr));
85 }
86};
87
88// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
89template <typename T>
90using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
91
Calin Juravle1a0af3b2017-03-09 14:33:33 -080092static unique_fd invalid_unique_fd() {
93 return unique_fd(-1);
94}
95
Andreas Gampe6a9cf722017-07-24 16:49:10 -070096static bool is_debug_runtime() {
97 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
98}
99
David Sehra3b5ab62017-10-25 14:27:29 -0700100static bool is_debuggable_build() {
101 return android::base::GetBoolProperty("ro.debuggable", false);
102}
103
Jeff Sharkey90aff262016-12-12 14:28:24 -0700104static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800105 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700106 if (ufd.get() < 0) {
107 if (errno != ENOENT) {
108 PLOG(WARNING) << "Could not open profile " << profile;
109 return false;
110 } else {
111 // Nothing to clear. That's ok.
112 return true;
113 }
114 }
115
116 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
117 if (errno != EWOULDBLOCK) {
118 PLOG(WARNING) << "Error locking profile " << profile;
119 }
120 // This implies that the app owning this profile is running
121 // (and has acquired the lock).
122 //
123 // If we can't acquire the lock bail out since clearing is useless anyway
124 // (the app will write again to the profile).
125 //
126 // Note:
127 // This does not impact the this is not an issue for the profiling correctness.
128 // In case this is needed because of an app upgrade, profiles will still be
129 // eventually cleared by the app itself due to checksum mismatch.
130 // If this is needed because profman advised, then keeping the data around
131 // until the next run is again not an issue.
132 //
133 // If the app attempts to acquire a lock while we've held one here,
134 // it will simply skip the current write cycle.
135 return false;
136 }
137
138 bool truncated = ftruncate(ufd.get(), 0) == 0;
139 if (!truncated) {
140 PLOG(WARNING) << "Could not truncate " << profile;
141 }
142 if (flock(ufd.get(), LOCK_UN) != 0) {
143 PLOG(WARNING) << "Error unlocking profile " << profile;
144 }
145 return truncated;
146}
147
Calin Juravle114f0812017-03-08 19:05:07 -0800148// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800149// The location is the profile name for primary apks or the dex path for secondary dex files.
150static bool clear_reference_profile(const std::string& package_name, const std::string& location,
151 bool is_secondary_dex) {
152 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700153}
154
Calin Juravle114f0812017-03-08 19:05:07 -0800155// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800156// The location is the profile name for primary apks or the dex path for secondary dex files.
157static bool clear_current_profile(const std::string& package_name, const std::string& location,
158 userid_t user, bool is_secondary_dex) {
159 return clear_profile(create_current_profile_path(user, package_name, location,
160 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700161}
162
Calin Juravle114f0812017-03-08 19:05:07 -0800163// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800164// The location is the profile name for primary apks or the dex path for secondary dex files.
165bool clear_primary_reference_profile(const std::string& package_name,
166 const std::string& location) {
167 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800168}
169
170// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800171// The location is the profile name for primary apks or the dex path for secondary dex files.
172bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700173 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800174 // 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 -0700175 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
176 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800177 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700178 }
179 return success;
180}
181
Calin Juravle114f0812017-03-08 19:05:07 -0800182// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800183bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
184 userid_t user) {
185 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800186}
187
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700188static std::vector<std::string> SplitBySpaces(const std::string& str) {
189 if (str.empty()) {
190 return {};
191 }
192 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700193}
194
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700195static const char* get_location_from_path(const char* path) {
196 static constexpr char kLocationSeparator = '/';
197 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700198 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700199 return path;
200 } else {
201 // Skip the separator character.
202 return location + 1;
203 }
204}
205
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800206// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
207// need to be performed between the fork and exec.
208class ExecVHelper {
209 public:
210 // Store a placeholder for the binary name.
211 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800212
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800213 void PrepareArgs(const std::string& bin) {
214 CHECK(!args_.empty());
215 CHECK(args_[0].empty());
216 args_[0] = bin;
217 // Write char* into array.
218 for (const std::string& arg : args_) {
219 argv_.push_back(arg.c_str());
220 }
221 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800222 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800223
224 [[ noreturn ]]
225 void Exec(int exit_code) {
226 execv(argv_[0], (char * const *)&argv_[0]);
227 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
228 exit(exit_code);
229 }
230
231 // Add an arg if it's not empty.
232 void AddArg(const std::string& arg) {
233 if (!arg.empty()) {
234 args_.push_back(arg);
235 }
236 }
237
238 // Add a runtime arg if it's not empty.
239 void AddRuntimeArg(const std::string& arg) {
240 if (!arg.empty()) {
241 args_.push_back("--runtime-arg");
242 args_.push_back(arg);
243 }
244 }
245
246 protected:
247 // Holder arrays for backing arg storage.
248 std::vector<std::string> args_;
249
250 // Argument poiners.
251 std::vector<const char*> argv_;
252};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700253
254static std::string MapPropertyToArg(const std::string& property,
255 const std::string& format,
256 const std::string& default_value = "") {
257 std::string prop = GetProperty(property, default_value);
258 if (!prop.empty()) {
259 return StringPrintf(format.c_str(), prop.c_str());
260 }
261 return "";
262}
263
Calin Juravlef74a7372019-02-28 20:29:41 -0800264// Determines which binary we should use for execution (the debug or non-debug version).
265// e.g. dex2oatd vs dex2oat
266static const char* select_execution_binary(const char* binary, const char* debug_binary,
267 bool background_job_compile) {
268 return select_execution_binary(
269 binary,
270 debug_binary,
271 background_job_compile,
272 is_debug_runtime(),
273 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
274 is_debuggable_build());
275}
276
277// Determines which binary we should use for execution (the debug or non-debug version).
278// e.g. dex2oatd vs dex2oat
279// This is convenient method which is much easier to test because it doesn't read
280// system properties.
281const char* select_execution_binary(
282 const char* binary,
283 const char* debug_binary,
284 bool background_job_compile,
285 bool is_debug_runtime,
286 bool is_release,
287 bool is_debuggable_build) {
288 // Do not use debug binaries for release candidates (to give more soak time).
289 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
290
291 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
292 // the file is present (it may not be on images with very little space available).
293 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
294
295 return useDebug ? debug_binary : binary;
296}
297
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000298// Namespace for Android Runtime flags applied during boot time.
299static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
300// Feature flag name for running the JIT in Zygote experiment, b/119800099.
301static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
302// Location of the apex image.
303static const char* kApexImage = "/system/framework/apex.art";
304
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800305class RunDex2Oat : public ExecVHelper {
306 public:
307 RunDex2Oat(int zip_fd,
308 int oat_fd,
309 int input_vdex_fd,
310 int output_vdex_fd,
311 int image_fd,
312 const char* input_file_name,
313 const char* output_file_name,
314 int swap_fd,
315 const char* instruction_set,
316 const char* compiler_filter,
317 bool debuggable,
318 bool post_bootcomplete,
319 bool background_job_compile,
320 int profile_fd,
321 const char* class_loader_context,
322 int target_sdk_version,
323 bool enable_hidden_api_checks,
324 bool generate_compact_dex,
325 int dex_metadata_fd,
326 const char* compilation_reason) {
327 // Get the relative path to the input file.
328 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700329
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800330 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
331 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700332
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800333 const char* threads_property = post_bootcomplete
334 ? "dalvik.vm.dex2oat-threads"
335 : "dalvik.vm.boot-dex2oat-threads";
336 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700337
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000338 std::string bootclasspath;
339 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
340 if (dex2oat_bootclasspath != nullptr) {
341 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
342 }
343 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
344 // BOOTCLASSPATH.
345
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800346 const std::string dex2oat_isa_features_key =
347 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
348 std::string instruction_set_features_arg =
349 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700350
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800351 const std::string dex2oat_isa_variant_key =
352 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
353 std::string instruction_set_variant_arg =
354 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700355
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800356 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700357
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800358 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
359 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
360 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700361
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800362 // If we are booting without the real /data, don't spend time compiling.
363 std::string vold_decrypt = GetProperty("vold.decrypt", "");
364 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
365 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700366
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800367 std::string resolve_startup_string_arg =
368 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
369 "--resolve-startup-const-strings=%s");
370 if (resolve_startup_string_arg.empty()) {
371 // If empty, fall back to system property.
372 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800373 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
374 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800375 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800376
377 const std::string image_block_size_arg =
378 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
379 "--max-image-block-size=%s");
380
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800381 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700382
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800383 std::string image_format_arg;
384 if (image_fd >= 0) {
385 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000386 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388 std::string dex2oat_large_app_threshold_arg =
389 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000390
Calin Juravlef74a7372019-02-28 20:29:41 -0800391
392 const char* dex2oat_bin = select_execution_binary(
393 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000394
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800395 bool generate_minidebug_info = kEnableMinidebugInfo &&
396 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000397
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000398 std::string boot_image;
399 std::string use_apex_image =
400 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
401 ENABLE_APEX_IMAGE,
402 /*default_value=*/ "");
403 if (use_apex_image == "true") {
404 boot_image = StringPrintf("-Ximage:%s", kApexImage);
405 } else {
406 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
407 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000408
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800409 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
410 // use arraysize instead.
411 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
412 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
413 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
414 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
415 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
416 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
417 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
418 std::string dex2oat_compiler_filter_arg;
419 std::string dex2oat_swap_fd;
420 std::string dex2oat_image_fd;
421 std::string target_sdk_version_arg;
422 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000423 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800424 }
425 std::string class_loader_context_arg;
426 if (class_loader_context != nullptr) {
427 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
428 class_loader_context);
429 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000430
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800431 if (swap_fd >= 0) {
432 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
433 }
434 if (image_fd >= 0) {
435 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
436 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000437
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800438 // Compute compiler filter.
439 bool have_dex2oat_relocation_skip_flag = false;
440 if (skip_compilation) {
441 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
442 have_dex2oat_relocation_skip_flag = true;
443 } else if (compiler_filter != nullptr) {
444 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
445 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000446
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800447 if (dex2oat_compiler_filter_arg.empty()) {
448 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
449 "--compiler-filter=%s");
450 }
451
452 // Check whether all apps should be compiled debuggable.
453 if (!debuggable) {
454 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
455 }
456 std::string profile_arg;
457 if (profile_fd != -1) {
458 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
459 }
460
461 // Get the directory of the apk to pass as a base classpath directory.
462 std::string base_dir;
463 std::string apk_dir(input_file_name);
464 unsigned long dir_index = apk_dir.rfind('/');
465 bool has_base_dir = dir_index != std::string::npos;
466 if (has_base_dir) {
467 apk_dir = apk_dir.substr(0, dir_index);
468 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
469 }
470
471 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
472
473 std::string compilation_reason_arg = compilation_reason == nullptr
474 ? ""
475 : std::string("--compilation-reason=") + compilation_reason;
476
477 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
478
479 // Disable cdex if update input vdex is true since this combination of options is not
480 // supported.
481 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
482
483 AddArg(zip_fd_arg);
484 AddArg(zip_location_arg);
485 AddArg(input_vdex_fd_arg);
486 AddArg(output_vdex_fd_arg);
487 AddArg(oat_fd_arg);
488 AddArg(oat_location_arg);
489 AddArg(instruction_set_arg);
490
491 AddArg(instruction_set_variant_arg);
492 AddArg(instruction_set_features_arg);
493
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000494 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000495 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800496 AddRuntimeArg(dex2oat_Xms_arg);
497 AddRuntimeArg(dex2oat_Xmx_arg);
498
499 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800500 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800501 AddArg(dex2oat_compiler_filter_arg);
502 AddArg(dex2oat_threads_arg);
503 AddArg(dex2oat_swap_fd);
504 AddArg(dex2oat_image_fd);
505
506 if (generate_debug_info) {
507 AddArg("--generate-debug-info");
508 }
509 if (debuggable) {
510 AddArg("--debuggable");
511 }
512 AddArg(image_format_arg);
513 AddArg(dex2oat_large_app_threshold_arg);
514
515 if (have_dex2oat_relocation_skip_flag) {
516 AddRuntimeArg(dex2oat_norelocation);
517 }
518 AddArg(profile_arg);
519 AddArg(base_dir);
520 AddArg(class_loader_context_arg);
521 if (generate_minidebug_info) {
522 AddArg(kMinidebugDex2oatFlag);
523 }
524 if (disable_cdex) {
525 AddArg(kDisableCompactDexFlag);
526 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000527 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800528 if (enable_hidden_api_checks) {
529 AddRuntimeArg("-Xhidden-api-checks");
530 }
531
532 if (dex_metadata_fd > -1) {
533 AddArg(dex_metadata_fd_arg);
534 }
535
536 AddArg(compilation_reason_arg);
537
538 // Do not add args after dex2oat_flags, they should override others for debugging.
539 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
540
541 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000542 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800543};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700544
545/*
546 * Whether dexopt should use a swap file when compiling an APK.
547 *
548 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
549 * itself, anyways).
550 *
551 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
552 *
553 * Otherwise, return true if this is a low-mem device.
554 *
555 * Otherwise, return default value.
556 */
557static bool kAlwaysProvideSwapFile = false;
558static bool kDefaultProvideSwapFile = true;
559
560static bool ShouldUseSwapFileForDexopt() {
561 if (kAlwaysProvideSwapFile) {
562 return true;
563 }
564
565 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700566 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
567 if (!dex2oat_prop_buf.empty()) {
568 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700569 }
570
571 // Shortcut for default value. This is an implementation optimization for the process sketched
572 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
573 // as low-mem is never returning false. The compiler will optimize this away if it can.
574 if (kDefaultProvideSwapFile) {
575 return true;
576 }
577
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700578 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700579 return true;
580 }
581
582 // Default value must be false here.
583 return kDefaultProvideSwapFile;
584}
585
Richard Uhler76cc0272016-12-08 10:46:35 +0000586static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700587 if (set_to_bg) {
588 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800589 PLOG(ERROR) << "set_sched_policy failed";
590 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700591 }
592 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800593 PLOG(ERROR) << "setpriority failed";
594 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700595 }
596 }
597}
598
Calin Juravle29591732017-11-20 17:46:19 -0800599static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
600 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800601 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800602 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800603 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800604 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800605 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700606 }
Calin Juravle114f0812017-03-08 19:05:07 -0800607 // Profiles should belong to the app; make sure of that by giving ownership to
608 // the app uid. If we cannot do that, there's no point in returning the fd
609 // since dex2oat/profman will fail with SElinux denials.
610 if (fchown(fd.get(), uid, uid) < 0) {
611 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800612 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800613 }
Calin Juravle29591732017-11-20 17:46:19 -0800614 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800615}
616
Calin Juravle29591732017-11-20 17:46:19 -0800617static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800618 // Do not follow symlinks when opening a profile:
619 // - primary profiles should not contain symlinks in their paths
620 // - secondary dex paths should have been already resolved and validated
621 flags |= O_NOFOLLOW;
622
Calin Juravle29591732017-11-20 17:46:19 -0800623 // Check if we need to create the profile
624 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
625 unique_fd fd;
626 if ((flags & O_CREAT) != 0) {
627 fd = create_profile(uid, profile, flags);
628 } else {
629 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
630 }
631
Calin Juravle114f0812017-03-08 19:05:07 -0800632 if (fd.get() < 0) {
633 if (errno != ENOENT) {
634 // Profiles might be missing for various reasons. For example, in a
635 // multi-user environment, the profile directory for one user can be created
636 // after we start a merge. In this case the current profile for that user
637 // will not be found.
638 // Also, the secondary dex profiles might be deleted by the app at any time,
639 // so we can't we need to prepare if they are missing.
640 PLOG(ERROR) << "Failed to open profile " << profile;
641 }
642 return invalid_unique_fd();
643 }
644
Jeff Sharkey90aff262016-12-12 14:28:24 -0700645 return fd;
646}
647
Calin Juravle824a64d2018-01-18 20:23:17 -0800648static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
649 const std::string& location, bool is_secondary_dex) {
650 std::string profile = create_current_profile_path(user, package_name, location,
651 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800652 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800653}
654
Calin Juravle824a64d2018-01-18 20:23:17 -0800655static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
656 const std::string& location, bool read_write, bool is_secondary_dex) {
657 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800658 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
659}
660
661static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800662 const std::string& location) {
663 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800664 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800665}
666
Calin Juravle824a64d2018-01-18 20:23:17 -0800667static void open_profile_files(uid_t uid, const std::string& package_name,
668 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800669 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700670 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800671 *reference_profile_fd = open_reference_profile(uid, package_name, location,
672 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700673
Calin Juravle114f0812017-03-08 19:05:07 -0800674 // For secondary dex files, we don't really need the user but we use it for sanity checks.
675 // Note: the user owning the dex file should be the current user.
676 std::vector<userid_t> users;
677 if (is_secondary_dex){
678 users.push_back(multiuser_get_user_id(uid));
679 } else {
680 users = get_known_users(/*volume_uuid*/ nullptr);
681 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700682 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800683 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
684 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700685 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800686 if (profile_fd.get() >= 0) {
687 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700688 }
689 }
690}
691
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
693static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
694static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
695static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
696static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
697
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800698class RunProfman : public ExecVHelper {
699 public:
700 void SetupArgs(const std::vector<unique_fd>& profile_fds,
701 const unique_fd& reference_profile_fd,
702 const std::vector<unique_fd>& apk_fds,
703 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800704 bool copy_and_update,
705 bool store_aggregation_counters) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800706
707 // TODO(calin): Assume for now we run in the bg compile job (which is in
708 // most of the invocation). With the current data flow, is not very easy or
709 // clean to discover this in RunProfman (it will require quite a messy refactoring).
710 const char* profman_bin = select_execution_binary(
711 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800713 if (copy_and_update) {
714 CHECK_EQ(1u, profile_fds.size());
715 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000716 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800717 if (reference_profile_fd != -1) {
718 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000719 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800720
721 for (const unique_fd& fd : profile_fds) {
722 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
723 }
724
725 for (const unique_fd& fd : apk_fds) {
726 AddArg("--apk-fd=" + std::to_string(fd.get()));
727 }
728
729 for (const std::string& dex_location : dex_locations) {
730 AddArg("--dex-location=" + dex_location);
731 }
732
733 if (copy_and_update) {
734 AddArg("--copy-and-update-profile-key");
735 }
736
Calin Juravleb3a929d2018-12-11 14:40:00 -0800737 if (store_aggregation_counters) {
738 AddArg("--store-aggregation-counters");
739 }
740
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800741 // Do not add after dex2oat_flags, they should override others for debugging.
742 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800743 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700744
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800745 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
746 const unique_fd& reference_profile_fd,
747 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800748 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
749 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800750 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800751 reference_profile_fd,
752 apk_fds,
753 dex_locations,
754 /*copy_and_update=*/false,
755 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800756 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700757
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800758 void SetupCopyAndUpdate(unique_fd&& profile_fd,
759 unique_fd&& reference_profile_fd,
760 unique_fd&& apk_fd,
761 const std::string& dex_location) {
762 // The fds need to stay open longer than the scope of the function, so put them into a local
763 // variable vector.
764 profiles_fd_.push_back(std::move(profile_fd));
765 apk_fds_.push_back(std::move(apk_fd));
766 reference_profile_fd_ = std::move(reference_profile_fd);
767 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800768 SetupArgs(profiles_fd_,
769 reference_profile_fd_,
770 apk_fds_,
771 dex_locations,
772 /*copy_and_update=*/true,
773 /*store_aggregation_counters=*/false);
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,
787 /*copy_and_update=*/false,
788 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800789 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000790
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800791 void Exec() {
792 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
793 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000794
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800795 private:
796 unique_fd reference_profile_fd_;
797 std::vector<unique_fd> profiles_fd_;
798 std::vector<unique_fd> apk_fds_;
799};
Mathieu Chartier31636522018-11-09 23:53:07 +0000800
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800801
Calin Juravlef63d4792018-01-30 17:43:34 +0000802
Jeff Sharkey90aff262016-12-12 14:28:24 -0700803// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800804// The location is the package name for primary apks or the dex path for secondary dex files.
805// Returns true if there is enough information in the current profiles that makes it
806// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807// If the return value is true all the current profiles would have been merged into
808// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800809static bool analyze_profiles(uid_t uid, const std::string& package_name,
810 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800811 std::vector<unique_fd> profiles_fd;
812 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800813 open_profile_files(uid, package_name, location, is_secondary_dex,
814 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800815 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816 // Skip profile guided compilation because no profiles were found.
817 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700818 return false;
819 }
820
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800821 RunProfman profman_merge;
822 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700823 pid_t pid = fork();
824 if (pid == 0) {
825 /* child -- drop privileges before continuing */
826 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800827 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700828 }
829 /* parent */
830 int return_code = wait_child(pid);
831 bool need_to_compile = false;
832 bool should_clear_current_profiles = false;
833 bool should_clear_reference_profile = false;
834 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800835 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836 } else {
837 return_code = WEXITSTATUS(return_code);
838 switch (return_code) {
839 case PROFMAN_BIN_RETURN_CODE_COMPILE:
840 need_to_compile = true;
841 should_clear_current_profiles = true;
842 should_clear_reference_profile = false;
843 break;
844 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
845 need_to_compile = false;
846 should_clear_current_profiles = false;
847 should_clear_reference_profile = false;
848 break;
849 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800850 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700851 need_to_compile = false;
852 should_clear_current_profiles = true;
853 should_clear_reference_profile = true;
854 break;
855 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
856 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
857 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800858 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700859 need_to_compile = false;
860 should_clear_current_profiles = false;
861 should_clear_reference_profile = false;
862 break;
863 default:
864 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800865 LOG(WARNING) << "Unknown error code while processing profiles for location "
866 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867 need_to_compile = false;
868 should_clear_current_profiles = true;
869 should_clear_reference_profile = true;
870 break;
871 }
872 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800873
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800875 if (is_secondary_dex) {
876 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800877 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
878 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800879 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800880 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800881 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 }
883 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800884 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700885 }
886 return need_to_compile;
887}
888
Calin Juravle114f0812017-03-08 19:05:07 -0800889// Decides if profile guided compilation is needed or not based on existing profiles.
890// The analysis is done for the primary apks of the given package.
891// Returns true if there is enough information in the current profiles that makes it
892// worth to recompile the package.
893// If the return value is true all the current profiles would have been merged into
894// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800895bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
896 const std::string& profile_name) {
897 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800898}
899
Calin Juravle408cd4a2018-01-20 23:34:18 -0800900bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
901 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800902 std::vector<unique_fd> profile_fds;
903 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800904 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
905 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700906
Calin Juravle408cd4a2018-01-20 23:34:18 -0800907 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800908 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700909
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800910 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700911 const bool has_profiles = !profile_fds.empty();
912
913 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800914 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700915 return false;
916 }
917
Calin Juravle114f0812017-03-08 19:05:07 -0800918 unique_fd output_fd(open(out_file_name.c_str(),
919 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700920 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800921 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700922 return false;
923 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800924
Jeff Sharkey90aff262016-12-12 14:28:24 -0700925 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800926 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800927 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
928 if (apk_fd == -1) {
929 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
930 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700931 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800932 dex_locations.push_back(get_location_from_path(code_path.c_str()));
933 apk_fds.push_back(std::move(apk_fd));
934
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800936 RunProfman profman_dump;
937 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700938 pid_t pid = fork();
939 if (pid == 0) {
940 /* child -- drop privileges before continuing */
941 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800942 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700943 }
944 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700945 int return_code = wait_child(pid);
946 if (!WIFEXITED(return_code)) {
947 LOG(WARNING) << "profman failed for package " << pkgname << ": "
948 << return_code;
949 return false;
950 }
951 return true;
952}
953
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700954bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800955 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700956 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
957 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800958 package_name,
959 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700960 /*read_write*/ true,
961 /*secondary*/ false));
962 if (in_fd.get() < 0) {
963 PLOG(WARNING) << "Could not open profile " << system_profile;
964 return false;
965 }
966 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800967 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700968 return false;
969 }
970
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700971 // As a security measure we want to write the profile information with the reduced capabilities
972 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700973 pid_t pid = fork();
974 if (pid == 0) {
975 /* child -- drop privileges before continuing */
976 drop_capabilities(packageUid);
977
978 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
979 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800980 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700981 }
982 // This implies that the app owning this profile is running
983 // (and has acquired the lock).
984 //
985 // The app never acquires the lock for the reference profiles of primary apks.
986 // Only dex2oat from installd will do that. Since installd is single threaded
987 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800988 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700989 return false;
990 }
991
992 bool truncated = ftruncate(out_fd.get(), 0) == 0;
993 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800994 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700995 }
996
997 // Copy over data.
998 static constexpr size_t kBufferSize = 4 * 1024;
999 char buffer[kBufferSize];
1000 while (true) {
1001 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1002 if (bytes == 0) {
1003 break;
1004 }
1005 write(out_fd.get(), buffer, bytes);
1006 }
1007 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001008 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001009 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001010 // Use _exit since we don't want to run the global destructors in the child.
1011 // b/62597429
1012 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001013 }
1014 /* parent */
1015 int return_code = wait_child(pid);
1016 return return_code == 0;
1017}
1018
Jeff Sharkey90aff262016-12-12 14:28:24 -07001019static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1020 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1021 if (EndsWith(oat_path, ".dex")) {
1022 std::string new_path = oat_path;
1023 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001024 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001025 return new_path;
1026 }
1027
1028 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1029 // case (where the base name will have an extension for the B artifact).
1030 size_t odex_pos = oat_path.rfind(".odex");
1031 if (odex_pos != std::string::npos) {
1032 std::string new_path = oat_path;
1033 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1034 CHECK_NE(new_path.find(new_ext), std::string::npos);
1035 return new_path;
1036 }
1037
1038 // Don't know how to handle this.
1039 return "";
1040}
1041
1042// Translate the given oat path to an art (app image) path. An empty string
1043// denotes an error.
1044static std::string create_image_filename(const std::string& oat_path) {
1045 return replace_file_extension(oat_path, ".art");
1046}
1047
1048// Translate the given oat path to a vdex path. An empty string denotes an error.
1049static std::string create_vdex_filename(const std::string& oat_path) {
1050 return replace_file_extension(oat_path, ".vdex");
1051}
1052
Jeff Sharkey90aff262016-12-12 14:28:24 -07001053static int open_output_file(const char* file_name, bool recreate, int permissions) {
1054 int flags = O_RDWR | O_CREAT;
1055 if (recreate) {
1056 if (unlink(file_name) < 0) {
1057 if (errno != ENOENT) {
1058 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1059 }
1060 }
1061 flags |= O_EXCL;
1062 }
1063 return open(file_name, flags, permissions);
1064}
1065
Calin Juravle2289c0a2017-02-15 12:44:14 -08001066static bool set_permissions_and_ownership(
1067 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1068 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1069 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001070 if (fchmod(fd,
1071 S_IRUSR|S_IWUSR|S_IRGRP |
1072 (is_public ? S_IROTH : 0)) < 0) {
1073 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1074 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001075 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001076 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1077 return false;
1078 }
1079 return true;
1080}
1081
1082static bool IsOutputDalvikCache(const char* oat_dir) {
1083 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1084 // into '!'. Play it safe by handling it both.
1085 // TODO: ensure we never get null.
1086 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1087 return oat_dir == nullptr || oat_dir[0] == '!';
1088}
1089
Calin Juravled23dee72017-07-06 16:29:11 -07001090// Best-effort check whether we can fit the the path into our buffers.
1091// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1092// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1093// extension to the cache path (5 bytes).
1094// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1095static bool validate_dex_path_size(const std::string& dex_path) {
1096 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1097 LOG(ERROR) << "dex_path too long: " << dex_path;
1098 return false;
1099 }
1100 return true;
1101}
1102
Jeff Sharkey90aff262016-12-12 14:28:24 -07001103static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001104 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001105 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001106 return false;
1107 }
1108
1109 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001110 // Oat dirs for secondary dex files are already validated.
1111 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001112 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1113 return false;
1114 }
1115 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1116 return false;
1117 }
1118 } else {
1119 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1120 return false;
1121 }
1122 }
1123 return true;
1124}
1125
1126// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1127// on destruction. It will also run the given cleanup (unless told not to) after closing.
1128//
1129// Usage example:
1130//
Calin Juravle7a570e82017-01-14 16:23:30 -08001131// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132// [name]() {
1133// unlink(name.c_str());
1134// });
1135// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1136// wrapper if captured as a reference.
1137//
1138// if (file.get() == -1) {
1139// // Error opening...
1140// }
1141//
1142// ...
1143// if (error) {
1144// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1145// // and delete the file (after the fd is closed).
1146// return -1;
1147// }
1148//
1149// (Success case)
1150// file.SetCleanup(false);
1151// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1152// // (leaving the file around; after the fd is closed).
1153//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001154class Dex2oatFileWrapper {
1155 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 }
1158
Calin Juravle7a570e82017-01-14 16:23:30 -08001159 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1160 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1161
1162 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1163 value_ = other.value_;
1164 cleanup_ = other.cleanup_;
1165 do_cleanup_ = other.do_cleanup_;
1166 auto_close_ = other.auto_close_;
1167 other.release();
1168 }
1169
1170 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1171 value_ = other.value_;
1172 cleanup_ = other.cleanup_;
1173 do_cleanup_ = other.do_cleanup_;
1174 auto_close_ = other.auto_close_;
1175 other.release();
1176 return *this;
1177 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001178
1179 ~Dex2oatFileWrapper() {
1180 reset(-1);
1181 }
1182
1183 int get() {
1184 return value_;
1185 }
1186
1187 void SetCleanup(bool cleanup) {
1188 do_cleanup_ = cleanup;
1189 }
1190
1191 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001193 close(value_);
1194 }
1195 if (do_cleanup_ && cleanup_ != nullptr) {
1196 cleanup_();
1197 }
1198
1199 value_ = new_value;
1200 }
1201
Calin Juravle7a570e82017-01-14 16:23:30 -08001202 void reset(int new_value, std::function<void ()> new_cleanup) {
1203 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001204 close(value_);
1205 }
1206 if (do_cleanup_ && cleanup_ != nullptr) {
1207 cleanup_();
1208 }
1209
1210 value_ = new_value;
1211 cleanup_ = new_cleanup;
1212 }
1213
Calin Juravle7a570e82017-01-14 16:23:30 -08001214 void DisableAutoClose() {
1215 auto_close_ = false;
1216 }
1217
Jeff Sharkey90aff262016-12-12 14:28:24 -07001218 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001219 void release() {
1220 value_ = -1;
1221 do_cleanup_ = false;
1222 cleanup_ = nullptr;
1223 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001224 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001226 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001227 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001228};
1229
Calin Juravle7a570e82017-01-14 16:23:30 -08001230// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001231Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1232 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001233
1234 // We don't create an image for secondary dex files.
1235 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 return Dex2oatFileWrapper();
1237 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001238
Calin Juravle7a570e82017-01-14 16:23:30 -08001239 const std::string image_path = create_image_filename(out_oat_path);
1240 if (image_path.empty()) {
1241 // Happens when the out_oat_path has an unknown extension.
1242 return Dex2oatFileWrapper();
1243 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001244
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001245 // In case there is a stale image, remove it now. Ignore any error.
1246 unlink(image_path.c_str());
1247
1248 // Not enabled, exit.
1249 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001250 return Dex2oatFileWrapper();
1251 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001252 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1253 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001254 return Dex2oatFileWrapper();
1255 }
1256 // Recreate is true since we do not want to modify a mapped image. If the app is
1257 // already running and we modify the image file, it can cause crashes (b/27493510).
1258 Dex2oatFileWrapper wrapper_fd(
1259 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1260 [image_path]() { unlink(image_path.c_str()); });
1261 if (wrapper_fd.get() < 0) {
1262 // Could not create application image file. Go on since we can compile without it.
1263 LOG(ERROR) << "installd could not create '" << image_path
1264 << "' for image file during dexopt";
1265 // If we have a valid image file path but no image fd, explicitly erase the image file.
1266 if (unlink(image_path.c_str()) < 0) {
1267 if (errno != ENOENT) {
1268 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1269 }
1270 }
1271 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001272 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001273 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1274 wrapper_fd.reset(-1);
1275 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001276
Calin Juravle7a570e82017-01-14 16:23:30 -08001277 return wrapper_fd;
1278}
1279
1280// Creates the dexopt swap file if necessary and return its fd.
1281// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001282unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001283 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001284 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001285 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001286 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001287 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001288 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001289 if (swap_fd.get() < 0) {
1290 // Could not create swap file. Optimistically go on and hope that we can compile
1291 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001292 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 } else {
1294 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001295 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1297 }
1298 }
1299 return swap_fd;
1300}
1301
1302// Opens the reference profiles if needed.
1303// 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 -08001304Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001305 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001306 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001307 // If we are not profile guided compilation, or we are compiling system server
1308 // do not bother to open the profiles; we won't be using them.
1309 if (!profile_guided || (pkgname[0] == '*')) {
1310 return Dex2oatFileWrapper();
1311 }
1312
1313 // If this is a secondary dex path which is public do not open the profile.
1314 // We cannot compile public secondary dex paths with profiles. That's because
1315 // it will expose how the dex files are used by their owner.
1316 //
1317 // Note that the PackageManager is responsible to set the is_public flag for
1318 // primary apks and we do not check it here. In some cases, e.g. when
1319 // compiling with a public profile from the .dm file the PackageManager will
1320 // set is_public toghether with the profile guided compilation.
1321 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001322 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001323 }
Calin Juravle114f0812017-03-08 19:05:07 -08001324
1325 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001326 std::string location;
1327 if (is_secondary_dex) {
1328 location = dex_path;
1329 } else {
1330 if (profile_name == nullptr) {
1331 // This path is taken for system server re-compilation lunched from ZygoteInit.
1332 return Dex2oatFileWrapper();
1333 } else {
1334 location = profile_name;
1335 }
1336 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001337 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1338 is_secondary_dex);
1339 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1340 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001341 };
1342 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001343}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001344
Calin Juravle7a570e82017-01-14 16:23:30 -08001345// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1346// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001347bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001348 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001349 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001350 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1351 CHECK(in_vdex_wrapper_fd != nullptr);
1352 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001353 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1354 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001355 char in_odex_path[PKG_PATH_MAX];
1356 int dexopt_action = abs(dexopt_needed);
1357 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001358 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001359
1360 // Infer the name of the output VDEX.
1361 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1362 if (out_vdex_path_str.empty()) {
1363 return false;
1364 }
1365
1366 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001367 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001368 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1369 const char* path = nullptr;
1370 if (is_odex_location) {
1371 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1372 path = in_odex_path;
1373 } else {
1374 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001375 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001376 }
1377 } else {
1378 path = out_oat_path;
1379 }
1380 in_vdex_path_str = create_vdex_filename(path);
1381 if (in_vdex_path_str.empty()) {
1382 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001383 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001384 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001385 // We can update in place when all these conditions are met:
1386 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1387 // on /system typically cannot be updated in place).
1388 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1389 // cannot be currently used by a running process.
1390 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1391 // different vdex files to operate.
1392 update_vdex_in_place =
1393 (in_vdex_path_str == out_vdex_path_str) &&
1394 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1395 !profile_guided;
1396 if (update_vdex_in_place) {
1397 // Open the file read-write to be able to update it.
1398 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1399 if (in_vdex_wrapper_fd->get() == -1) {
1400 // If we failed to open the file, we cannot update it in place.
1401 update_vdex_in_place = false;
1402 }
1403 } else {
1404 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1405 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001406 }
1407
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001408 // If we are updating the vdex in place, we do not need to recreate a vdex,
1409 // and can use the same existing one.
1410 if (update_vdex_in_place) {
1411 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1412 // have bogus stale vdex files.
1413 out_vdex_wrapper_fd->reset(
1414 in_vdex_wrapper_fd->get(),
1415 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1416 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1417 // wrapper).
1418 in_vdex_wrapper_fd->DisableAutoClose();
1419 } else {
1420 out_vdex_wrapper_fd->reset(
1421 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1422 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1423 if (out_vdex_wrapper_fd->get() < 0) {
1424 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1425 return false;
1426 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001427 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001428 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001429 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001430 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1431 return false;
1432 }
1433
1434 // If we got here we successfully opened the vdex files.
1435 return true;
1436}
1437
1438// Opens the output oat file for the given apk.
1439// If successful it stores the output path into out_oat_path and returns true.
1440Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001441 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1442 char* out_oat_path) {
1443 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001444 return Dex2oatFileWrapper();
1445 }
1446 const std::string out_oat_path_str(out_oat_path);
1447 Dex2oatFileWrapper wrapper_fd(
1448 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1449 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1450 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001451 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001452 } else if (!set_permissions_and_ownership(
1453 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001454 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1455 wrapper_fd.reset(-1);
1456 }
1457 return wrapper_fd;
1458}
1459
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001460// Creates RDONLY fds for oat and vdex files, if exist.
1461// Returns false if it fails to create oat out path for the given apk path.
1462// Note that the method returns true even if the files could not be opened.
1463bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1464 const std::string& oat_dir,
1465 const std::string& instruction_set,
1466 bool is_secondary_dex,
1467 unique_fd* oat_file_fd,
1468 unique_fd* vdex_file_fd) {
1469 char oat_path[PKG_PATH_MAX];
1470 if (!create_oat_out_path(apk_path.c_str(),
1471 instruction_set.c_str(),
1472 oat_dir.c_str(),
1473 is_secondary_dex,
1474 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001475 LOG(ERROR) << "Could not create oat out path for "
1476 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001477 return false;
1478 }
1479 oat_file_fd->reset(open(oat_path, O_RDONLY));
1480 if (oat_file_fd->get() < 0) {
1481 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1482 }
1483
1484 std::string vdex_filename = create_vdex_filename(oat_path);
1485 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1486 if (vdex_file_fd->get() < 0) {
1487 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1488 }
1489
1490 return true;
1491}
1492
Calin Juravle7a570e82017-01-14 16:23:30 -08001493// Updates the access times of out_oat_path based on those from apk_path.
1494void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1495 struct stat input_stat;
1496 memset(&input_stat, 0, sizeof(input_stat));
1497 if (stat(apk_path, &input_stat) != 0) {
1498 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1499 return;
1500 }
1501
1502 struct utimbuf ut;
1503 ut.actime = input_stat.st_atime;
1504 ut.modtime = input_stat.st_mtime;
1505 if (utime(out_oat_path, &ut) != 0) {
1506 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1507 }
1508}
1509
Calin Juravle80a21252017-01-17 14:43:25 -08001510// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001511// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1512// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1513// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001514class RunDexoptAnalyzer : public ExecVHelper {
1515 public:
1516 RunDexoptAnalyzer(const std::string& dex_file,
1517 int vdex_fd,
1518 int oat_fd,
1519 int zip_fd,
1520 const std::string& instruction_set,
1521 const std::string& compiler_filter,
1522 bool profile_was_updated,
1523 bool downgrade,
1524 const char* class_loader_context) {
1525 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 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001543
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001544 // program name, dex file, isa, filter
1545 AddArg(dex_file_arg);
1546 AddArg(isa_arg);
1547 AddArg(compiler_filter_arg);
1548 if (oat_fd >= 0) {
1549 AddArg(oat_fd_arg);
1550 }
1551 if (vdex_fd >= 0) {
1552 AddArg(vdex_fd_arg);
1553 }
1554 AddArg(zip_fd_arg.c_str());
1555 if (profile_was_updated) {
1556 AddArg(assume_profile_changed);
1557 }
1558 if (downgrade) {
1559 AddArg(downgrade_flag);
1560 }
1561 if (class_loader_context != nullptr) {
1562 AddArg(class_loader_context_arg.c_str());
1563 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001564
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001565 PrepareArgs(dexoptanalyzer_bin);
1566 }
1567};
Calin Juravle80a21252017-01-17 14:43:25 -08001568
1569// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001570static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001571 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001572 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001573 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001574 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001575 return false;
1576 }
Calin Juravle114f0812017-03-08 19:05:07 -08001577 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001578
Calin Juravle80a21252017-01-17 14:43:25 -08001579 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001580 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1581 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001582 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001583 return false;
1584 }
1585
1586 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001587 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001588
Calin Juravle7d765462017-09-04 15:57:10 -07001589 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001590 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001591 return false;
1592 }
1593
1594 return true;
1595}
1596
Calin Juravle7d765462017-09-04 15:57:10 -07001597// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1598// secondary dex files. This return codes are returned by the child process created for
1599// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001600
Andreas Gampe194fe422018-02-28 20:16:19 -08001601enum DexoptAnalyzerSkipCodes {
1602 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001603 // Specific errors are encoded in the name.
1604 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1605 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1606 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1607 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1608 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001609 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001610 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001611};
Calin Juravle7d765462017-09-04 15:57:10 -07001612
1613// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001614// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1615// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001616// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1617// of dexoptanalyzer.
1618static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001619 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001620 // The result values are defined in dexoptanalyzer.
1621 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001622 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001623 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001624 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001625 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001626 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001627 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001628 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001629 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001630 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1631 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001632 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1633 " Expected odex file status for secondary dex %s"
1634 " : dexoptanalyzer result=%d",
1635 dex_path.c_str(),
1636 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001637 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001638 }
1639
1640 // Use a second switch for enum switch-case analysis.
1641 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001642 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001643 // If the file does not exist there's no need for dexopt.
1644 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1645 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001646
1647 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1648 *error_msg = "Dexoptanalyzer path validation failed";
1649 return false;
1650 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1651 *error_msg = "Dexoptanalyzer open zip failed";
1652 return false;
1653 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1654 *error_msg = "Dexoptanalyzer dir preparation failed";
1655 return false;
1656 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1657 *error_msg = "Dexoptanalyzer open output failed";
1658 return false;
1659 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1660 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001661 return false;
1662 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001663
1664 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1665 dex_path.c_str(),
1666 result);
1667 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001668}
1669
Calin Juravle7d765462017-09-04 15:57:10 -07001670enum SecondaryDexAccess {
1671 kSecondaryDexAccessReadOk = 0,
1672 kSecondaryDexAccessDoesNotExist = 1,
1673 kSecondaryDexAccessPermissionError = 2,
1674 kSecondaryDexAccessIOError = 3
1675};
1676
1677static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1678 // Check if the path exists and can be read. If not, there's nothing to do.
1679 if (access(dex_path.c_str(), R_OK) == 0) {
1680 return kSecondaryDexAccessReadOk;
1681 } else {
1682 if (errno == ENOENT) {
1683 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1684 return kSecondaryDexAccessDoesNotExist;
1685 } else {
1686 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1687 return errno == EACCES
1688 ? kSecondaryDexAccessPermissionError
1689 : kSecondaryDexAccessIOError;
1690 }
1691 }
1692}
1693
1694static bool is_file_public(const std::string& filename) {
1695 struct stat file_stat;
1696 if (stat(filename.c_str(), &file_stat) == 0) {
1697 return (file_stat.st_mode & S_IROTH) != 0;
1698 }
1699 return false;
1700}
1701
1702// Create the oat file structure for the secondary dex 'dex_path' and assign
1703// the individual path component to the 'out_' parameters.
1704static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001705 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001706 size_t dirIndex = dex_path.rfind('/');
1707 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001708 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001709 return false;
1710 }
1711 // TODO(calin): we have similar computations in at lest 3 other places
1712 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1713 // using string append.
1714 std::string apk_dir = dex_path.substr(0, dirIndex);
1715 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1716 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1717
1718 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1719 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001720 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001721 return false;
1722 }
1723 return true;
1724}
1725
1726// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1727// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001728static bool validate_dexopt_storage_flags(int dexopt_flags,
1729 int* out_storage_flag,
1730 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001731 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1732 *out_storage_flag = FLAG_STORAGE_CE;
1733 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001734 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001735 return false;
1736 }
1737 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1738 *out_storage_flag = FLAG_STORAGE_DE;
1739 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001740 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001741 return false;
1742 }
1743 return true;
1744}
1745
Calin Juravlec9eab382017-01-25 01:17:17 -08001746// 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 -08001747// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1748// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001749// When returning true, the output parameters will be:
1750// - is_public_out: whether or not the oat file should not be made public
1751// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1752// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001753static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001754 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001755 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001756 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1757 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001758 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001759 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001760 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1761 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001762 return false;
1763 }
Calin Juravle7d765462017-09-04 15:57:10 -07001764 // Compute the oat dir as it's not easy to extract it from the child computation.
1765 char oat_path[PKG_PATH_MAX];
1766 char oat_dir[PKG_PATH_MAX];
1767 char oat_isa_dir[PKG_PATH_MAX];
1768 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001769 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1770 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001771 return false;
1772 }
Calin Juravle7d765462017-09-04 15:57:10 -07001773 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001774
Calin Juravle80a21252017-01-17 14:43:25 -08001775 pid_t pid = fork();
1776 if (pid == 0) {
1777 // child -- drop privileges before continuing.
1778 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001779
1780 // Validate the path structure.
1781 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1782 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001783 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001784 }
1785
1786 // Open the dex file.
1787 unique_fd zip_fd;
1788 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1789 if (zip_fd.get() < 0) {
1790 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001791 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001792 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001793 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001794 }
1795 }
1796
1797 // Prepare the oat directories.
1798 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001799 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001800 }
1801
1802 // Open the vdex/oat files if any.
1803 unique_fd oat_file_fd;
1804 unique_fd vdex_file_fd;
1805 if (!maybe_open_oat_and_vdex_file(dex_path,
1806 *oat_dir_out,
1807 instruction_set,
1808 true /* is_secondary_dex */,
1809 &oat_file_fd,
1810 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001811 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001812 }
1813
1814 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001815 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1816 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001817
1818 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001819 // Note that we do not do it before the fork since opening the files is required to happen
1820 // after forking.
1821 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1822 vdex_file_fd.get(),
1823 oat_file_fd.get(),
1824 zip_fd.get(),
1825 instruction_set,
1826 compiler_filter, profile_was_updated,
1827 downgrade,
1828 class_loader_context);
1829 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001830 }
1831
1832 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001833 int result = wait_child(pid);
1834 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001835 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1836 dex_path.c_str(),
1837 result);
1838 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001839 return false;
1840 }
1841 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001842 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001843 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1844 result,
1845 dexopt_needed_out,
1846 error_msg);
1847 if (!success) {
1848 LOG(ERROR) << *error_msg;
1849 }
Calin Juravle7d765462017-09-04 15:57:10 -07001850
1851 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1852
Calin Juravle80a21252017-01-17 14:43:25 -08001853 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001854 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1855 // makes the code simpler; force compilation is only needed during tests).
1856 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001857 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001858 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001859 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1860 }
1861
Calin Juravle7d765462017-09-04 15:57:10 -07001862 // Check if we should make the oat file public.
1863 // Note that if the dex file is not public the compiled code cannot be made public.
1864 // It is ok to check this flag outside in the parent process.
1865 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1866
Calin Juravle80a21252017-01-17 14:43:25 -08001867 return success;
1868}
1869
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001870static std::string format_dexopt_error(int status, const char* dex_path) {
1871 if (WIFEXITED(status)) {
1872 int int_code = WEXITSTATUS(status);
1873 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1874 if (code_name != nullptr) {
1875 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1876 }
1877 }
1878 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001879}
1880
Calin Juravlec9eab382017-01-25 01:17:17 -08001881int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001882 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001883 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001884 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001885 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001886 CHECK(pkgname != nullptr);
1887 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001888 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001889 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1890 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001891
Calin Juravled23dee72017-07-06 16:29:11 -07001892 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001893 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001894 return -1;
1895 }
1896
1897 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001898 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1899 class_loader_context);
1900 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001901 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001902 }
1903
Calin Juravleebc8a792017-04-04 20:21:05 -07001904 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001905 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1906 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1907 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001908 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001909 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001910 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001911 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001912 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001913
1914 // Check if we're dealing with a secondary dex file and if we need to compile it.
1915 std::string oat_dir_str;
1916 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001917 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001918 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001919 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001920 oat_dir = oat_dir_str.c_str();
1921 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1922 return 0; // Nothing to do, report success.
1923 }
1924 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001925 if (error_msg->empty()) { // TODO: Make this a CHECK.
1926 *error_msg = "Failed processing secondary.";
1927 }
Calin Juravle80a21252017-01-17 14:43:25 -08001928 return -1; // We had an error, logged in the process method.
1929 }
1930 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001931 // Currently these flags are only use for secondary dex files.
1932 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001933 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1934 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1935 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001936
1937 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001938 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001939 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001940 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1941 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001942 return -1;
1943 }
1944
1945 // Create the output OAT file.
1946 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001947 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001948 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001949 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001950 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001951 return -1;
1952 }
1953
1954 // Open vdex files.
1955 Dex2oatFileWrapper in_vdex_fd;
1956 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001957 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1958 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001959 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001960 return -1;
1961 }
1962
Calin Juravlecb556e32017-04-04 20:22:50 -07001963 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1964 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1965 // fully inherit their parent context).
1966 // Note that for primary apk the oat files are created before, in a separate installd
1967 // call which also does the restorecon. TODO(calin): unify the paths.
1968 if (is_secondary_dex) {
1969 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1970 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001971 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1972 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001973 return -1;
1974 }
1975 }
1976
Jeff Sharkey90aff262016-12-12 14:28:24 -07001977 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001978 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001979
Calin Juravle7a570e82017-01-14 16:23:30 -08001980 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001981 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1982 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001983
Calin Juravle7a570e82017-01-14 16:23:30 -08001984 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001985 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001986 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001987
Calin Juravle62c5a372018-02-01 17:03:23 +00001988 unique_fd dex_metadata_fd;
1989 if (dex_metadata_path != nullptr) {
1990 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1991 if (dex_metadata_fd.get() < 0) {
1992 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1993 }
1994 }
1995
Andreas Gampe023b2242018-02-28 16:03:25 -08001996 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001997
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001998 RunDex2Oat runner(input_fd.get(),
1999 out_oat_fd.get(),
2000 in_vdex_fd.get(),
2001 out_vdex_fd.get(),
2002 image_fd.get(),
2003 dex_path,
2004 out_oat_path,
2005 swap_fd.get(),
2006 instruction_set,
2007 compiler_filter,
2008 debuggable,
2009 boot_complete,
2010 background_job_compile,
2011 reference_profile_fd.get(),
2012 class_loader_context,
2013 target_sdk_version,
2014 enable_hidden_api_checks,
2015 generate_compact_dex,
2016 dex_metadata_fd.get(),
2017 compilation_reason);
2018
Jeff Sharkey90aff262016-12-12 14:28:24 -07002019 pid_t pid = fork();
2020 if (pid == 0) {
2021 /* child -- drop privileges before continuing */
2022 drop_capabilities(uid);
2023
Richard Uhler76cc0272016-12-08 10:46:35 +00002024 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002025 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002026 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002027 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002028 }
2029
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002030 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002031 } else {
2032 int res = wait_child(pid);
2033 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002034 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002035 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002036 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2037 << std::hex << std::setw(4) << res << ", process failed";
2038 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002039 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002040 }
2041 }
2042
Calin Juravlec9eab382017-01-25 01:17:17 -08002043 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002044
2045 // We've been successful, don't delete output.
2046 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002047 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002048 image_fd.SetCleanup(false);
2049 reference_profile_fd.SetCleanup(false);
2050
2051 return 0;
2052}
2053
Calin Juravlec9eab382017-01-25 01:17:17 -08002054// Try to remove the given directory. Log an error if the directory exists
2055// and is empty but could not be removed.
2056static bool rmdir_if_empty(const char* dir) {
2057 if (rmdir(dir) == 0) {
2058 return true;
2059 }
2060 if (errno == ENOENT || errno == ENOTEMPTY) {
2061 return true;
2062 }
2063 PLOG(ERROR) << "Failed to remove dir: " << dir;
2064 return false;
2065}
2066
2067// Try to unlink the given file. Log an error if the file exists and could not
2068// be unlinked.
2069static bool unlink_if_exists(const std::string& file) {
2070 if (unlink(file.c_str()) == 0) {
2071 return true;
2072 }
2073 if (errno == ENOENT) {
2074 return true;
2075
2076 }
2077 PLOG(ERROR) << "Could not unlink: " << file;
2078 return false;
2079}
2080
Calin Juravle7d765462017-09-04 15:57:10 -07002081enum ReconcileSecondaryDexResult {
2082 kReconcileSecondaryDexExists = 0,
2083 kReconcileSecondaryDexCleanedUp = 1,
2084 kReconcileSecondaryDexValidationError = 2,
2085 kReconcileSecondaryDexCleanUpError = 3,
2086 kReconcileSecondaryDexAccessIOError = 4,
2087};
Calin Juravlec9eab382017-01-25 01:17:17 -08002088
2089// Reconcile the secondary dex 'dex_path' and its generated oat files.
2090// Return true if all the parameters are valid and the secondary dex file was
2091// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2092// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2093// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2094// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2095// Return false if there were errors during processing. In this case
2096// out_secondary_dex_exists will be set to false.
2097bool reconcile_secondary_dex_file(const std::string& dex_path,
2098 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2099 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2100 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002101 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002102 if (isas.size() == 0) {
2103 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2104 return false;
2105 }
2106
Calin Juravle7d765462017-09-04 15:57:10 -07002107 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2108 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2109 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002110 return false;
2111 }
2112
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002113 // As a security measure we want to unlink art artifacts with the reduced capabilities
2114 // of the package user id. So we fork and drop capabilities in the child.
2115 pid_t pid = fork();
2116 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002117 /* child -- drop privileges before continuing */
2118 drop_capabilities(uid);
2119
2120 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2121 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2122 uid, storage_flag)) {
2123 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2124 _exit(kReconcileSecondaryDexValidationError);
2125 }
2126
2127 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2128 switch (access_check) {
2129 case kSecondaryDexAccessDoesNotExist:
2130 // File does not exist. Proceed with cleaning.
2131 break;
2132 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2133 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2134 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2135 default:
2136 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2137 _exit(kReconcileSecondaryDexValidationError);
2138 }
2139
2140 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002141 char oat_path[PKG_PATH_MAX];
2142 char oat_dir[PKG_PATH_MAX];
2143 char oat_isa_dir[PKG_PATH_MAX];
2144 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002145 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002146 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002147 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002148 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2149 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002150 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002151 }
Calin Juravle51314092017-05-18 15:33:05 -07002152
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002153 // Delete oat/vdex/art files.
2154 result = unlink_if_exists(oat_path) && result;
2155 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2156 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002157
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002158 // Delete profiles.
2159 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002160 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002161 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002162 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002163 result = unlink_if_exists(current_profile) && result;
2164 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002165
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002166 // We upgraded once the location of current profile for secondary dex files.
2167 // Check for any previous left-overs and remove them as well.
2168 std::string old_current_profile = dex_path + ".prof";
2169 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002170
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002171 // Try removing the directories as well, they might be empty.
2172 result = rmdir_if_empty(oat_isa_dir) && result;
2173 result = rmdir_if_empty(oat_dir) && result;
2174 }
Calin Juravle7d765462017-09-04 15:57:10 -07002175 if (!result) {
2176 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2177 }
2178 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002179 }
2180
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002181 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002182 if (!WIFEXITED(return_code)) {
2183 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2184 } else {
2185 return_code = WEXITSTATUS(return_code);
2186 }
2187
2188 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2189
2190 switch (return_code) {
2191 case kReconcileSecondaryDexCleanedUp:
2192 case kReconcileSecondaryDexValidationError:
2193 // If we couldn't validate assume the dex file does not exist.
2194 // This will purge the entry from the PM records.
2195 *out_secondary_dex_exists = false;
2196 return true;
2197 case kReconcileSecondaryDexExists:
2198 *out_secondary_dex_exists = true;
2199 return true;
2200 case kReconcileSecondaryDexAccessIOError:
2201 // We had an access IO error.
2202 // Return false so that we can try again.
2203 // The value of out_secondary_dex_exists does not matter in this case and by convention
2204 // is set to false.
2205 *out_secondary_dex_exists = false;
2206 return false;
2207 default:
2208 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2209 *out_secondary_dex_exists = false;
2210 return false;
2211 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002212}
2213
Alan Stokesa25d90c2017-10-16 10:56:00 +01002214// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2215// Returns true if all parameters are valid and the hash successfully computed and stored in
2216// out_secondary_dex_hash.
2217// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2218// the app.
2219// For any other errors (e.g. if any of the parameters are invalid) returns false.
2220bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2221 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2222 std::vector<uint8_t>* out_secondary_dex_hash) {
2223 out_secondary_dex_hash->clear();
2224
2225 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2226
2227 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2228 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2229 << storage_flag;
2230 return false;
2231 }
2232
2233 // Pipe to get the hash result back from our child process.
2234 unique_fd pipe_read, pipe_write;
2235 if (!Pipe(&pipe_read, &pipe_write)) {
2236 PLOG(ERROR) << "Failed to create pipe";
2237 return false;
2238 }
2239
2240 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2241 // access data the app itself can access.
2242 pid_t pid = fork();
2243 if (pid == 0) {
2244 // child -- drop privileges before continuing
2245 drop_capabilities(uid);
2246 pipe_read.reset();
2247
2248 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2249 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002250 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002251 }
2252
2253 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2254 if (fd == -1) {
2255 if (errno == EACCES || errno == ENOENT) {
2256 // Not treated as an error.
2257 _exit(0);
2258 }
2259 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002260 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002261 }
2262
2263 SHA256_CTX ctx;
2264 SHA256_Init(&ctx);
2265
2266 std::vector<uint8_t> buffer(65536);
2267 while (true) {
2268 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2269 if (bytes_read == 0) {
2270 break;
2271 } else if (bytes_read == -1) {
2272 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002273 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002274 }
2275
2276 SHA256_Update(&ctx, buffer.data(), bytes_read);
2277 }
2278
2279 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2280 SHA256_Final(hash.data(), &ctx);
2281 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002282 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002283 }
2284
2285 _exit(0);
2286 }
2287
2288 // parent
2289 pipe_write.reset();
2290
2291 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2292 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2293 out_secondary_dex_hash->clear();
2294 }
2295 return wait_child(pid) == 0;
2296}
2297
Jeff Sharkey90aff262016-12-12 14:28:24 -07002298// Helper for move_ab, so that we can have common failure-case cleanup.
2299static bool unlink_and_rename(const char* from, const char* to) {
2300 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2301 // return a failure.
2302 struct stat s;
2303 if (stat(to, &s) == 0) {
2304 if (!S_ISREG(s.st_mode)) {
2305 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2306 return false;
2307 }
2308 if (unlink(to) != 0) {
2309 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2310 return false;
2311 }
2312 } else {
2313 // This may be a permission problem. We could investigate the error code, but we'll just
2314 // let the rename failure do the work for us.
2315 }
2316
2317 // Try to rename "to" to "from."
2318 if (rename(from, to) != 0) {
2319 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2320 return false;
2321 }
2322 return true;
2323}
2324
2325// Move/rename a B artifact (from) to an A artifact (to).
2326static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2327 // Check whether B exists.
2328 {
2329 struct stat s;
2330 if (stat(b_path.c_str(), &s) != 0) {
2331 // Silently ignore for now. The service calling this isn't smart enough to understand
2332 // lack of artifacts at the moment.
2333 return false;
2334 }
2335 if (!S_ISREG(s.st_mode)) {
2336 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2337 // Try to unlink, but swallow errors.
2338 unlink(b_path.c_str());
2339 return false;
2340 }
2341 }
2342
2343 // Rename B to A.
2344 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2345 // Delete the b_path so we don't try again (or fail earlier).
2346 if (unlink(b_path.c_str()) != 0) {
2347 PLOG(ERROR) << "Could not unlink " << b_path;
2348 }
2349
2350 return false;
2351 }
2352
2353 return true;
2354}
2355
2356bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2357 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002358 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2359 if (slot_suffix.empty()) {
2360 return false;
2361 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002362
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002363 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2364 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2365 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002366 }
2367
2368 // Validate other inputs.
2369 if (validate_apk_path(apk_path) != 0) {
2370 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2371 return false;
2372 }
2373 if (validate_apk_path(oat_dir) != 0) {
2374 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2375 return false;
2376 }
2377
2378 char a_path[PKG_PATH_MAX];
2379 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2380 return false;
2381 }
2382 const std::string a_vdex_path = create_vdex_filename(a_path);
2383 const std::string a_image_path = create_image_filename(a_path);
2384
2385 // B path = A path + slot suffix.
2386 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2387 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2388 const std::string b_image_path = StringPrintf("%s.%s",
2389 a_image_path.c_str(),
2390 slot_suffix.c_str());
2391
2392 bool success = true;
2393 if (move_ab_path(b_path, a_path)) {
2394 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2395 // Note: we can live without an app image. As such, ignore failure to move the image file.
2396 // If we decide to require the app image, or the app image being moved correctly,
2397 // then change accordingly.
2398 constexpr bool kIgnoreAppImageFailure = true;
2399
2400 if (!a_image_path.empty()) {
2401 if (!move_ab_path(b_image_path, a_image_path)) {
2402 unlink(a_image_path.c_str());
2403 if (!kIgnoreAppImageFailure) {
2404 success = false;
2405 }
2406 }
2407 }
2408 } else {
2409 // Cleanup: delete B image, ignore errors.
2410 unlink(b_image_path.c_str());
2411 success = false;
2412 }
2413 } else {
2414 // Cleanup: delete B image, ignore errors.
2415 unlink(b_vdex_path.c_str());
2416 unlink(b_image_path.c_str());
2417 success = false;
2418 }
2419 return success;
2420}
2421
2422bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2423 // Delete the oat/odex file.
2424 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002425 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002426 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002427 return false;
2428 }
2429
2430 // In case of a permission failure report the issue. Otherwise just print a warning.
2431 auto unlink_and_check = [](const char* path) -> bool {
2432 int result = unlink(path);
2433 if (result != 0) {
2434 if (errno == EACCES || errno == EPERM) {
2435 PLOG(ERROR) << "Could not unlink " << path;
2436 return false;
2437 }
2438 PLOG(WARNING) << "Could not unlink " << path;
2439 }
2440 return true;
2441 };
2442
2443 // Delete the oat/odex file.
2444 bool return_value_oat = unlink_and_check(out_path);
2445
2446 // Derive and delete the app image.
2447 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2448
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002449 // Derive and delete the vdex file.
2450 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2451
Jeff Sharkey90aff262016-12-12 14:28:24 -07002452 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002453 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002454}
2455
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002456static bool is_absolute_path(const std::string& path) {
2457 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2458 LOG(ERROR) << "Invalid absolute path " << path;
2459 return false;
2460 } else {
2461 return true;
2462 }
2463}
2464
2465static bool is_valid_instruction_set(const std::string& instruction_set) {
2466 // TODO: add explicit whitelisting of instruction sets
2467 if (instruction_set.find('/') != std::string::npos) {
2468 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2469 return false;
2470 } else {
2471 return true;
2472 }
2473}
2474
2475bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2476 const char *apk_path, const char *instruction_set) {
2477 std::string oat_dir_ = oat_dir;
2478 std::string apk_path_ = apk_path;
2479 std::string instruction_set_ = instruction_set;
2480
2481 if (!is_absolute_path(oat_dir_)) return false;
2482 if (!is_absolute_path(apk_path_)) return false;
2483 if (!is_valid_instruction_set(instruction_set_)) return false;
2484
2485 std::string::size_type end = apk_path_.rfind('.');
2486 std::string::size_type start = apk_path_.rfind('/', end);
2487 if (end == std::string::npos || start == std::string::npos) {
2488 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2489 return false;
2490 }
2491
2492 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2493 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2494 const char* res = res_.c_str();
2495 if (strlen(res) >= PKG_PATH_MAX) {
2496 LOG(ERROR) << "Result too large";
2497 return false;
2498 } else {
2499 strlcpy(path, res, PKG_PATH_MAX);
2500 return true;
2501 }
2502}
2503
2504bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2505 const char *instruction_set) {
2506 std::string apk_path_ = apk_path;
2507 std::string instruction_set_ = instruction_set;
2508
2509 if (!is_absolute_path(apk_path_)) return false;
2510 if (!is_valid_instruction_set(instruction_set_)) return false;
2511
2512 std::string::size_type end = apk_path_.rfind('.');
2513 std::string::size_type start = apk_path_.rfind('/', end);
2514 if (end == std::string::npos || start == std::string::npos) {
2515 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2516 return false;
2517 }
2518
2519 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2520 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2521}
2522
2523bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2524 const char *instruction_set) {
2525 std::string src_ = src;
2526 std::string instruction_set_ = instruction_set;
2527
2528 if (!is_absolute_path(src_)) return false;
2529 if (!is_valid_instruction_set(instruction_set_)) return false;
2530
2531 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2532 if (*it == '/') {
2533 *it = '@';
2534 }
2535 }
2536
2537 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2538 + DALVIK_CACHE_POSTFIX;
2539 const char* res = res_.c_str();
2540 if (strlen(res) >= PKG_PATH_MAX) {
2541 LOG(ERROR) << "Result too large";
2542 return false;
2543 } else {
2544 strlcpy(path, res, PKG_PATH_MAX);
2545 return true;
2546 }
2547}
2548
Calin Juravle59f7ab82018-04-27 17:50:23 -07002549bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2550 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002551 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2552 for (const std::string& elem : classpaths_elems) {
2553 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2554 if (fd < 0) {
2555 PLOG(ERROR) << "Could not open classpath elem " << elem;
2556 return false;
2557 } else {
2558 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002559 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002560 }
2561 }
2562 return true;
2563}
2564
2565static bool create_app_profile_snapshot(int32_t app_id,
2566 const std::string& package_name,
2567 const std::string& profile_name,
2568 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002569 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2570
Calin Juravle824a64d2018-01-18 20:23:17 -08002571 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002572 if (snapshot_fd < 0) {
2573 return false;
2574 }
2575
2576 std::vector<unique_fd> profiles_fd;
2577 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002578 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2579 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002580 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2581 return false;
2582 }
2583
2584 profiles_fd.push_back(std::move(reference_profile_fd));
2585
Calin Juravle0d0a4922018-01-23 19:54:11 -08002586 // Open the class paths elements. These will be used to filter out profile data that does
2587 // not belong to the classpath during merge.
2588 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002589 std::vector<std::string> dex_locations;
2590 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002591 return false;
2592 }
2593
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002594 RunProfman args;
2595 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002596 pid_t pid = fork();
2597 if (pid == 0) {
2598 /* child -- drop privileges before continuing */
2599 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002600 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002601 }
2602
2603 /* parent */
2604 int return_code = wait_child(pid);
2605 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002606 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002607 return false;
2608 }
2609
2610 return true;
2611}
2612
Calin Juravle0d0a4922018-01-23 19:54:11 -08002613static bool create_boot_image_profile_snapshot(const std::string& package_name,
2614 const std::string& profile_name,
2615 const std::string& classpath) {
2616 // The reference profile directory for the android package might not be prepared. Do it now.
2617 const std::string ref_profile_dir =
2618 create_primary_reference_profile_package_dir_path(package_name);
2619 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2620 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2621 return false;
2622 }
2623
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002624 // Return false for empty class path since it may otherwise return true below if profiles is
2625 // empty.
2626 if (classpath.empty()) {
2627 PLOG(ERROR) << "Class path is empty";
2628 return false;
2629 }
2630
Calin Juravle0d0a4922018-01-23 19:54:11 -08002631 // Open and create the snapshot profile.
2632 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2633
2634 // Collect all non empty profiles.
2635 // The collection will traverse all applications profiles and find the non empty files.
2636 // This has the potential of inspecting a large number of files and directories (depending
2637 // on the number of applications and users). So there is a slight increase in the chance
2638 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2639 // fail the snapshot and aggregate whatever profile we could open.
2640 //
2641 // The profile snapshot is a best effort based on available data it's ok if some data
2642 // from some apps is missing. It will be counter productive for the snapshot to fail
2643 // because we could not open or read some of the files.
2644 std::vector<std::string> profiles;
2645 if (!collect_profiles(&profiles)) {
2646 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2647 }
2648
2649 // If we have no profiles return early.
2650 if (profiles.empty()) {
2651 return true;
2652 }
2653
2654 // Open the classpath elements. These will be used to filter out profile data that does
2655 // not belong to the classpath during merge.
2656 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002657 std::vector<std::string> dex_locations;
2658 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002659 return false;
2660 }
2661
2662 // If we could not open any files from the classpath return an error.
2663 if (apk_fds.empty()) {
2664 LOG(ERROR) << "Could not open any of the classpath elements.";
2665 return false;
2666 }
2667
2668 // Aggregate the profiles in batches of kAggregationBatchSize.
2669 // We do this to avoid opening a huge a amount of files.
2670 static constexpr size_t kAggregationBatchSize = 10;
2671
2672 std::vector<unique_fd> profiles_fd;
2673 for (size_t i = 0; i < profiles.size(); ) {
2674 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2675 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2676 if (fd.get() >= 0) {
2677 profiles_fd.push_back(std::move(fd));
2678 }
2679 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002680 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002681 args.SetupMerge(profiles_fd,
2682 snapshot_fd,
2683 apk_fds,
2684 dex_locations,
2685 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002686 pid_t pid = fork();
2687 if (pid == 0) {
2688 /* child -- drop privileges before continuing */
2689 drop_capabilities(AID_SYSTEM);
2690
Calin Juravle59f7ab82018-04-27 17:50:23 -07002691 // The introduction of new access flags into boot jars causes them to
2692 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002693 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002694 }
2695
2696 /* parent */
2697 int return_code = wait_child(pid);
2698 if (!WIFEXITED(return_code)) {
2699 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2700 return false;
2701 }
2702 return true;
2703 }
2704 return true;
2705}
2706
2707bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2708 const std::string& profile_name, const std::string& classpath) {
2709 if (app_id == -1) {
2710 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2711 } else {
2712 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2713 }
2714}
2715
Calin Juravlec3b049e2018-01-18 22:32:58 -08002716bool prepare_app_profile(const std::string& package_name,
2717 userid_t user_id,
2718 appid_t app_id,
2719 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002720 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002721 const std::unique_ptr<std::string>& dex_metadata) {
2722 // Prepare the current profile.
2723 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2724 /*is_secondary_dex*/ false);
2725 uid_t uid = multiuser_get_uid(user_id, app_id);
2726 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2727 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2728 return false;
2729 }
2730
2731 // Check if we need to install the profile from the dex metadata.
2732 if (dex_metadata == nullptr) {
2733 return true;
2734 }
2735
2736 // We have a dex metdata. Merge the profile into the reference profile.
2737 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2738 /*read_write*/ true, /*is_secondary_dex*/ false);
2739 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2740 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002741 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2742 if (apk_fd < 0) {
2743 PLOG(ERROR) << "Could not open code path " << code_path;
2744 return false;
2745 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002746
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002747 RunProfman args;
2748 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2749 std::move(ref_profile_fd),
2750 std::move(apk_fd),
2751 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002752 pid_t pid = fork();
2753 if (pid == 0) {
2754 /* child -- drop privileges before continuing */
2755 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2756 drop_capabilities(app_shared_gid);
2757
Calin Juravlef63d4792018-01-30 17:43:34 +00002758 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002759 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002760 }
2761
2762 /* parent */
2763 int return_code = wait_child(pid);
2764 if (!WIFEXITED(return_code)) {
2765 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2766 return false;
2767 }
2768 return true;
2769}
2770
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002771} // namespace installd
2772} // namespace android