blob: f523725e7b03f5e80668befe18ba1f927ebd4d01 [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
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000264// Namespace for Android Runtime flags applied during boot time.
265static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
266// Feature flag name for running the JIT in Zygote experiment, b/119800099.
267static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
268// Location of the apex image.
269static const char* kApexImage = "/system/framework/apex.art";
270
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800271class RunDex2Oat : public ExecVHelper {
272 public:
273 RunDex2Oat(int zip_fd,
274 int oat_fd,
275 int input_vdex_fd,
276 int output_vdex_fd,
277 int image_fd,
278 const char* input_file_name,
279 const char* output_file_name,
280 int swap_fd,
281 const char* instruction_set,
282 const char* compiler_filter,
283 bool debuggable,
284 bool post_bootcomplete,
285 bool background_job_compile,
286 int profile_fd,
287 const char* class_loader_context,
288 int target_sdk_version,
289 bool enable_hidden_api_checks,
290 bool generate_compact_dex,
291 int dex_metadata_fd,
292 const char* compilation_reason) {
293 // Get the relative path to the input file.
294 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700295
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800296 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
297 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700298
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800299 const char* threads_property = post_bootcomplete
300 ? "dalvik.vm.dex2oat-threads"
301 : "dalvik.vm.boot-dex2oat-threads";
302 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700303
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000304 std::string bootclasspath;
305 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
306 if (dex2oat_bootclasspath != nullptr) {
307 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
308 }
309 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
310 // BOOTCLASSPATH.
311
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800312 const std::string dex2oat_isa_features_key =
313 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
314 std::string instruction_set_features_arg =
315 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700316
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800317 const std::string dex2oat_isa_variant_key =
318 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
319 std::string instruction_set_variant_arg =
320 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700321
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800322 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700323
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800324 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
325 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
326 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700327
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800328 // If we are booting without the real /data, don't spend time compiling.
329 std::string vold_decrypt = GetProperty("vold.decrypt", "");
330 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
331 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700332
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800333 std::string resolve_startup_string_arg =
334 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
335 "--resolve-startup-const-strings=%s");
336 if (resolve_startup_string_arg.empty()) {
337 // If empty, fall back to system property.
338 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800339 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
340 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800341 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800342
343 const std::string image_block_size_arg =
344 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
345 "--max-image-block-size=%s");
346
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800347 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 std::string image_format_arg;
350 if (image_fd >= 0) {
351 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000352 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000353
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800354 std::string dex2oat_large_app_threshold_arg =
355 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000356
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800357 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
Roland Levillain67a14f62019-01-23 15:59:50 +0000358 const char* dex2oat_bin = kDex2oatPath;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800359 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
360 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
361 if (is_debug_runtime() ||
362 (background_job_compile && is_debuggable_build() && !is_release)) {
363 if (access(kDex2oatDebugPath, X_OK) == 0) {
364 dex2oat_bin = kDex2oatDebugPath;
365 }
366 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000367
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800368 bool generate_minidebug_info = kEnableMinidebugInfo &&
369 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000370
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000371 std::string boot_image;
372 std::string use_apex_image =
373 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
374 ENABLE_APEX_IMAGE,
375 /*default_value=*/ "");
376 if (use_apex_image == "true") {
377 boot_image = StringPrintf("-Ximage:%s", kApexImage);
378 } else {
379 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
380 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000381
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800382 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
383 // use arraysize instead.
384 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
385 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
386 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
387 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
388 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
389 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
390 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
391 std::string dex2oat_compiler_filter_arg;
392 std::string dex2oat_swap_fd;
393 std::string dex2oat_image_fd;
394 std::string target_sdk_version_arg;
395 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000396 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800397 }
398 std::string class_loader_context_arg;
399 if (class_loader_context != nullptr) {
400 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
401 class_loader_context);
402 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000403
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800404 if (swap_fd >= 0) {
405 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
406 }
407 if (image_fd >= 0) {
408 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
409 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000410
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800411 // Compute compiler filter.
412 bool have_dex2oat_relocation_skip_flag = false;
413 if (skip_compilation) {
414 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
415 have_dex2oat_relocation_skip_flag = true;
416 } else if (compiler_filter != nullptr) {
417 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
418 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000419
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800420 if (dex2oat_compiler_filter_arg.empty()) {
421 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
422 "--compiler-filter=%s");
423 }
424
425 // Check whether all apps should be compiled debuggable.
426 if (!debuggable) {
427 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
428 }
429 std::string profile_arg;
430 if (profile_fd != -1) {
431 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
432 }
433
434 // Get the directory of the apk to pass as a base classpath directory.
435 std::string base_dir;
436 std::string apk_dir(input_file_name);
437 unsigned long dir_index = apk_dir.rfind('/');
438 bool has_base_dir = dir_index != std::string::npos;
439 if (has_base_dir) {
440 apk_dir = apk_dir.substr(0, dir_index);
441 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
442 }
443
444 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
445
446 std::string compilation_reason_arg = compilation_reason == nullptr
447 ? ""
448 : std::string("--compilation-reason=") + compilation_reason;
449
450 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
451
452 // Disable cdex if update input vdex is true since this combination of options is not
453 // supported.
454 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
455
456 AddArg(zip_fd_arg);
457 AddArg(zip_location_arg);
458 AddArg(input_vdex_fd_arg);
459 AddArg(output_vdex_fd_arg);
460 AddArg(oat_fd_arg);
461 AddArg(oat_location_arg);
462 AddArg(instruction_set_arg);
463
464 AddArg(instruction_set_variant_arg);
465 AddArg(instruction_set_features_arg);
466
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000467 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000468 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800469 AddRuntimeArg(dex2oat_Xms_arg);
470 AddRuntimeArg(dex2oat_Xmx_arg);
471
472 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800473 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800474 AddArg(dex2oat_compiler_filter_arg);
475 AddArg(dex2oat_threads_arg);
476 AddArg(dex2oat_swap_fd);
477 AddArg(dex2oat_image_fd);
478
479 if (generate_debug_info) {
480 AddArg("--generate-debug-info");
481 }
482 if (debuggable) {
483 AddArg("--debuggable");
484 }
485 AddArg(image_format_arg);
486 AddArg(dex2oat_large_app_threshold_arg);
487
488 if (have_dex2oat_relocation_skip_flag) {
489 AddRuntimeArg(dex2oat_norelocation);
490 }
491 AddArg(profile_arg);
492 AddArg(base_dir);
493 AddArg(class_loader_context_arg);
494 if (generate_minidebug_info) {
495 AddArg(kMinidebugDex2oatFlag);
496 }
497 if (disable_cdex) {
498 AddArg(kDisableCompactDexFlag);
499 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000500 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800501 if (enable_hidden_api_checks) {
502 AddRuntimeArg("-Xhidden-api-checks");
503 }
504
505 if (dex_metadata_fd > -1) {
506 AddArg(dex_metadata_fd_arg);
507 }
508
509 AddArg(compilation_reason_arg);
510
511 // Do not add args after dex2oat_flags, they should override others for debugging.
512 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
513
514 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000515 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800516};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700517
518/*
519 * Whether dexopt should use a swap file when compiling an APK.
520 *
521 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
522 * itself, anyways).
523 *
524 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
525 *
526 * Otherwise, return true if this is a low-mem device.
527 *
528 * Otherwise, return default value.
529 */
530static bool kAlwaysProvideSwapFile = false;
531static bool kDefaultProvideSwapFile = true;
532
533static bool ShouldUseSwapFileForDexopt() {
534 if (kAlwaysProvideSwapFile) {
535 return true;
536 }
537
538 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700539 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
540 if (!dex2oat_prop_buf.empty()) {
541 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700542 }
543
544 // Shortcut for default value. This is an implementation optimization for the process sketched
545 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
546 // as low-mem is never returning false. The compiler will optimize this away if it can.
547 if (kDefaultProvideSwapFile) {
548 return true;
549 }
550
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700551 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552 return true;
553 }
554
555 // Default value must be false here.
556 return kDefaultProvideSwapFile;
557}
558
Richard Uhler76cc0272016-12-08 10:46:35 +0000559static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700560 if (set_to_bg) {
561 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800562 PLOG(ERROR) << "set_sched_policy failed";
563 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700564 }
565 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800566 PLOG(ERROR) << "setpriority failed";
567 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700568 }
569 }
570}
571
Calin Juravle29591732017-11-20 17:46:19 -0800572static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
573 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800574 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800575 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800576 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800577 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800578 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700579 }
Calin Juravle114f0812017-03-08 19:05:07 -0800580 // Profiles should belong to the app; make sure of that by giving ownership to
581 // the app uid. If we cannot do that, there's no point in returning the fd
582 // since dex2oat/profman will fail with SElinux denials.
583 if (fchown(fd.get(), uid, uid) < 0) {
584 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800585 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800586 }
Calin Juravle29591732017-11-20 17:46:19 -0800587 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800588}
589
Calin Juravle29591732017-11-20 17:46:19 -0800590static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800591 // Do not follow symlinks when opening a profile:
592 // - primary profiles should not contain symlinks in their paths
593 // - secondary dex paths should have been already resolved and validated
594 flags |= O_NOFOLLOW;
595
Calin Juravle29591732017-11-20 17:46:19 -0800596 // Check if we need to create the profile
597 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
598 unique_fd fd;
599 if ((flags & O_CREAT) != 0) {
600 fd = create_profile(uid, profile, flags);
601 } else {
602 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
603 }
604
Calin Juravle114f0812017-03-08 19:05:07 -0800605 if (fd.get() < 0) {
606 if (errno != ENOENT) {
607 // Profiles might be missing for various reasons. For example, in a
608 // multi-user environment, the profile directory for one user can be created
609 // after we start a merge. In this case the current profile for that user
610 // will not be found.
611 // Also, the secondary dex profiles might be deleted by the app at any time,
612 // so we can't we need to prepare if they are missing.
613 PLOG(ERROR) << "Failed to open profile " << profile;
614 }
615 return invalid_unique_fd();
616 }
617
Jeff Sharkey90aff262016-12-12 14:28:24 -0700618 return fd;
619}
620
Calin Juravle824a64d2018-01-18 20:23:17 -0800621static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
622 const std::string& location, bool is_secondary_dex) {
623 std::string profile = create_current_profile_path(user, package_name, location,
624 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800625 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800626}
627
Calin Juravle824a64d2018-01-18 20:23:17 -0800628static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
629 const std::string& location, bool read_write, bool is_secondary_dex) {
630 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800631 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
632}
633
634static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800635 const std::string& location) {
636 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800637 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800638}
639
Calin Juravle824a64d2018-01-18 20:23:17 -0800640static void open_profile_files(uid_t uid, const std::string& package_name,
641 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800642 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700643 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800644 *reference_profile_fd = open_reference_profile(uid, package_name, location,
645 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646
Calin Juravle114f0812017-03-08 19:05:07 -0800647 // For secondary dex files, we don't really need the user but we use it for sanity checks.
648 // Note: the user owning the dex file should be the current user.
649 std::vector<userid_t> users;
650 if (is_secondary_dex){
651 users.push_back(multiuser_get_user_id(uid));
652 } else {
653 users = get_known_users(/*volume_uuid*/ nullptr);
654 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700655 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800656 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
657 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700658 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800659 if (profile_fd.get() >= 0) {
660 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 }
662 }
663}
664
Jeff Sharkey90aff262016-12-12 14:28:24 -0700665static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
666static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
667static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
668static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
669static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
670
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800671class RunProfman : public ExecVHelper {
672 public:
673 void SetupArgs(const std::vector<unique_fd>& profile_fds,
674 const unique_fd& reference_profile_fd,
675 const std::vector<unique_fd>& apk_fds,
676 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800677 bool copy_and_update,
678 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000679 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700680
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800681 if (copy_and_update) {
682 CHECK_EQ(1u, profile_fds.size());
683 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000684 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800685 if (reference_profile_fd != -1) {
686 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000687 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800688
689 for (const unique_fd& fd : profile_fds) {
690 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
691 }
692
693 for (const unique_fd& fd : apk_fds) {
694 AddArg("--apk-fd=" + std::to_string(fd.get()));
695 }
696
697 for (const std::string& dex_location : dex_locations) {
698 AddArg("--dex-location=" + dex_location);
699 }
700
701 if (copy_and_update) {
702 AddArg("--copy-and-update-profile-key");
703 }
704
Calin Juravleb3a929d2018-12-11 14:40:00 -0800705 if (store_aggregation_counters) {
706 AddArg("--store-aggregation-counters");
707 }
708
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800709 // Do not add after dex2oat_flags, they should override others for debugging.
710 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800711 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800713 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
714 const unique_fd& reference_profile_fd,
715 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800716 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
717 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800718 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800719 reference_profile_fd,
720 apk_fds,
721 dex_locations,
722 /*copy_and_update=*/false,
723 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800724 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700725
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800726 void SetupCopyAndUpdate(unique_fd&& profile_fd,
727 unique_fd&& reference_profile_fd,
728 unique_fd&& apk_fd,
729 const std::string& dex_location) {
730 // The fds need to stay open longer than the scope of the function, so put them into a local
731 // variable vector.
732 profiles_fd_.push_back(std::move(profile_fd));
733 apk_fds_.push_back(std::move(apk_fd));
734 reference_profile_fd_ = std::move(reference_profile_fd);
735 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800736 SetupArgs(profiles_fd_,
737 reference_profile_fd_,
738 apk_fds_,
739 dex_locations,
740 /*copy_and_update=*/true,
741 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800742 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000743
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800744 void SetupDump(const std::vector<unique_fd>& profiles_fd,
745 const unique_fd& reference_profile_fd,
746 const std::vector<std::string>& dex_locations,
747 const std::vector<unique_fd>& apk_fds,
748 const unique_fd& output_fd) {
749 AddArg("--dump-only");
750 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800751 SetupArgs(profiles_fd,
752 reference_profile_fd,
753 apk_fds,
754 dex_locations,
755 /*copy_and_update=*/false,
756 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800757 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000758
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800759 void Exec() {
760 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
761 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000762
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800763 private:
764 unique_fd reference_profile_fd_;
765 std::vector<unique_fd> profiles_fd_;
766 std::vector<unique_fd> apk_fds_;
767};
Mathieu Chartier31636522018-11-09 23:53:07 +0000768
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800769
Calin Juravlef63d4792018-01-30 17:43:34 +0000770
Jeff Sharkey90aff262016-12-12 14:28:24 -0700771// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800772// The location is the package name for primary apks or the dex path for secondary dex files.
773// Returns true if there is enough information in the current profiles that makes it
774// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775// If the return value is true all the current profiles would have been merged into
776// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800777static bool analyze_profiles(uid_t uid, const std::string& package_name,
778 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800779 std::vector<unique_fd> profiles_fd;
780 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800781 open_profile_files(uid, package_name, location, is_secondary_dex,
782 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800783 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 // Skip profile guided compilation because no profiles were found.
785 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700786 return false;
787 }
788
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800789 RunProfman profman_merge;
790 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700791 pid_t pid = fork();
792 if (pid == 0) {
793 /* child -- drop privileges before continuing */
794 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800795 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700796 }
797 /* parent */
798 int return_code = wait_child(pid);
799 bool need_to_compile = false;
800 bool should_clear_current_profiles = false;
801 bool should_clear_reference_profile = false;
802 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800803 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700804 } else {
805 return_code = WEXITSTATUS(return_code);
806 switch (return_code) {
807 case PROFMAN_BIN_RETURN_CODE_COMPILE:
808 need_to_compile = true;
809 should_clear_current_profiles = true;
810 should_clear_reference_profile = false;
811 break;
812 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
813 need_to_compile = false;
814 should_clear_current_profiles = false;
815 should_clear_reference_profile = false;
816 break;
817 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800818 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700819 need_to_compile = false;
820 should_clear_current_profiles = true;
821 should_clear_reference_profile = true;
822 break;
823 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
824 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
825 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800826 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827 need_to_compile = false;
828 should_clear_current_profiles = false;
829 should_clear_reference_profile = false;
830 break;
831 default:
832 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800833 LOG(WARNING) << "Unknown error code while processing profiles for location "
834 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700835 need_to_compile = false;
836 should_clear_current_profiles = true;
837 should_clear_reference_profile = true;
838 break;
839 }
840 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800841
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800843 if (is_secondary_dex) {
844 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800845 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
846 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800847 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800848 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800849 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 }
851 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800852 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 }
854 return need_to_compile;
855}
856
Calin Juravle114f0812017-03-08 19:05:07 -0800857// Decides if profile guided compilation is needed or not based on existing profiles.
858// The analysis is done for the primary apks of the given package.
859// Returns true if there is enough information in the current profiles that makes it
860// worth to recompile the package.
861// If the return value is true all the current profiles would have been merged into
862// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800863bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
864 const std::string& profile_name) {
865 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800866}
867
Calin Juravle408cd4a2018-01-20 23:34:18 -0800868bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
869 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800870 std::vector<unique_fd> profile_fds;
871 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800872 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
873 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874
Calin Juravle408cd4a2018-01-20 23:34:18 -0800875 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800876 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800878 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879 const bool has_profiles = !profile_fds.empty();
880
881 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800882 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883 return false;
884 }
885
Calin Juravle114f0812017-03-08 19:05:07 -0800886 unique_fd output_fd(open(out_file_name.c_str(),
887 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800889 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700890 return false;
891 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800892
Jeff Sharkey90aff262016-12-12 14:28:24 -0700893 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800894 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800895 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
896 if (apk_fd == -1) {
897 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
898 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700899 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800900 dex_locations.push_back(get_location_from_path(code_path.c_str()));
901 apk_fds.push_back(std::move(apk_fd));
902
Jeff Sharkey90aff262016-12-12 14:28:24 -0700903
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800904 RunProfman profman_dump;
905 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700906 pid_t pid = fork();
907 if (pid == 0) {
908 /* child -- drop privileges before continuing */
909 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800910 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700911 }
912 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700913 int return_code = wait_child(pid);
914 if (!WIFEXITED(return_code)) {
915 LOG(WARNING) << "profman failed for package " << pkgname << ": "
916 << return_code;
917 return false;
918 }
919 return true;
920}
921
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700922bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800923 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700924 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
925 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800926 package_name,
927 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700928 /*read_write*/ true,
929 /*secondary*/ false));
930 if (in_fd.get() < 0) {
931 PLOG(WARNING) << "Could not open profile " << system_profile;
932 return false;
933 }
934 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800935 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700936 return false;
937 }
938
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700939 // As a security measure we want to write the profile information with the reduced capabilities
940 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700941 pid_t pid = fork();
942 if (pid == 0) {
943 /* child -- drop privileges before continuing */
944 drop_capabilities(packageUid);
945
946 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
947 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800948 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700949 }
950 // This implies that the app owning this profile is running
951 // (and has acquired the lock).
952 //
953 // The app never acquires the lock for the reference profiles of primary apks.
954 // Only dex2oat from installd will do that. Since installd is single threaded
955 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800956 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700957 return false;
958 }
959
960 bool truncated = ftruncate(out_fd.get(), 0) == 0;
961 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800962 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700963 }
964
965 // Copy over data.
966 static constexpr size_t kBufferSize = 4 * 1024;
967 char buffer[kBufferSize];
968 while (true) {
969 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
970 if (bytes == 0) {
971 break;
972 }
973 write(out_fd.get(), buffer, bytes);
974 }
975 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800976 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700977 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700978 // Use _exit since we don't want to run the global destructors in the child.
979 // b/62597429
980 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700981 }
982 /* parent */
983 int return_code = wait_child(pid);
984 return return_code == 0;
985}
986
Jeff Sharkey90aff262016-12-12 14:28:24 -0700987static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
988 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
989 if (EndsWith(oat_path, ".dex")) {
990 std::string new_path = oat_path;
991 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800992 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700993 return new_path;
994 }
995
996 // An odex entry. Not that this may not be an extension, e.g., in the OTA
997 // case (where the base name will have an extension for the B artifact).
998 size_t odex_pos = oat_path.rfind(".odex");
999 if (odex_pos != std::string::npos) {
1000 std::string new_path = oat_path;
1001 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1002 CHECK_NE(new_path.find(new_ext), std::string::npos);
1003 return new_path;
1004 }
1005
1006 // Don't know how to handle this.
1007 return "";
1008}
1009
1010// Translate the given oat path to an art (app image) path. An empty string
1011// denotes an error.
1012static std::string create_image_filename(const std::string& oat_path) {
1013 return replace_file_extension(oat_path, ".art");
1014}
1015
1016// Translate the given oat path to a vdex path. An empty string denotes an error.
1017static std::string create_vdex_filename(const std::string& oat_path) {
1018 return replace_file_extension(oat_path, ".vdex");
1019}
1020
Jeff Sharkey90aff262016-12-12 14:28:24 -07001021static int open_output_file(const char* file_name, bool recreate, int permissions) {
1022 int flags = O_RDWR | O_CREAT;
1023 if (recreate) {
1024 if (unlink(file_name) < 0) {
1025 if (errno != ENOENT) {
1026 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1027 }
1028 }
1029 flags |= O_EXCL;
1030 }
1031 return open(file_name, flags, permissions);
1032}
1033
Calin Juravle2289c0a2017-02-15 12:44:14 -08001034static bool set_permissions_and_ownership(
1035 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1036 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1037 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001038 if (fchmod(fd,
1039 S_IRUSR|S_IWUSR|S_IRGRP |
1040 (is_public ? S_IROTH : 0)) < 0) {
1041 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1042 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001043 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001044 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1045 return false;
1046 }
1047 return true;
1048}
1049
1050static bool IsOutputDalvikCache(const char* oat_dir) {
1051 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1052 // into '!'. Play it safe by handling it both.
1053 // TODO: ensure we never get null.
1054 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1055 return oat_dir == nullptr || oat_dir[0] == '!';
1056}
1057
Calin Juravled23dee72017-07-06 16:29:11 -07001058// Best-effort check whether we can fit the the path into our buffers.
1059// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1060// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1061// extension to the cache path (5 bytes).
1062// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1063static bool validate_dex_path_size(const std::string& dex_path) {
1064 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1065 LOG(ERROR) << "dex_path too long: " << dex_path;
1066 return false;
1067 }
1068 return true;
1069}
1070
Jeff Sharkey90aff262016-12-12 14:28:24 -07001071static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001072 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001073 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001074 return false;
1075 }
1076
1077 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001078 // Oat dirs for secondary dex files are already validated.
1079 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001080 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1081 return false;
1082 }
1083 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1084 return false;
1085 }
1086 } else {
1087 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1088 return false;
1089 }
1090 }
1091 return true;
1092}
1093
1094// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1095// on destruction. It will also run the given cleanup (unless told not to) after closing.
1096//
1097// Usage example:
1098//
Calin Juravle7a570e82017-01-14 16:23:30 -08001099// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001100// [name]() {
1101// unlink(name.c_str());
1102// });
1103// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1104// wrapper if captured as a reference.
1105//
1106// if (file.get() == -1) {
1107// // Error opening...
1108// }
1109//
1110// ...
1111// if (error) {
1112// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1113// // and delete the file (after the fd is closed).
1114// return -1;
1115// }
1116//
1117// (Success case)
1118// file.SetCleanup(false);
1119// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1120// // (leaving the file around; after the fd is closed).
1121//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001122class Dex2oatFileWrapper {
1123 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001124 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 }
1126
Calin Juravle7a570e82017-01-14 16:23:30 -08001127 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1128 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1129
1130 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1131 value_ = other.value_;
1132 cleanup_ = other.cleanup_;
1133 do_cleanup_ = other.do_cleanup_;
1134 auto_close_ = other.auto_close_;
1135 other.release();
1136 }
1137
1138 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1139 value_ = other.value_;
1140 cleanup_ = other.cleanup_;
1141 do_cleanup_ = other.do_cleanup_;
1142 auto_close_ = other.auto_close_;
1143 other.release();
1144 return *this;
1145 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146
1147 ~Dex2oatFileWrapper() {
1148 reset(-1);
1149 }
1150
1151 int get() {
1152 return value_;
1153 }
1154
1155 void SetCleanup(bool cleanup) {
1156 do_cleanup_ = cleanup;
1157 }
1158
1159 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001160 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001161 close(value_);
1162 }
1163 if (do_cleanup_ && cleanup_ != nullptr) {
1164 cleanup_();
1165 }
1166
1167 value_ = new_value;
1168 }
1169
Calin Juravle7a570e82017-01-14 16:23:30 -08001170 void reset(int new_value, std::function<void ()> new_cleanup) {
1171 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001172 close(value_);
1173 }
1174 if (do_cleanup_ && cleanup_ != nullptr) {
1175 cleanup_();
1176 }
1177
1178 value_ = new_value;
1179 cleanup_ = new_cleanup;
1180 }
1181
Calin Juravle7a570e82017-01-14 16:23:30 -08001182 void DisableAutoClose() {
1183 auto_close_ = false;
1184 }
1185
Jeff Sharkey90aff262016-12-12 14:28:24 -07001186 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001187 void release() {
1188 value_ = -1;
1189 do_cleanup_ = false;
1190 cleanup_ = nullptr;
1191 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001192 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001193 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001194 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001195 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001196};
1197
Calin Juravle7a570e82017-01-14 16:23:30 -08001198// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001199Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1200 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001201
1202 // We don't create an image for secondary dex files.
1203 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001204 return Dex2oatFileWrapper();
1205 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001206
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 const std::string image_path = create_image_filename(out_oat_path);
1208 if (image_path.empty()) {
1209 // Happens when the out_oat_path has an unknown extension.
1210 return Dex2oatFileWrapper();
1211 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001212
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001213 // In case there is a stale image, remove it now. Ignore any error.
1214 unlink(image_path.c_str());
1215
1216 // Not enabled, exit.
1217 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001218 return Dex2oatFileWrapper();
1219 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001220 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1221 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001222 return Dex2oatFileWrapper();
1223 }
1224 // Recreate is true since we do not want to modify a mapped image. If the app is
1225 // already running and we modify the image file, it can cause crashes (b/27493510).
1226 Dex2oatFileWrapper wrapper_fd(
1227 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1228 [image_path]() { unlink(image_path.c_str()); });
1229 if (wrapper_fd.get() < 0) {
1230 // Could not create application image file. Go on since we can compile without it.
1231 LOG(ERROR) << "installd could not create '" << image_path
1232 << "' for image file during dexopt";
1233 // If we have a valid image file path but no image fd, explicitly erase the image file.
1234 if (unlink(image_path.c_str()) < 0) {
1235 if (errno != ENOENT) {
1236 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1237 }
1238 }
1239 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001240 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001241 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1242 wrapper_fd.reset(-1);
1243 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001244
Calin Juravle7a570e82017-01-14 16:23:30 -08001245 return wrapper_fd;
1246}
1247
1248// Creates the dexopt swap file if necessary and return its fd.
1249// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001250unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001251 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001252 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001253 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001254 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001255 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001256 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001257 if (swap_fd.get() < 0) {
1258 // Could not create swap file. Optimistically go on and hope that we can compile
1259 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001260 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001261 } else {
1262 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001263 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001264 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1265 }
1266 }
1267 return swap_fd;
1268}
1269
1270// Opens the reference profiles if needed.
1271// 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 -08001272Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001273 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001274 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001275 // If we are not profile guided compilation, or we are compiling system server
1276 // do not bother to open the profiles; we won't be using them.
1277 if (!profile_guided || (pkgname[0] == '*')) {
1278 return Dex2oatFileWrapper();
1279 }
1280
1281 // If this is a secondary dex path which is public do not open the profile.
1282 // We cannot compile public secondary dex paths with profiles. That's because
1283 // it will expose how the dex files are used by their owner.
1284 //
1285 // Note that the PackageManager is responsible to set the is_public flag for
1286 // primary apks and we do not check it here. In some cases, e.g. when
1287 // compiling with a public profile from the .dm file the PackageManager will
1288 // set is_public toghether with the profile guided compilation.
1289 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001290 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001291 }
Calin Juravle114f0812017-03-08 19:05:07 -08001292
1293 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001294 std::string location;
1295 if (is_secondary_dex) {
1296 location = dex_path;
1297 } else {
1298 if (profile_name == nullptr) {
1299 // This path is taken for system server re-compilation lunched from ZygoteInit.
1300 return Dex2oatFileWrapper();
1301 } else {
1302 location = profile_name;
1303 }
1304 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001305 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1306 is_secondary_dex);
1307 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1308 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001309 };
1310 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001311}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001312
Calin Juravle7a570e82017-01-14 16:23:30 -08001313// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1314// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001315bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001316 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001317 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001318 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1319 CHECK(in_vdex_wrapper_fd != nullptr);
1320 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001321 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1322 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001323 char in_odex_path[PKG_PATH_MAX];
1324 int dexopt_action = abs(dexopt_needed);
1325 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001326 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001327
1328 // Infer the name of the output VDEX.
1329 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1330 if (out_vdex_path_str.empty()) {
1331 return false;
1332 }
1333
1334 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001335 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001336 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1337 const char* path = nullptr;
1338 if (is_odex_location) {
1339 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1340 path = in_odex_path;
1341 } else {
1342 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001343 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001344 }
1345 } else {
1346 path = out_oat_path;
1347 }
1348 in_vdex_path_str = create_vdex_filename(path);
1349 if (in_vdex_path_str.empty()) {
1350 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001351 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001352 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001353 // We can update in place when all these conditions are met:
1354 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1355 // on /system typically cannot be updated in place).
1356 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1357 // cannot be currently used by a running process.
1358 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1359 // different vdex files to operate.
1360 update_vdex_in_place =
1361 (in_vdex_path_str == out_vdex_path_str) &&
1362 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1363 !profile_guided;
1364 if (update_vdex_in_place) {
1365 // Open the file read-write to be able to update it.
1366 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1367 if (in_vdex_wrapper_fd->get() == -1) {
1368 // If we failed to open the file, we cannot update it in place.
1369 update_vdex_in_place = false;
1370 }
1371 } else {
1372 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1373 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001374 }
1375
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001376 // If we are updating the vdex in place, we do not need to recreate a vdex,
1377 // and can use the same existing one.
1378 if (update_vdex_in_place) {
1379 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1380 // have bogus stale vdex files.
1381 out_vdex_wrapper_fd->reset(
1382 in_vdex_wrapper_fd->get(),
1383 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1384 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1385 // wrapper).
1386 in_vdex_wrapper_fd->DisableAutoClose();
1387 } else {
1388 out_vdex_wrapper_fd->reset(
1389 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1390 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1391 if (out_vdex_wrapper_fd->get() < 0) {
1392 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1393 return false;
1394 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001395 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001396 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001397 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001398 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1399 return false;
1400 }
1401
1402 // If we got here we successfully opened the vdex files.
1403 return true;
1404}
1405
1406// Opens the output oat file for the given apk.
1407// If successful it stores the output path into out_oat_path and returns true.
1408Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001409 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1410 char* out_oat_path) {
1411 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001412 return Dex2oatFileWrapper();
1413 }
1414 const std::string out_oat_path_str(out_oat_path);
1415 Dex2oatFileWrapper wrapper_fd(
1416 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1417 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1418 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001419 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001420 } else if (!set_permissions_and_ownership(
1421 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001422 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1423 wrapper_fd.reset(-1);
1424 }
1425 return wrapper_fd;
1426}
1427
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001428// Creates RDONLY fds for oat and vdex files, if exist.
1429// Returns false if it fails to create oat out path for the given apk path.
1430// Note that the method returns true even if the files could not be opened.
1431bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1432 const std::string& oat_dir,
1433 const std::string& instruction_set,
1434 bool is_secondary_dex,
1435 unique_fd* oat_file_fd,
1436 unique_fd* vdex_file_fd) {
1437 char oat_path[PKG_PATH_MAX];
1438 if (!create_oat_out_path(apk_path.c_str(),
1439 instruction_set.c_str(),
1440 oat_dir.c_str(),
1441 is_secondary_dex,
1442 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001443 LOG(ERROR) << "Could not create oat out path for "
1444 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001445 return false;
1446 }
1447 oat_file_fd->reset(open(oat_path, O_RDONLY));
1448 if (oat_file_fd->get() < 0) {
1449 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1450 }
1451
1452 std::string vdex_filename = create_vdex_filename(oat_path);
1453 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1454 if (vdex_file_fd->get() < 0) {
1455 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1456 }
1457
1458 return true;
1459}
1460
Calin Juravle7a570e82017-01-14 16:23:30 -08001461// Updates the access times of out_oat_path based on those from apk_path.
1462void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1463 struct stat input_stat;
1464 memset(&input_stat, 0, sizeof(input_stat));
1465 if (stat(apk_path, &input_stat) != 0) {
1466 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1467 return;
1468 }
1469
1470 struct utimbuf ut;
1471 ut.actime = input_stat.st_atime;
1472 ut.modtime = input_stat.st_mtime;
1473 if (utime(out_oat_path, &ut) != 0) {
1474 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1475 }
1476}
1477
Calin Juravle80a21252017-01-17 14:43:25 -08001478// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001479// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1480// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1481// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001482class RunDexoptAnalyzer : public ExecVHelper {
1483 public:
1484 RunDexoptAnalyzer(const std::string& dex_file,
1485 int vdex_fd,
1486 int oat_fd,
1487 int zip_fd,
1488 const std::string& instruction_set,
1489 const std::string& compiler_filter,
1490 bool profile_was_updated,
1491 bool downgrade,
1492 const char* class_loader_context) {
1493 CHECK_GE(zip_fd, 0);
1494 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001495 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001496
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001497 std::string dex_file_arg = "--dex-file=" + dex_file;
1498 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1499 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1500 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1501 std::string isa_arg = "--isa=" + instruction_set;
1502 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1503 const char* assume_profile_changed = "--assume-profile-changed";
1504 const char* downgrade_flag = "--downgrade";
1505 std::string class_loader_context_arg = "--class-loader-context=";
1506 if (class_loader_context != nullptr) {
1507 class_loader_context_arg += class_loader_context;
1508 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001509
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001510 // program name, dex file, isa, filter
1511 AddArg(dex_file_arg);
1512 AddArg(isa_arg);
1513 AddArg(compiler_filter_arg);
1514 if (oat_fd >= 0) {
1515 AddArg(oat_fd_arg);
1516 }
1517 if (vdex_fd >= 0) {
1518 AddArg(vdex_fd_arg);
1519 }
1520 AddArg(zip_fd_arg.c_str());
1521 if (profile_was_updated) {
1522 AddArg(assume_profile_changed);
1523 }
1524 if (downgrade) {
1525 AddArg(downgrade_flag);
1526 }
1527 if (class_loader_context != nullptr) {
1528 AddArg(class_loader_context_arg.c_str());
1529 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001530
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001531 PrepareArgs(dexoptanalyzer_bin);
1532 }
1533};
Calin Juravle80a21252017-01-17 14:43:25 -08001534
1535// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001536static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001537 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001538 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001539 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001540 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001541 return false;
1542 }
Calin Juravle114f0812017-03-08 19:05:07 -08001543 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001544
Calin Juravle80a21252017-01-17 14:43:25 -08001545 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001546 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1547 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001548 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001549 return false;
1550 }
1551
1552 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001553 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001554
Calin Juravle7d765462017-09-04 15:57:10 -07001555 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001556 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001557 return false;
1558 }
1559
1560 return true;
1561}
1562
Calin Juravle7d765462017-09-04 15:57:10 -07001563// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1564// secondary dex files. This return codes are returned by the child process created for
1565// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001566
Andreas Gampe194fe422018-02-28 20:16:19 -08001567enum DexoptAnalyzerSkipCodes {
1568 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001569 // Specific errors are encoded in the name.
1570 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1571 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1572 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1573 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1574 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001575 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001576 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001577};
Calin Juravle7d765462017-09-04 15:57:10 -07001578
1579// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001580// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1581// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001582// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1583// of dexoptanalyzer.
1584static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001585 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001586 // The result values are defined in dexoptanalyzer.
1587 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001588 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001589 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001590 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001591 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001592 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001593 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001594 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001595 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001596 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1597 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001598 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1599 " Expected odex file status for secondary dex %s"
1600 " : dexoptanalyzer result=%d",
1601 dex_path.c_str(),
1602 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001603 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001604 }
1605
1606 // Use a second switch for enum switch-case analysis.
1607 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001608 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001609 // If the file does not exist there's no need for dexopt.
1610 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1611 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001612
1613 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1614 *error_msg = "Dexoptanalyzer path validation failed";
1615 return false;
1616 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1617 *error_msg = "Dexoptanalyzer open zip failed";
1618 return false;
1619 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1620 *error_msg = "Dexoptanalyzer dir preparation failed";
1621 return false;
1622 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1623 *error_msg = "Dexoptanalyzer open output failed";
1624 return false;
1625 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1626 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001627 return false;
1628 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001629
1630 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1631 dex_path.c_str(),
1632 result);
1633 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001634}
1635
Calin Juravle7d765462017-09-04 15:57:10 -07001636enum SecondaryDexAccess {
1637 kSecondaryDexAccessReadOk = 0,
1638 kSecondaryDexAccessDoesNotExist = 1,
1639 kSecondaryDexAccessPermissionError = 2,
1640 kSecondaryDexAccessIOError = 3
1641};
1642
1643static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1644 // Check if the path exists and can be read. If not, there's nothing to do.
1645 if (access(dex_path.c_str(), R_OK) == 0) {
1646 return kSecondaryDexAccessReadOk;
1647 } else {
1648 if (errno == ENOENT) {
1649 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1650 return kSecondaryDexAccessDoesNotExist;
1651 } else {
1652 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1653 return errno == EACCES
1654 ? kSecondaryDexAccessPermissionError
1655 : kSecondaryDexAccessIOError;
1656 }
1657 }
1658}
1659
1660static bool is_file_public(const std::string& filename) {
1661 struct stat file_stat;
1662 if (stat(filename.c_str(), &file_stat) == 0) {
1663 return (file_stat.st_mode & S_IROTH) != 0;
1664 }
1665 return false;
1666}
1667
1668// Create the oat file structure for the secondary dex 'dex_path' and assign
1669// the individual path component to the 'out_' parameters.
1670static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001671 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001672 size_t dirIndex = dex_path.rfind('/');
1673 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001674 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001675 return false;
1676 }
1677 // TODO(calin): we have similar computations in at lest 3 other places
1678 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1679 // using string append.
1680 std::string apk_dir = dex_path.substr(0, dirIndex);
1681 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1682 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1683
1684 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1685 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001686 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001687 return false;
1688 }
1689 return true;
1690}
1691
1692// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1693// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001694static bool validate_dexopt_storage_flags(int dexopt_flags,
1695 int* out_storage_flag,
1696 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001697 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1698 *out_storage_flag = FLAG_STORAGE_CE;
1699 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001700 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001701 return false;
1702 }
1703 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1704 *out_storage_flag = FLAG_STORAGE_DE;
1705 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001706 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001707 return false;
1708 }
1709 return true;
1710}
1711
Calin Juravlec9eab382017-01-25 01:17:17 -08001712// 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 -08001713// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1714// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001715// When returning true, the output parameters will be:
1716// - is_public_out: whether or not the oat file should not be made public
1717// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1718// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001719static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001720 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001721 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001722 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1723 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001724 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001725 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001726 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1727 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001728 return false;
1729 }
Calin Juravle7d765462017-09-04 15:57:10 -07001730 // Compute the oat dir as it's not easy to extract it from the child computation.
1731 char oat_path[PKG_PATH_MAX];
1732 char oat_dir[PKG_PATH_MAX];
1733 char oat_isa_dir[PKG_PATH_MAX];
1734 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001735 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1736 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001737 return false;
1738 }
Calin Juravle7d765462017-09-04 15:57:10 -07001739 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001740
Calin Juravle80a21252017-01-17 14:43:25 -08001741 pid_t pid = fork();
1742 if (pid == 0) {
1743 // child -- drop privileges before continuing.
1744 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001745
1746 // Validate the path structure.
1747 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1748 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001749 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001750 }
1751
1752 // Open the dex file.
1753 unique_fd zip_fd;
1754 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1755 if (zip_fd.get() < 0) {
1756 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001757 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001758 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001759 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001760 }
1761 }
1762
1763 // Prepare the oat directories.
1764 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001765 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001766 }
1767
1768 // Open the vdex/oat files if any.
1769 unique_fd oat_file_fd;
1770 unique_fd vdex_file_fd;
1771 if (!maybe_open_oat_and_vdex_file(dex_path,
1772 *oat_dir_out,
1773 instruction_set,
1774 true /* is_secondary_dex */,
1775 &oat_file_fd,
1776 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001777 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001778 }
1779
1780 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001781 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1782 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001783
1784 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001785 // Note that we do not do it before the fork since opening the files is required to happen
1786 // after forking.
1787 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1788 vdex_file_fd.get(),
1789 oat_file_fd.get(),
1790 zip_fd.get(),
1791 instruction_set,
1792 compiler_filter, profile_was_updated,
1793 downgrade,
1794 class_loader_context);
1795 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001796 }
1797
1798 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001799 int result = wait_child(pid);
1800 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001801 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1802 dex_path.c_str(),
1803 result);
1804 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001805 return false;
1806 }
1807 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001808 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001809 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1810 result,
1811 dexopt_needed_out,
1812 error_msg);
1813 if (!success) {
1814 LOG(ERROR) << *error_msg;
1815 }
Calin Juravle7d765462017-09-04 15:57:10 -07001816
1817 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1818
Calin Juravle80a21252017-01-17 14:43:25 -08001819 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001820 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1821 // makes the code simpler; force compilation is only needed during tests).
1822 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001823 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001824 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001825 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1826 }
1827
Calin Juravle7d765462017-09-04 15:57:10 -07001828 // Check if we should make the oat file public.
1829 // Note that if the dex file is not public the compiled code cannot be made public.
1830 // It is ok to check this flag outside in the parent process.
1831 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1832
Calin Juravle80a21252017-01-17 14:43:25 -08001833 return success;
1834}
1835
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001836static std::string format_dexopt_error(int status, const char* dex_path) {
1837 if (WIFEXITED(status)) {
1838 int int_code = WEXITSTATUS(status);
1839 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1840 if (code_name != nullptr) {
1841 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1842 }
1843 }
1844 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001845}
1846
Calin Juravlec9eab382017-01-25 01:17:17 -08001847int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001848 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001849 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001850 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001851 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001852 CHECK(pkgname != nullptr);
1853 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001854 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001855 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1856 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001857
Calin Juravled23dee72017-07-06 16:29:11 -07001858 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001859 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001860 return -1;
1861 }
1862
1863 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001864 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1865 class_loader_context);
1866 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001867 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001868 }
1869
Calin Juravleebc8a792017-04-04 20:21:05 -07001870 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001871 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1872 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1873 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001874 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001875 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001876 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001877 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001878 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001879
1880 // Check if we're dealing with a secondary dex file and if we need to compile it.
1881 std::string oat_dir_str;
1882 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001883 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001884 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001885 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001886 oat_dir = oat_dir_str.c_str();
1887 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1888 return 0; // Nothing to do, report success.
1889 }
1890 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001891 if (error_msg->empty()) { // TODO: Make this a CHECK.
1892 *error_msg = "Failed processing secondary.";
1893 }
Calin Juravle80a21252017-01-17 14:43:25 -08001894 return -1; // We had an error, logged in the process method.
1895 }
1896 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001897 // Currently these flags are only use for secondary dex files.
1898 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001899 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1900 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1901 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001902
1903 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001904 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001905 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001906 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1907 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001908 return -1;
1909 }
1910
1911 // Create the output OAT file.
1912 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001913 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001914 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001915 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001916 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001917 return -1;
1918 }
1919
1920 // Open vdex files.
1921 Dex2oatFileWrapper in_vdex_fd;
1922 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001923 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1924 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001925 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001926 return -1;
1927 }
1928
Calin Juravlecb556e32017-04-04 20:22:50 -07001929 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1930 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1931 // fully inherit their parent context).
1932 // Note that for primary apk the oat files are created before, in a separate installd
1933 // call which also does the restorecon. TODO(calin): unify the paths.
1934 if (is_secondary_dex) {
1935 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1936 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001937 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1938 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001939 return -1;
1940 }
1941 }
1942
Jeff Sharkey90aff262016-12-12 14:28:24 -07001943 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001944 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001945
Calin Juravle7a570e82017-01-14 16:23:30 -08001946 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001947 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1948 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001949
Calin Juravle7a570e82017-01-14 16:23:30 -08001950 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001951 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001952 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001953
Calin Juravle62c5a372018-02-01 17:03:23 +00001954 unique_fd dex_metadata_fd;
1955 if (dex_metadata_path != nullptr) {
1956 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1957 if (dex_metadata_fd.get() < 0) {
1958 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1959 }
1960 }
1961
Andreas Gampe023b2242018-02-28 16:03:25 -08001962 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001963
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001964 RunDex2Oat runner(input_fd.get(),
1965 out_oat_fd.get(),
1966 in_vdex_fd.get(),
1967 out_vdex_fd.get(),
1968 image_fd.get(),
1969 dex_path,
1970 out_oat_path,
1971 swap_fd.get(),
1972 instruction_set,
1973 compiler_filter,
1974 debuggable,
1975 boot_complete,
1976 background_job_compile,
1977 reference_profile_fd.get(),
1978 class_loader_context,
1979 target_sdk_version,
1980 enable_hidden_api_checks,
1981 generate_compact_dex,
1982 dex_metadata_fd.get(),
1983 compilation_reason);
1984
Jeff Sharkey90aff262016-12-12 14:28:24 -07001985 pid_t pid = fork();
1986 if (pid == 0) {
1987 /* child -- drop privileges before continuing */
1988 drop_capabilities(uid);
1989
Richard Uhler76cc0272016-12-08 10:46:35 +00001990 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001991 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001992 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001993 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001994 }
1995
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001996 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001997 } else {
1998 int res = wait_child(pid);
1999 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002000 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002001 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002002 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2003 << std::hex << std::setw(4) << res << ", process failed";
2004 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002005 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002006 }
2007 }
2008
Calin Juravlec9eab382017-01-25 01:17:17 -08002009 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002010
2011 // We've been successful, don't delete output.
2012 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002013 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002014 image_fd.SetCleanup(false);
2015 reference_profile_fd.SetCleanup(false);
2016
2017 return 0;
2018}
2019
Calin Juravlec9eab382017-01-25 01:17:17 -08002020// Try to remove the given directory. Log an error if the directory exists
2021// and is empty but could not be removed.
2022static bool rmdir_if_empty(const char* dir) {
2023 if (rmdir(dir) == 0) {
2024 return true;
2025 }
2026 if (errno == ENOENT || errno == ENOTEMPTY) {
2027 return true;
2028 }
2029 PLOG(ERROR) << "Failed to remove dir: " << dir;
2030 return false;
2031}
2032
2033// Try to unlink the given file. Log an error if the file exists and could not
2034// be unlinked.
2035static bool unlink_if_exists(const std::string& file) {
2036 if (unlink(file.c_str()) == 0) {
2037 return true;
2038 }
2039 if (errno == ENOENT) {
2040 return true;
2041
2042 }
2043 PLOG(ERROR) << "Could not unlink: " << file;
2044 return false;
2045}
2046
Calin Juravle7d765462017-09-04 15:57:10 -07002047enum ReconcileSecondaryDexResult {
2048 kReconcileSecondaryDexExists = 0,
2049 kReconcileSecondaryDexCleanedUp = 1,
2050 kReconcileSecondaryDexValidationError = 2,
2051 kReconcileSecondaryDexCleanUpError = 3,
2052 kReconcileSecondaryDexAccessIOError = 4,
2053};
Calin Juravlec9eab382017-01-25 01:17:17 -08002054
2055// Reconcile the secondary dex 'dex_path' and its generated oat files.
2056// Return true if all the parameters are valid and the secondary dex file was
2057// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2058// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2059// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2060// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2061// Return false if there were errors during processing. In this case
2062// out_secondary_dex_exists will be set to false.
2063bool reconcile_secondary_dex_file(const std::string& dex_path,
2064 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2065 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2066 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002067 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002068 if (isas.size() == 0) {
2069 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2070 return false;
2071 }
2072
Calin Juravle7d765462017-09-04 15:57:10 -07002073 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2074 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2075 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002076 return false;
2077 }
2078
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002079 // As a security measure we want to unlink art artifacts with the reduced capabilities
2080 // of the package user id. So we fork and drop capabilities in the child.
2081 pid_t pid = fork();
2082 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002083 /* child -- drop privileges before continuing */
2084 drop_capabilities(uid);
2085
2086 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2087 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2088 uid, storage_flag)) {
2089 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2090 _exit(kReconcileSecondaryDexValidationError);
2091 }
2092
2093 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2094 switch (access_check) {
2095 case kSecondaryDexAccessDoesNotExist:
2096 // File does not exist. Proceed with cleaning.
2097 break;
2098 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2099 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2100 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2101 default:
2102 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2103 _exit(kReconcileSecondaryDexValidationError);
2104 }
2105
2106 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002107 char oat_path[PKG_PATH_MAX];
2108 char oat_dir[PKG_PATH_MAX];
2109 char oat_isa_dir[PKG_PATH_MAX];
2110 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002111 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002112 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002113 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002114 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2115 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002116 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002117 }
Calin Juravle51314092017-05-18 15:33:05 -07002118
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002119 // Delete oat/vdex/art files.
2120 result = unlink_if_exists(oat_path) && result;
2121 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2122 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002123
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002124 // Delete profiles.
2125 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002126 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002127 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002128 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002129 result = unlink_if_exists(current_profile) && result;
2130 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002131
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002132 // We upgraded once the location of current profile for secondary dex files.
2133 // Check for any previous left-overs and remove them as well.
2134 std::string old_current_profile = dex_path + ".prof";
2135 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002136
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002137 // Try removing the directories as well, they might be empty.
2138 result = rmdir_if_empty(oat_isa_dir) && result;
2139 result = rmdir_if_empty(oat_dir) && result;
2140 }
Calin Juravle7d765462017-09-04 15:57:10 -07002141 if (!result) {
2142 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2143 }
2144 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002145 }
2146
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002147 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002148 if (!WIFEXITED(return_code)) {
2149 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2150 } else {
2151 return_code = WEXITSTATUS(return_code);
2152 }
2153
2154 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2155
2156 switch (return_code) {
2157 case kReconcileSecondaryDexCleanedUp:
2158 case kReconcileSecondaryDexValidationError:
2159 // If we couldn't validate assume the dex file does not exist.
2160 // This will purge the entry from the PM records.
2161 *out_secondary_dex_exists = false;
2162 return true;
2163 case kReconcileSecondaryDexExists:
2164 *out_secondary_dex_exists = true;
2165 return true;
2166 case kReconcileSecondaryDexAccessIOError:
2167 // We had an access IO error.
2168 // Return false so that we can try again.
2169 // The value of out_secondary_dex_exists does not matter in this case and by convention
2170 // is set to false.
2171 *out_secondary_dex_exists = false;
2172 return false;
2173 default:
2174 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2175 *out_secondary_dex_exists = false;
2176 return false;
2177 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002178}
2179
Alan Stokesa25d90c2017-10-16 10:56:00 +01002180// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2181// Returns true if all parameters are valid and the hash successfully computed and stored in
2182// out_secondary_dex_hash.
2183// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2184// the app.
2185// For any other errors (e.g. if any of the parameters are invalid) returns false.
2186bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2187 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2188 std::vector<uint8_t>* out_secondary_dex_hash) {
2189 out_secondary_dex_hash->clear();
2190
2191 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2192
2193 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2194 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2195 << storage_flag;
2196 return false;
2197 }
2198
2199 // Pipe to get the hash result back from our child process.
2200 unique_fd pipe_read, pipe_write;
2201 if (!Pipe(&pipe_read, &pipe_write)) {
2202 PLOG(ERROR) << "Failed to create pipe";
2203 return false;
2204 }
2205
2206 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2207 // access data the app itself can access.
2208 pid_t pid = fork();
2209 if (pid == 0) {
2210 // child -- drop privileges before continuing
2211 drop_capabilities(uid);
2212 pipe_read.reset();
2213
2214 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2215 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002216 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002217 }
2218
2219 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2220 if (fd == -1) {
2221 if (errno == EACCES || errno == ENOENT) {
2222 // Not treated as an error.
2223 _exit(0);
2224 }
2225 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002226 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002227 }
2228
2229 SHA256_CTX ctx;
2230 SHA256_Init(&ctx);
2231
2232 std::vector<uint8_t> buffer(65536);
2233 while (true) {
2234 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2235 if (bytes_read == 0) {
2236 break;
2237 } else if (bytes_read == -1) {
2238 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002239 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002240 }
2241
2242 SHA256_Update(&ctx, buffer.data(), bytes_read);
2243 }
2244
2245 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2246 SHA256_Final(hash.data(), &ctx);
2247 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002248 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002249 }
2250
2251 _exit(0);
2252 }
2253
2254 // parent
2255 pipe_write.reset();
2256
2257 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2258 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2259 out_secondary_dex_hash->clear();
2260 }
2261 return wait_child(pid) == 0;
2262}
2263
Jeff Sharkey90aff262016-12-12 14:28:24 -07002264// Helper for move_ab, so that we can have common failure-case cleanup.
2265static bool unlink_and_rename(const char* from, const char* to) {
2266 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2267 // return a failure.
2268 struct stat s;
2269 if (stat(to, &s) == 0) {
2270 if (!S_ISREG(s.st_mode)) {
2271 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2272 return false;
2273 }
2274 if (unlink(to) != 0) {
2275 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2276 return false;
2277 }
2278 } else {
2279 // This may be a permission problem. We could investigate the error code, but we'll just
2280 // let the rename failure do the work for us.
2281 }
2282
2283 // Try to rename "to" to "from."
2284 if (rename(from, to) != 0) {
2285 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2286 return false;
2287 }
2288 return true;
2289}
2290
2291// Move/rename a B artifact (from) to an A artifact (to).
2292static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2293 // Check whether B exists.
2294 {
2295 struct stat s;
2296 if (stat(b_path.c_str(), &s) != 0) {
2297 // Silently ignore for now. The service calling this isn't smart enough to understand
2298 // lack of artifacts at the moment.
2299 return false;
2300 }
2301 if (!S_ISREG(s.st_mode)) {
2302 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2303 // Try to unlink, but swallow errors.
2304 unlink(b_path.c_str());
2305 return false;
2306 }
2307 }
2308
2309 // Rename B to A.
2310 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2311 // Delete the b_path so we don't try again (or fail earlier).
2312 if (unlink(b_path.c_str()) != 0) {
2313 PLOG(ERROR) << "Could not unlink " << b_path;
2314 }
2315
2316 return false;
2317 }
2318
2319 return true;
2320}
2321
2322bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2323 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002324 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2325 if (slot_suffix.empty()) {
2326 return false;
2327 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002328
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002329 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2330 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2331 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002332 }
2333
2334 // Validate other inputs.
2335 if (validate_apk_path(apk_path) != 0) {
2336 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2337 return false;
2338 }
2339 if (validate_apk_path(oat_dir) != 0) {
2340 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2341 return false;
2342 }
2343
2344 char a_path[PKG_PATH_MAX];
2345 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2346 return false;
2347 }
2348 const std::string a_vdex_path = create_vdex_filename(a_path);
2349 const std::string a_image_path = create_image_filename(a_path);
2350
2351 // B path = A path + slot suffix.
2352 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2353 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2354 const std::string b_image_path = StringPrintf("%s.%s",
2355 a_image_path.c_str(),
2356 slot_suffix.c_str());
2357
2358 bool success = true;
2359 if (move_ab_path(b_path, a_path)) {
2360 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2361 // Note: we can live without an app image. As such, ignore failure to move the image file.
2362 // If we decide to require the app image, or the app image being moved correctly,
2363 // then change accordingly.
2364 constexpr bool kIgnoreAppImageFailure = true;
2365
2366 if (!a_image_path.empty()) {
2367 if (!move_ab_path(b_image_path, a_image_path)) {
2368 unlink(a_image_path.c_str());
2369 if (!kIgnoreAppImageFailure) {
2370 success = false;
2371 }
2372 }
2373 }
2374 } else {
2375 // Cleanup: delete B image, ignore errors.
2376 unlink(b_image_path.c_str());
2377 success = false;
2378 }
2379 } else {
2380 // Cleanup: delete B image, ignore errors.
2381 unlink(b_vdex_path.c_str());
2382 unlink(b_image_path.c_str());
2383 success = false;
2384 }
2385 return success;
2386}
2387
2388bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2389 // Delete the oat/odex file.
2390 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002391 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002392 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002393 return false;
2394 }
2395
2396 // In case of a permission failure report the issue. Otherwise just print a warning.
2397 auto unlink_and_check = [](const char* path) -> bool {
2398 int result = unlink(path);
2399 if (result != 0) {
2400 if (errno == EACCES || errno == EPERM) {
2401 PLOG(ERROR) << "Could not unlink " << path;
2402 return false;
2403 }
2404 PLOG(WARNING) << "Could not unlink " << path;
2405 }
2406 return true;
2407 };
2408
2409 // Delete the oat/odex file.
2410 bool return_value_oat = unlink_and_check(out_path);
2411
2412 // Derive and delete the app image.
2413 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2414
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002415 // Derive and delete the vdex file.
2416 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2417
Jeff Sharkey90aff262016-12-12 14:28:24 -07002418 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002419 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002420}
2421
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002422static bool is_absolute_path(const std::string& path) {
2423 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2424 LOG(ERROR) << "Invalid absolute path " << path;
2425 return false;
2426 } else {
2427 return true;
2428 }
2429}
2430
2431static bool is_valid_instruction_set(const std::string& instruction_set) {
2432 // TODO: add explicit whitelisting of instruction sets
2433 if (instruction_set.find('/') != std::string::npos) {
2434 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2435 return false;
2436 } else {
2437 return true;
2438 }
2439}
2440
2441bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2442 const char *apk_path, const char *instruction_set) {
2443 std::string oat_dir_ = oat_dir;
2444 std::string apk_path_ = apk_path;
2445 std::string instruction_set_ = instruction_set;
2446
2447 if (!is_absolute_path(oat_dir_)) return false;
2448 if (!is_absolute_path(apk_path_)) return false;
2449 if (!is_valid_instruction_set(instruction_set_)) return false;
2450
2451 std::string::size_type end = apk_path_.rfind('.');
2452 std::string::size_type start = apk_path_.rfind('/', end);
2453 if (end == std::string::npos || start == std::string::npos) {
2454 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2455 return false;
2456 }
2457
2458 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2459 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2460 const char* res = res_.c_str();
2461 if (strlen(res) >= PKG_PATH_MAX) {
2462 LOG(ERROR) << "Result too large";
2463 return false;
2464 } else {
2465 strlcpy(path, res, PKG_PATH_MAX);
2466 return true;
2467 }
2468}
2469
2470bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2471 const char *instruction_set) {
2472 std::string apk_path_ = apk_path;
2473 std::string instruction_set_ = instruction_set;
2474
2475 if (!is_absolute_path(apk_path_)) return false;
2476 if (!is_valid_instruction_set(instruction_set_)) return false;
2477
2478 std::string::size_type end = apk_path_.rfind('.');
2479 std::string::size_type start = apk_path_.rfind('/', end);
2480 if (end == std::string::npos || start == std::string::npos) {
2481 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2482 return false;
2483 }
2484
2485 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2486 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2487}
2488
2489bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2490 const char *instruction_set) {
2491 std::string src_ = src;
2492 std::string instruction_set_ = instruction_set;
2493
2494 if (!is_absolute_path(src_)) return false;
2495 if (!is_valid_instruction_set(instruction_set_)) return false;
2496
2497 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2498 if (*it == '/') {
2499 *it = '@';
2500 }
2501 }
2502
2503 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2504 + DALVIK_CACHE_POSTFIX;
2505 const char* res = res_.c_str();
2506 if (strlen(res) >= PKG_PATH_MAX) {
2507 LOG(ERROR) << "Result too large";
2508 return false;
2509 } else {
2510 strlcpy(path, res, PKG_PATH_MAX);
2511 return true;
2512 }
2513}
2514
Calin Juravle59f7ab82018-04-27 17:50:23 -07002515bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2516 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002517 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2518 for (const std::string& elem : classpaths_elems) {
2519 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2520 if (fd < 0) {
2521 PLOG(ERROR) << "Could not open classpath elem " << elem;
2522 return false;
2523 } else {
2524 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002525 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002526 }
2527 }
2528 return true;
2529}
2530
2531static bool create_app_profile_snapshot(int32_t app_id,
2532 const std::string& package_name,
2533 const std::string& profile_name,
2534 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002535 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2536
Calin Juravle824a64d2018-01-18 20:23:17 -08002537 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002538 if (snapshot_fd < 0) {
2539 return false;
2540 }
2541
2542 std::vector<unique_fd> profiles_fd;
2543 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002544 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2545 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002546 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2547 return false;
2548 }
2549
2550 profiles_fd.push_back(std::move(reference_profile_fd));
2551
Calin Juravle0d0a4922018-01-23 19:54:11 -08002552 // Open the class paths elements. These will be used to filter out profile data that does
2553 // not belong to the classpath during merge.
2554 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002555 std::vector<std::string> dex_locations;
2556 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002557 return false;
2558 }
2559
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002560 RunProfman args;
2561 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002562 pid_t pid = fork();
2563 if (pid == 0) {
2564 /* child -- drop privileges before continuing */
2565 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002566 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002567 }
2568
2569 /* parent */
2570 int return_code = wait_child(pid);
2571 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002572 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002573 return false;
2574 }
2575
2576 return true;
2577}
2578
Calin Juravle0d0a4922018-01-23 19:54:11 -08002579static bool create_boot_image_profile_snapshot(const std::string& package_name,
2580 const std::string& profile_name,
2581 const std::string& classpath) {
2582 // The reference profile directory for the android package might not be prepared. Do it now.
2583 const std::string ref_profile_dir =
2584 create_primary_reference_profile_package_dir_path(package_name);
2585 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2586 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2587 return false;
2588 }
2589
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002590 // Return false for empty class path since it may otherwise return true below if profiles is
2591 // empty.
2592 if (classpath.empty()) {
2593 PLOG(ERROR) << "Class path is empty";
2594 return false;
2595 }
2596
Calin Juravle0d0a4922018-01-23 19:54:11 -08002597 // Open and create the snapshot profile.
2598 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2599
2600 // Collect all non empty profiles.
2601 // The collection will traverse all applications profiles and find the non empty files.
2602 // This has the potential of inspecting a large number of files and directories (depending
2603 // on the number of applications and users). So there is a slight increase in the chance
2604 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2605 // fail the snapshot and aggregate whatever profile we could open.
2606 //
2607 // The profile snapshot is a best effort based on available data it's ok if some data
2608 // from some apps is missing. It will be counter productive for the snapshot to fail
2609 // because we could not open or read some of the files.
2610 std::vector<std::string> profiles;
2611 if (!collect_profiles(&profiles)) {
2612 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2613 }
2614
2615 // If we have no profiles return early.
2616 if (profiles.empty()) {
2617 return true;
2618 }
2619
2620 // Open the classpath elements. These will be used to filter out profile data that does
2621 // not belong to the classpath during merge.
2622 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002623 std::vector<std::string> dex_locations;
2624 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002625 return false;
2626 }
2627
2628 // If we could not open any files from the classpath return an error.
2629 if (apk_fds.empty()) {
2630 LOG(ERROR) << "Could not open any of the classpath elements.";
2631 return false;
2632 }
2633
2634 // Aggregate the profiles in batches of kAggregationBatchSize.
2635 // We do this to avoid opening a huge a amount of files.
2636 static constexpr size_t kAggregationBatchSize = 10;
2637
2638 std::vector<unique_fd> profiles_fd;
2639 for (size_t i = 0; i < profiles.size(); ) {
2640 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2641 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2642 if (fd.get() >= 0) {
2643 profiles_fd.push_back(std::move(fd));
2644 }
2645 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002646 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002647 args.SetupMerge(profiles_fd,
2648 snapshot_fd,
2649 apk_fds,
2650 dex_locations,
2651 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002652 pid_t pid = fork();
2653 if (pid == 0) {
2654 /* child -- drop privileges before continuing */
2655 drop_capabilities(AID_SYSTEM);
2656
Calin Juravle59f7ab82018-04-27 17:50:23 -07002657 // The introduction of new access flags into boot jars causes them to
2658 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002659 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002660 }
2661
2662 /* parent */
2663 int return_code = wait_child(pid);
2664 if (!WIFEXITED(return_code)) {
2665 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2666 return false;
2667 }
2668 return true;
2669 }
2670 return true;
2671}
2672
2673bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2674 const std::string& profile_name, const std::string& classpath) {
2675 if (app_id == -1) {
2676 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2677 } else {
2678 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2679 }
2680}
2681
Calin Juravlec3b049e2018-01-18 22:32:58 -08002682bool prepare_app_profile(const std::string& package_name,
2683 userid_t user_id,
2684 appid_t app_id,
2685 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002686 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002687 const std::unique_ptr<std::string>& dex_metadata) {
2688 // Prepare the current profile.
2689 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2690 /*is_secondary_dex*/ false);
2691 uid_t uid = multiuser_get_uid(user_id, app_id);
2692 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2693 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2694 return false;
2695 }
2696
2697 // Check if we need to install the profile from the dex metadata.
2698 if (dex_metadata == nullptr) {
2699 return true;
2700 }
2701
2702 // We have a dex metdata. Merge the profile into the reference profile.
2703 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2704 /*read_write*/ true, /*is_secondary_dex*/ false);
2705 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2706 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002707 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2708 if (apk_fd < 0) {
2709 PLOG(ERROR) << "Could not open code path " << code_path;
2710 return false;
2711 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002712
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002713 RunProfman args;
2714 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2715 std::move(ref_profile_fd),
2716 std::move(apk_fd),
2717 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002718 pid_t pid = fork();
2719 if (pid == 0) {
2720 /* child -- drop privileges before continuing */
2721 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2722 drop_capabilities(app_shared_gid);
2723
Calin Juravlef63d4792018-01-30 17:43:34 +00002724 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002725 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002726 }
2727
2728 /* parent */
2729 int return_code = wait_child(pid);
2730 if (!WIFEXITED(return_code)) {
2731 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2732 return false;
2733 }
2734 return true;
2735}
2736
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002737} // namespace installd
2738} // namespace android