blob: fa25c971d6f08390db792118825435ae0cd1a23f [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
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800304 const std::string dex2oat_isa_features_key =
305 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
306 std::string instruction_set_features_arg =
307 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700308
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800309 const std::string dex2oat_isa_variant_key =
310 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
311 std::string instruction_set_variant_arg =
312 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700313
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800314 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700315
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800316 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
317 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
318 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700319
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800320 // If we are booting without the real /data, don't spend time compiling.
321 std::string vold_decrypt = GetProperty("vold.decrypt", "");
322 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
323 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700324
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800325 std::string resolve_startup_string_arg =
326 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
327 "--resolve-startup-const-strings=%s");
328 if (resolve_startup_string_arg.empty()) {
329 // If empty, fall back to system property.
330 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800331 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
332 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800333 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800334
335 const std::string image_block_size_arg =
336 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
337 "--max-image-block-size=%s");
338
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800339 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800341 std::string image_format_arg;
342 if (image_fd >= 0) {
343 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000344 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000345
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800346 std::string dex2oat_large_app_threshold_arg =
347 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
Roland Levillain67a14f62019-01-23 15:59:50 +0000350 const char* dex2oat_bin = kDex2oatPath;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800351 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
352 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
353 if (is_debug_runtime() ||
354 (background_job_compile && is_debuggable_build() && !is_release)) {
355 if (access(kDex2oatDebugPath, X_OK) == 0) {
356 dex2oat_bin = kDex2oatDebugPath;
357 }
358 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000359
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800360 bool generate_minidebug_info = kEnableMinidebugInfo &&
361 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000362
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000363 std::string boot_image;
364 std::string use_apex_image =
365 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
366 ENABLE_APEX_IMAGE,
367 /*default_value=*/ "");
368 if (use_apex_image == "true") {
369 boot_image = StringPrintf("-Ximage:%s", kApexImage);
370 } else {
371 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
372 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000373
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800374 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
375 // use arraysize instead.
376 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
377 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
378 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
379 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
380 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
381 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
382 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
383 std::string dex2oat_compiler_filter_arg;
384 std::string dex2oat_swap_fd;
385 std::string dex2oat_image_fd;
386 std::string target_sdk_version_arg;
387 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000388 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800389 }
390 std::string class_loader_context_arg;
391 if (class_loader_context != nullptr) {
392 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
393 class_loader_context);
394 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000395
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800396 if (swap_fd >= 0) {
397 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
398 }
399 if (image_fd >= 0) {
400 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
401 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000402
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800403 // Compute compiler filter.
404 bool have_dex2oat_relocation_skip_flag = false;
405 if (skip_compilation) {
406 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
407 have_dex2oat_relocation_skip_flag = true;
408 } else if (compiler_filter != nullptr) {
409 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
410 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000411
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800412 if (dex2oat_compiler_filter_arg.empty()) {
413 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
414 "--compiler-filter=%s");
415 }
416
417 // Check whether all apps should be compiled debuggable.
418 if (!debuggable) {
419 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
420 }
421 std::string profile_arg;
422 if (profile_fd != -1) {
423 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
424 }
425
426 // Get the directory of the apk to pass as a base classpath directory.
427 std::string base_dir;
428 std::string apk_dir(input_file_name);
429 unsigned long dir_index = apk_dir.rfind('/');
430 bool has_base_dir = dir_index != std::string::npos;
431 if (has_base_dir) {
432 apk_dir = apk_dir.substr(0, dir_index);
433 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
434 }
435
436 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
437
438 std::string compilation_reason_arg = compilation_reason == nullptr
439 ? ""
440 : std::string("--compilation-reason=") + compilation_reason;
441
442 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
443
444 // Disable cdex if update input vdex is true since this combination of options is not
445 // supported.
446 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
447
448 AddArg(zip_fd_arg);
449 AddArg(zip_location_arg);
450 AddArg(input_vdex_fd_arg);
451 AddArg(output_vdex_fd_arg);
452 AddArg(oat_fd_arg);
453 AddArg(oat_location_arg);
454 AddArg(instruction_set_arg);
455
456 AddArg(instruction_set_variant_arg);
457 AddArg(instruction_set_features_arg);
458
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000459 AddRuntimeArg(boot_image);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800460 AddRuntimeArg(dex2oat_Xms_arg);
461 AddRuntimeArg(dex2oat_Xmx_arg);
462
463 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800464 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800465 AddArg(dex2oat_compiler_filter_arg);
466 AddArg(dex2oat_threads_arg);
467 AddArg(dex2oat_swap_fd);
468 AddArg(dex2oat_image_fd);
469
470 if (generate_debug_info) {
471 AddArg("--generate-debug-info");
472 }
473 if (debuggable) {
474 AddArg("--debuggable");
475 }
476 AddArg(image_format_arg);
477 AddArg(dex2oat_large_app_threshold_arg);
478
479 if (have_dex2oat_relocation_skip_flag) {
480 AddRuntimeArg(dex2oat_norelocation);
481 }
482 AddArg(profile_arg);
483 AddArg(base_dir);
484 AddArg(class_loader_context_arg);
485 if (generate_minidebug_info) {
486 AddArg(kMinidebugDex2oatFlag);
487 }
488 if (disable_cdex) {
489 AddArg(kDisableCompactDexFlag);
490 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000491 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800492 if (enable_hidden_api_checks) {
493 AddRuntimeArg("-Xhidden-api-checks");
494 }
495
496 if (dex_metadata_fd > -1) {
497 AddArg(dex_metadata_fd_arg);
498 }
499
500 AddArg(compilation_reason_arg);
501
502 // Do not add args after dex2oat_flags, they should override others for debugging.
503 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
504
505 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000506 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800507};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700508
509/*
510 * Whether dexopt should use a swap file when compiling an APK.
511 *
512 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
513 * itself, anyways).
514 *
515 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
516 *
517 * Otherwise, return true if this is a low-mem device.
518 *
519 * Otherwise, return default value.
520 */
521static bool kAlwaysProvideSwapFile = false;
522static bool kDefaultProvideSwapFile = true;
523
524static bool ShouldUseSwapFileForDexopt() {
525 if (kAlwaysProvideSwapFile) {
526 return true;
527 }
528
529 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700530 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
531 if (!dex2oat_prop_buf.empty()) {
532 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700533 }
534
535 // Shortcut for default value. This is an implementation optimization for the process sketched
536 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
537 // as low-mem is never returning false. The compiler will optimize this away if it can.
538 if (kDefaultProvideSwapFile) {
539 return true;
540 }
541
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700542 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700543 return true;
544 }
545
546 // Default value must be false here.
547 return kDefaultProvideSwapFile;
548}
549
Richard Uhler76cc0272016-12-08 10:46:35 +0000550static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700551 if (set_to_bg) {
552 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800553 PLOG(ERROR) << "set_sched_policy failed";
554 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700555 }
556 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800557 PLOG(ERROR) << "setpriority failed";
558 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700559 }
560 }
561}
562
Calin Juravle29591732017-11-20 17:46:19 -0800563static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
564 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800565 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800566 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800567 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800568 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800569 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700570 }
Calin Juravle114f0812017-03-08 19:05:07 -0800571 // Profiles should belong to the app; make sure of that by giving ownership to
572 // the app uid. If we cannot do that, there's no point in returning the fd
573 // since dex2oat/profman will fail with SElinux denials.
574 if (fchown(fd.get(), uid, uid) < 0) {
575 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800576 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800577 }
Calin Juravle29591732017-11-20 17:46:19 -0800578 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800579}
580
Calin Juravle29591732017-11-20 17:46:19 -0800581static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800582 // Do not follow symlinks when opening a profile:
583 // - primary profiles should not contain symlinks in their paths
584 // - secondary dex paths should have been already resolved and validated
585 flags |= O_NOFOLLOW;
586
Calin Juravle29591732017-11-20 17:46:19 -0800587 // Check if we need to create the profile
588 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
589 unique_fd fd;
590 if ((flags & O_CREAT) != 0) {
591 fd = create_profile(uid, profile, flags);
592 } else {
593 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
594 }
595
Calin Juravle114f0812017-03-08 19:05:07 -0800596 if (fd.get() < 0) {
597 if (errno != ENOENT) {
598 // Profiles might be missing for various reasons. For example, in a
599 // multi-user environment, the profile directory for one user can be created
600 // after we start a merge. In this case the current profile for that user
601 // will not be found.
602 // Also, the secondary dex profiles might be deleted by the app at any time,
603 // so we can't we need to prepare if they are missing.
604 PLOG(ERROR) << "Failed to open profile " << profile;
605 }
606 return invalid_unique_fd();
607 }
608
Jeff Sharkey90aff262016-12-12 14:28:24 -0700609 return fd;
610}
611
Calin Juravle824a64d2018-01-18 20:23:17 -0800612static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
613 const std::string& location, bool is_secondary_dex) {
614 std::string profile = create_current_profile_path(user, package_name, location,
615 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800616 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800617}
618
Calin Juravle824a64d2018-01-18 20:23:17 -0800619static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
620 const std::string& location, bool read_write, bool is_secondary_dex) {
621 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800622 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
623}
624
625static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800626 const std::string& location) {
627 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800628 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800629}
630
Calin Juravle824a64d2018-01-18 20:23:17 -0800631static void open_profile_files(uid_t uid, const std::string& package_name,
632 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800633 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700634 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800635 *reference_profile_fd = open_reference_profile(uid, package_name, location,
636 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700637
Calin Juravle114f0812017-03-08 19:05:07 -0800638 // For secondary dex files, we don't really need the user but we use it for sanity checks.
639 // Note: the user owning the dex file should be the current user.
640 std::vector<userid_t> users;
641 if (is_secondary_dex){
642 users.push_back(multiuser_get_user_id(uid));
643 } else {
644 users = get_known_users(/*volume_uuid*/ nullptr);
645 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700646 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800647 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
648 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700649 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800650 if (profile_fd.get() >= 0) {
651 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700652 }
653 }
654}
655
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
657static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
658static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
659static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
660static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
661
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800662class RunProfman : public ExecVHelper {
663 public:
664 void SetupArgs(const std::vector<unique_fd>& profile_fds,
665 const unique_fd& reference_profile_fd,
666 const std::vector<unique_fd>& apk_fds,
667 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800668 bool copy_and_update,
669 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000670 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800672 if (copy_and_update) {
673 CHECK_EQ(1u, profile_fds.size());
674 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000675 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800676 if (reference_profile_fd != -1) {
677 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000678 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800679
680 for (const unique_fd& fd : profile_fds) {
681 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
682 }
683
684 for (const unique_fd& fd : apk_fds) {
685 AddArg("--apk-fd=" + std::to_string(fd.get()));
686 }
687
688 for (const std::string& dex_location : dex_locations) {
689 AddArg("--dex-location=" + dex_location);
690 }
691
692 if (copy_and_update) {
693 AddArg("--copy-and-update-profile-key");
694 }
695
Calin Juravleb3a929d2018-12-11 14:40:00 -0800696 if (store_aggregation_counters) {
697 AddArg("--store-aggregation-counters");
698 }
699
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800700 // Do not add after dex2oat_flags, they should override others for debugging.
701 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800702 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700703
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800704 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
705 const unique_fd& reference_profile_fd,
706 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800707 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
708 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800709 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800710 reference_profile_fd,
711 apk_fds,
712 dex_locations,
713 /*copy_and_update=*/false,
714 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800715 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700716
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800717 void SetupCopyAndUpdate(unique_fd&& profile_fd,
718 unique_fd&& reference_profile_fd,
719 unique_fd&& apk_fd,
720 const std::string& dex_location) {
721 // The fds need to stay open longer than the scope of the function, so put them into a local
722 // variable vector.
723 profiles_fd_.push_back(std::move(profile_fd));
724 apk_fds_.push_back(std::move(apk_fd));
725 reference_profile_fd_ = std::move(reference_profile_fd);
726 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800727 SetupArgs(profiles_fd_,
728 reference_profile_fd_,
729 apk_fds_,
730 dex_locations,
731 /*copy_and_update=*/true,
732 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800733 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000734
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800735 void SetupDump(const std::vector<unique_fd>& profiles_fd,
736 const unique_fd& reference_profile_fd,
737 const std::vector<std::string>& dex_locations,
738 const std::vector<unique_fd>& apk_fds,
739 const unique_fd& output_fd) {
740 AddArg("--dump-only");
741 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800742 SetupArgs(profiles_fd,
743 reference_profile_fd,
744 apk_fds,
745 dex_locations,
746 /*copy_and_update=*/false,
747 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800748 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000749
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800750 void Exec() {
751 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
752 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000753
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800754 private:
755 unique_fd reference_profile_fd_;
756 std::vector<unique_fd> profiles_fd_;
757 std::vector<unique_fd> apk_fds_;
758};
Mathieu Chartier31636522018-11-09 23:53:07 +0000759
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800760
Calin Juravlef63d4792018-01-30 17:43:34 +0000761
Jeff Sharkey90aff262016-12-12 14:28:24 -0700762// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800763// The location is the package name for primary apks or the dex path for secondary dex files.
764// Returns true if there is enough information in the current profiles that makes it
765// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700766// If the return value is true all the current profiles would have been merged into
767// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800768static bool analyze_profiles(uid_t uid, const std::string& package_name,
769 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800770 std::vector<unique_fd> profiles_fd;
771 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800772 open_profile_files(uid, package_name, location, is_secondary_dex,
773 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800774 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 // Skip profile guided compilation because no profiles were found.
776 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700777 return false;
778 }
779
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800780 RunProfman profman_merge;
781 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700782 pid_t pid = fork();
783 if (pid == 0) {
784 /* child -- drop privileges before continuing */
785 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800786 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700787 }
788 /* parent */
789 int return_code = wait_child(pid);
790 bool need_to_compile = false;
791 bool should_clear_current_profiles = false;
792 bool should_clear_reference_profile = false;
793 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800794 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700795 } else {
796 return_code = WEXITSTATUS(return_code);
797 switch (return_code) {
798 case PROFMAN_BIN_RETURN_CODE_COMPILE:
799 need_to_compile = true;
800 should_clear_current_profiles = true;
801 should_clear_reference_profile = false;
802 break;
803 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
804 need_to_compile = false;
805 should_clear_current_profiles = false;
806 should_clear_reference_profile = false;
807 break;
808 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800809 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700810 need_to_compile = false;
811 should_clear_current_profiles = true;
812 should_clear_reference_profile = true;
813 break;
814 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
815 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
816 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800817 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700818 need_to_compile = false;
819 should_clear_current_profiles = false;
820 should_clear_reference_profile = false;
821 break;
822 default:
823 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800824 LOG(WARNING) << "Unknown error code while processing profiles for location "
825 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700826 need_to_compile = false;
827 should_clear_current_profiles = true;
828 should_clear_reference_profile = true;
829 break;
830 }
831 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800832
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800834 if (is_secondary_dex) {
835 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800836 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
837 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800838 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800839 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800840 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841 }
842 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800843 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700844 }
845 return need_to_compile;
846}
847
Calin Juravle114f0812017-03-08 19:05:07 -0800848// Decides if profile guided compilation is needed or not based on existing profiles.
849// The analysis is done for the primary apks of the given package.
850// Returns true if there is enough information in the current profiles that makes it
851// worth to recompile the package.
852// If the return value is true all the current profiles would have been merged into
853// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800854bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
855 const std::string& profile_name) {
856 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800857}
858
Calin Juravle408cd4a2018-01-20 23:34:18 -0800859bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
860 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800861 std::vector<unique_fd> profile_fds;
862 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800863 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
864 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865
Calin Juravle408cd4a2018-01-20 23:34:18 -0800866 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800867 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700868
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800869 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 const bool has_profiles = !profile_fds.empty();
871
872 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800873 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874 return false;
875 }
876
Calin Juravle114f0812017-03-08 19:05:07 -0800877 unique_fd output_fd(open(out_file_name.c_str(),
878 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800880 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700881 return false;
882 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800883
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800885 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800886 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
887 if (apk_fd == -1) {
888 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
889 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700890 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800891 dex_locations.push_back(get_location_from_path(code_path.c_str()));
892 apk_fds.push_back(std::move(apk_fd));
893
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800895 RunProfman profman_dump;
896 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700897 pid_t pid = fork();
898 if (pid == 0) {
899 /* child -- drop privileges before continuing */
900 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800901 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 }
903 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700904 int return_code = wait_child(pid);
905 if (!WIFEXITED(return_code)) {
906 LOG(WARNING) << "profman failed for package " << pkgname << ": "
907 << return_code;
908 return false;
909 }
910 return true;
911}
912
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700913bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800914 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700915 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
916 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800917 package_name,
918 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700919 /*read_write*/ true,
920 /*secondary*/ false));
921 if (in_fd.get() < 0) {
922 PLOG(WARNING) << "Could not open profile " << system_profile;
923 return false;
924 }
925 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800926 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700927 return false;
928 }
929
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700930 // As a security measure we want to write the profile information with the reduced capabilities
931 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700932 pid_t pid = fork();
933 if (pid == 0) {
934 /* child -- drop privileges before continuing */
935 drop_capabilities(packageUid);
936
937 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
938 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800939 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700940 }
941 // This implies that the app owning this profile is running
942 // (and has acquired the lock).
943 //
944 // The app never acquires the lock for the reference profiles of primary apks.
945 // Only dex2oat from installd will do that. Since installd is single threaded
946 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800947 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700948 return false;
949 }
950
951 bool truncated = ftruncate(out_fd.get(), 0) == 0;
952 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800953 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700954 }
955
956 // Copy over data.
957 static constexpr size_t kBufferSize = 4 * 1024;
958 char buffer[kBufferSize];
959 while (true) {
960 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
961 if (bytes == 0) {
962 break;
963 }
964 write(out_fd.get(), buffer, bytes);
965 }
966 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800967 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700968 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700969 // Use _exit since we don't want to run the global destructors in the child.
970 // b/62597429
971 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700972 }
973 /* parent */
974 int return_code = wait_child(pid);
975 return return_code == 0;
976}
977
Jeff Sharkey90aff262016-12-12 14:28:24 -0700978static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
979 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
980 if (EndsWith(oat_path, ".dex")) {
981 std::string new_path = oat_path;
982 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800983 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700984 return new_path;
985 }
986
987 // An odex entry. Not that this may not be an extension, e.g., in the OTA
988 // case (where the base name will have an extension for the B artifact).
989 size_t odex_pos = oat_path.rfind(".odex");
990 if (odex_pos != std::string::npos) {
991 std::string new_path = oat_path;
992 new_path.replace(odex_pos, strlen(".odex"), new_ext);
993 CHECK_NE(new_path.find(new_ext), std::string::npos);
994 return new_path;
995 }
996
997 // Don't know how to handle this.
998 return "";
999}
1000
1001// Translate the given oat path to an art (app image) path. An empty string
1002// denotes an error.
1003static std::string create_image_filename(const std::string& oat_path) {
1004 return replace_file_extension(oat_path, ".art");
1005}
1006
1007// Translate the given oat path to a vdex path. An empty string denotes an error.
1008static std::string create_vdex_filename(const std::string& oat_path) {
1009 return replace_file_extension(oat_path, ".vdex");
1010}
1011
Jeff Sharkey90aff262016-12-12 14:28:24 -07001012static int open_output_file(const char* file_name, bool recreate, int permissions) {
1013 int flags = O_RDWR | O_CREAT;
1014 if (recreate) {
1015 if (unlink(file_name) < 0) {
1016 if (errno != ENOENT) {
1017 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1018 }
1019 }
1020 flags |= O_EXCL;
1021 }
1022 return open(file_name, flags, permissions);
1023}
1024
Calin Juravle2289c0a2017-02-15 12:44:14 -08001025static bool set_permissions_and_ownership(
1026 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1027 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1028 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001029 if (fchmod(fd,
1030 S_IRUSR|S_IWUSR|S_IRGRP |
1031 (is_public ? S_IROTH : 0)) < 0) {
1032 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1033 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001034 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001035 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1036 return false;
1037 }
1038 return true;
1039}
1040
1041static bool IsOutputDalvikCache(const char* oat_dir) {
1042 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1043 // into '!'. Play it safe by handling it both.
1044 // TODO: ensure we never get null.
1045 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1046 return oat_dir == nullptr || oat_dir[0] == '!';
1047}
1048
Calin Juravled23dee72017-07-06 16:29:11 -07001049// Best-effort check whether we can fit the the path into our buffers.
1050// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1051// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1052// extension to the cache path (5 bytes).
1053// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1054static bool validate_dex_path_size(const std::string& dex_path) {
1055 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1056 LOG(ERROR) << "dex_path too long: " << dex_path;
1057 return false;
1058 }
1059 return true;
1060}
1061
Jeff Sharkey90aff262016-12-12 14:28:24 -07001062static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001063 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001064 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001065 return false;
1066 }
1067
1068 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001069 // Oat dirs for secondary dex files are already validated.
1070 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001071 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1072 return false;
1073 }
1074 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1075 return false;
1076 }
1077 } else {
1078 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1079 return false;
1080 }
1081 }
1082 return true;
1083}
1084
1085// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1086// on destruction. It will also run the given cleanup (unless told not to) after closing.
1087//
1088// Usage example:
1089//
Calin Juravle7a570e82017-01-14 16:23:30 -08001090// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001091// [name]() {
1092// unlink(name.c_str());
1093// });
1094// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1095// wrapper if captured as a reference.
1096//
1097// if (file.get() == -1) {
1098// // Error opening...
1099// }
1100//
1101// ...
1102// if (error) {
1103// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1104// // and delete the file (after the fd is closed).
1105// return -1;
1106// }
1107//
1108// (Success case)
1109// file.SetCleanup(false);
1110// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1111// // (leaving the file around; after the fd is closed).
1112//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001113class Dex2oatFileWrapper {
1114 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001115 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001116 }
1117
Calin Juravle7a570e82017-01-14 16:23:30 -08001118 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1119 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1120
1121 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1122 value_ = other.value_;
1123 cleanup_ = other.cleanup_;
1124 do_cleanup_ = other.do_cleanup_;
1125 auto_close_ = other.auto_close_;
1126 other.release();
1127 }
1128
1129 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1130 value_ = other.value_;
1131 cleanup_ = other.cleanup_;
1132 do_cleanup_ = other.do_cleanup_;
1133 auto_close_ = other.auto_close_;
1134 other.release();
1135 return *this;
1136 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001137
1138 ~Dex2oatFileWrapper() {
1139 reset(-1);
1140 }
1141
1142 int get() {
1143 return value_;
1144 }
1145
1146 void SetCleanup(bool cleanup) {
1147 do_cleanup_ = cleanup;
1148 }
1149
1150 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001151 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001152 close(value_);
1153 }
1154 if (do_cleanup_ && cleanup_ != nullptr) {
1155 cleanup_();
1156 }
1157
1158 value_ = new_value;
1159 }
1160
Calin Juravle7a570e82017-01-14 16:23:30 -08001161 void reset(int new_value, std::function<void ()> new_cleanup) {
1162 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001163 close(value_);
1164 }
1165 if (do_cleanup_ && cleanup_ != nullptr) {
1166 cleanup_();
1167 }
1168
1169 value_ = new_value;
1170 cleanup_ = new_cleanup;
1171 }
1172
Calin Juravle7a570e82017-01-14 16:23:30 -08001173 void DisableAutoClose() {
1174 auto_close_ = false;
1175 }
1176
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 void release() {
1179 value_ = -1;
1180 do_cleanup_ = false;
1181 cleanup_ = nullptr;
1182 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001183 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001185 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001187};
1188
Calin Juravle7a570e82017-01-14 16:23:30 -08001189// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001190Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1191 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001192
1193 // We don't create an image for secondary dex files.
1194 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001195 return Dex2oatFileWrapper();
1196 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001197
Calin Juravle7a570e82017-01-14 16:23:30 -08001198 const std::string image_path = create_image_filename(out_oat_path);
1199 if (image_path.empty()) {
1200 // Happens when the out_oat_path has an unknown extension.
1201 return Dex2oatFileWrapper();
1202 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001203
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001204 // In case there is a stale image, remove it now. Ignore any error.
1205 unlink(image_path.c_str());
1206
1207 // Not enabled, exit.
1208 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001209 return Dex2oatFileWrapper();
1210 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001211 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1212 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 return Dex2oatFileWrapper();
1214 }
1215 // Recreate is true since we do not want to modify a mapped image. If the app is
1216 // already running and we modify the image file, it can cause crashes (b/27493510).
1217 Dex2oatFileWrapper wrapper_fd(
1218 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1219 [image_path]() { unlink(image_path.c_str()); });
1220 if (wrapper_fd.get() < 0) {
1221 // Could not create application image file. Go on since we can compile without it.
1222 LOG(ERROR) << "installd could not create '" << image_path
1223 << "' for image file during dexopt";
1224 // If we have a valid image file path but no image fd, explicitly erase the image file.
1225 if (unlink(image_path.c_str()) < 0) {
1226 if (errno != ENOENT) {
1227 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1228 }
1229 }
1230 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001231 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001232 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1233 wrapper_fd.reset(-1);
1234 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001235
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 return wrapper_fd;
1237}
1238
1239// Creates the dexopt swap file if necessary and return its fd.
1240// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001241unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001242 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001243 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001244 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001245 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001246 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001247 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001248 if (swap_fd.get() < 0) {
1249 // Could not create swap file. Optimistically go on and hope that we can compile
1250 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001251 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001252 } else {
1253 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001254 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001255 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1256 }
1257 }
1258 return swap_fd;
1259}
1260
1261// Opens the reference profiles if needed.
1262// 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 -08001263Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001264 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001265 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001266 // If we are not profile guided compilation, or we are compiling system server
1267 // do not bother to open the profiles; we won't be using them.
1268 if (!profile_guided || (pkgname[0] == '*')) {
1269 return Dex2oatFileWrapper();
1270 }
1271
1272 // If this is a secondary dex path which is public do not open the profile.
1273 // We cannot compile public secondary dex paths with profiles. That's because
1274 // it will expose how the dex files are used by their owner.
1275 //
1276 // Note that the PackageManager is responsible to set the is_public flag for
1277 // primary apks and we do not check it here. In some cases, e.g. when
1278 // compiling with a public profile from the .dm file the PackageManager will
1279 // set is_public toghether with the profile guided compilation.
1280 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001281 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001282 }
Calin Juravle114f0812017-03-08 19:05:07 -08001283
1284 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001285 std::string location;
1286 if (is_secondary_dex) {
1287 location = dex_path;
1288 } else {
1289 if (profile_name == nullptr) {
1290 // This path is taken for system server re-compilation lunched from ZygoteInit.
1291 return Dex2oatFileWrapper();
1292 } else {
1293 location = profile_name;
1294 }
1295 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001296 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1297 is_secondary_dex);
1298 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1299 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001300 };
1301 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001302}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001303
Calin Juravle7a570e82017-01-14 16:23:30 -08001304// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1305// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001306bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001307 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001308 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001309 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1310 CHECK(in_vdex_wrapper_fd != nullptr);
1311 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001312 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1313 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001314 char in_odex_path[PKG_PATH_MAX];
1315 int dexopt_action = abs(dexopt_needed);
1316 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001317 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001318
1319 // Infer the name of the output VDEX.
1320 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1321 if (out_vdex_path_str.empty()) {
1322 return false;
1323 }
1324
1325 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001326 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001327 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1328 const char* path = nullptr;
1329 if (is_odex_location) {
1330 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1331 path = in_odex_path;
1332 } else {
1333 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001334 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001335 }
1336 } else {
1337 path = out_oat_path;
1338 }
1339 in_vdex_path_str = create_vdex_filename(path);
1340 if (in_vdex_path_str.empty()) {
1341 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001342 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001343 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001344 // We can update in place when all these conditions are met:
1345 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1346 // on /system typically cannot be updated in place).
1347 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1348 // cannot be currently used by a running process.
1349 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1350 // different vdex files to operate.
1351 update_vdex_in_place =
1352 (in_vdex_path_str == out_vdex_path_str) &&
1353 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1354 !profile_guided;
1355 if (update_vdex_in_place) {
1356 // Open the file read-write to be able to update it.
1357 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1358 if (in_vdex_wrapper_fd->get() == -1) {
1359 // If we failed to open the file, we cannot update it in place.
1360 update_vdex_in_place = false;
1361 }
1362 } else {
1363 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1364 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001365 }
1366
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001367 // If we are updating the vdex in place, we do not need to recreate a vdex,
1368 // and can use the same existing one.
1369 if (update_vdex_in_place) {
1370 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1371 // have bogus stale vdex files.
1372 out_vdex_wrapper_fd->reset(
1373 in_vdex_wrapper_fd->get(),
1374 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1375 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1376 // wrapper).
1377 in_vdex_wrapper_fd->DisableAutoClose();
1378 } else {
1379 out_vdex_wrapper_fd->reset(
1380 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1381 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1382 if (out_vdex_wrapper_fd->get() < 0) {
1383 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1384 return false;
1385 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001386 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001387 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001388 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001389 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1390 return false;
1391 }
1392
1393 // If we got here we successfully opened the vdex files.
1394 return true;
1395}
1396
1397// Opens the output oat file for the given apk.
1398// If successful it stores the output path into out_oat_path and returns true.
1399Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001400 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1401 char* out_oat_path) {
1402 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001403 return Dex2oatFileWrapper();
1404 }
1405 const std::string out_oat_path_str(out_oat_path);
1406 Dex2oatFileWrapper wrapper_fd(
1407 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1408 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1409 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001410 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001411 } else if (!set_permissions_and_ownership(
1412 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001413 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1414 wrapper_fd.reset(-1);
1415 }
1416 return wrapper_fd;
1417}
1418
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001419// Creates RDONLY fds for oat and vdex files, if exist.
1420// Returns false if it fails to create oat out path for the given apk path.
1421// Note that the method returns true even if the files could not be opened.
1422bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1423 const std::string& oat_dir,
1424 const std::string& instruction_set,
1425 bool is_secondary_dex,
1426 unique_fd* oat_file_fd,
1427 unique_fd* vdex_file_fd) {
1428 char oat_path[PKG_PATH_MAX];
1429 if (!create_oat_out_path(apk_path.c_str(),
1430 instruction_set.c_str(),
1431 oat_dir.c_str(),
1432 is_secondary_dex,
1433 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001434 LOG(ERROR) << "Could not create oat out path for "
1435 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001436 return false;
1437 }
1438 oat_file_fd->reset(open(oat_path, O_RDONLY));
1439 if (oat_file_fd->get() < 0) {
1440 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1441 }
1442
1443 std::string vdex_filename = create_vdex_filename(oat_path);
1444 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1445 if (vdex_file_fd->get() < 0) {
1446 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1447 }
1448
1449 return true;
1450}
1451
Calin Juravle7a570e82017-01-14 16:23:30 -08001452// Updates the access times of out_oat_path based on those from apk_path.
1453void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1454 struct stat input_stat;
1455 memset(&input_stat, 0, sizeof(input_stat));
1456 if (stat(apk_path, &input_stat) != 0) {
1457 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1458 return;
1459 }
1460
1461 struct utimbuf ut;
1462 ut.actime = input_stat.st_atime;
1463 ut.modtime = input_stat.st_mtime;
1464 if (utime(out_oat_path, &ut) != 0) {
1465 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1466 }
1467}
1468
Calin Juravle80a21252017-01-17 14:43:25 -08001469// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001470// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1471// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1472// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001473class RunDexoptAnalyzer : public ExecVHelper {
1474 public:
1475 RunDexoptAnalyzer(const std::string& dex_file,
1476 int vdex_fd,
1477 int oat_fd,
1478 int zip_fd,
1479 const std::string& instruction_set,
1480 const std::string& compiler_filter,
1481 bool profile_was_updated,
1482 bool downgrade,
1483 const char* class_loader_context) {
1484 CHECK_GE(zip_fd, 0);
1485 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001486 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001487
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001488 std::string dex_file_arg = "--dex-file=" + dex_file;
1489 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1490 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1491 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1492 std::string isa_arg = "--isa=" + instruction_set;
1493 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1494 const char* assume_profile_changed = "--assume-profile-changed";
1495 const char* downgrade_flag = "--downgrade";
1496 std::string class_loader_context_arg = "--class-loader-context=";
1497 if (class_loader_context != nullptr) {
1498 class_loader_context_arg += class_loader_context;
1499 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001500
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001501 // program name, dex file, isa, filter
1502 AddArg(dex_file_arg);
1503 AddArg(isa_arg);
1504 AddArg(compiler_filter_arg);
1505 if (oat_fd >= 0) {
1506 AddArg(oat_fd_arg);
1507 }
1508 if (vdex_fd >= 0) {
1509 AddArg(vdex_fd_arg);
1510 }
1511 AddArg(zip_fd_arg.c_str());
1512 if (profile_was_updated) {
1513 AddArg(assume_profile_changed);
1514 }
1515 if (downgrade) {
1516 AddArg(downgrade_flag);
1517 }
1518 if (class_loader_context != nullptr) {
1519 AddArg(class_loader_context_arg.c_str());
1520 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001521
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001522 PrepareArgs(dexoptanalyzer_bin);
1523 }
1524};
Calin Juravle80a21252017-01-17 14:43:25 -08001525
1526// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001527static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001528 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001529 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001530 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001531 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001532 return false;
1533 }
Calin Juravle114f0812017-03-08 19:05:07 -08001534 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001535
Calin Juravle80a21252017-01-17 14:43:25 -08001536 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001537 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1538 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001539 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001540 return false;
1541 }
1542
1543 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001544 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001545
Calin Juravle7d765462017-09-04 15:57:10 -07001546 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001547 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001548 return false;
1549 }
1550
1551 return true;
1552}
1553
Calin Juravle7d765462017-09-04 15:57:10 -07001554// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1555// secondary dex files. This return codes are returned by the child process created for
1556// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001557
Andreas Gampe194fe422018-02-28 20:16:19 -08001558enum DexoptAnalyzerSkipCodes {
1559 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001560 // Specific errors are encoded in the name.
1561 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1562 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1563 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1564 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1565 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001566 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001567 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001568};
Calin Juravle7d765462017-09-04 15:57:10 -07001569
1570// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001571// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1572// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001573// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1574// of dexoptanalyzer.
1575static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001576 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001577 // The result values are defined in dexoptanalyzer.
1578 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001579 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001580 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001581 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001582 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001583 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001584 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001585 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001586 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001587 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1588 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001589 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1590 " Expected odex file status for secondary dex %s"
1591 " : dexoptanalyzer result=%d",
1592 dex_path.c_str(),
1593 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001594 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001595 }
1596
1597 // Use a second switch for enum switch-case analysis.
1598 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001599 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001600 // If the file does not exist there's no need for dexopt.
1601 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1602 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001603
1604 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1605 *error_msg = "Dexoptanalyzer path validation failed";
1606 return false;
1607 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1608 *error_msg = "Dexoptanalyzer open zip failed";
1609 return false;
1610 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1611 *error_msg = "Dexoptanalyzer dir preparation failed";
1612 return false;
1613 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1614 *error_msg = "Dexoptanalyzer open output failed";
1615 return false;
1616 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1617 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001618 return false;
1619 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001620
1621 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1622 dex_path.c_str(),
1623 result);
1624 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001625}
1626
Calin Juravle7d765462017-09-04 15:57:10 -07001627enum SecondaryDexAccess {
1628 kSecondaryDexAccessReadOk = 0,
1629 kSecondaryDexAccessDoesNotExist = 1,
1630 kSecondaryDexAccessPermissionError = 2,
1631 kSecondaryDexAccessIOError = 3
1632};
1633
1634static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1635 // Check if the path exists and can be read. If not, there's nothing to do.
1636 if (access(dex_path.c_str(), R_OK) == 0) {
1637 return kSecondaryDexAccessReadOk;
1638 } else {
1639 if (errno == ENOENT) {
1640 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1641 return kSecondaryDexAccessDoesNotExist;
1642 } else {
1643 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1644 return errno == EACCES
1645 ? kSecondaryDexAccessPermissionError
1646 : kSecondaryDexAccessIOError;
1647 }
1648 }
1649}
1650
1651static bool is_file_public(const std::string& filename) {
1652 struct stat file_stat;
1653 if (stat(filename.c_str(), &file_stat) == 0) {
1654 return (file_stat.st_mode & S_IROTH) != 0;
1655 }
1656 return false;
1657}
1658
1659// Create the oat file structure for the secondary dex 'dex_path' and assign
1660// the individual path component to the 'out_' parameters.
1661static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001662 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001663 size_t dirIndex = dex_path.rfind('/');
1664 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001665 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001666 return false;
1667 }
1668 // TODO(calin): we have similar computations in at lest 3 other places
1669 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1670 // using string append.
1671 std::string apk_dir = dex_path.substr(0, dirIndex);
1672 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1673 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1674
1675 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1676 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001677 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001678 return false;
1679 }
1680 return true;
1681}
1682
1683// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1684// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001685static bool validate_dexopt_storage_flags(int dexopt_flags,
1686 int* out_storage_flag,
1687 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001688 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1689 *out_storage_flag = FLAG_STORAGE_CE;
1690 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001691 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001692 return false;
1693 }
1694 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1695 *out_storage_flag = FLAG_STORAGE_DE;
1696 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001697 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001698 return false;
1699 }
1700 return true;
1701}
1702
Calin Juravlec9eab382017-01-25 01:17:17 -08001703// 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 -08001704// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1705// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001706// When returning true, the output parameters will be:
1707// - is_public_out: whether or not the oat file should not be made public
1708// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1709// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001710static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001711 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001712 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001713 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1714 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001715 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001716 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001717 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1718 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001719 return false;
1720 }
Calin Juravle7d765462017-09-04 15:57:10 -07001721 // Compute the oat dir as it's not easy to extract it from the child computation.
1722 char oat_path[PKG_PATH_MAX];
1723 char oat_dir[PKG_PATH_MAX];
1724 char oat_isa_dir[PKG_PATH_MAX];
1725 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001726 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1727 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001728 return false;
1729 }
Calin Juravle7d765462017-09-04 15:57:10 -07001730 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001731
Calin Juravle80a21252017-01-17 14:43:25 -08001732 pid_t pid = fork();
1733 if (pid == 0) {
1734 // child -- drop privileges before continuing.
1735 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001736
1737 // Validate the path structure.
1738 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1739 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001740 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001741 }
1742
1743 // Open the dex file.
1744 unique_fd zip_fd;
1745 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1746 if (zip_fd.get() < 0) {
1747 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001748 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001749 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001750 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001751 }
1752 }
1753
1754 // Prepare the oat directories.
1755 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001756 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001757 }
1758
1759 // Open the vdex/oat files if any.
1760 unique_fd oat_file_fd;
1761 unique_fd vdex_file_fd;
1762 if (!maybe_open_oat_and_vdex_file(dex_path,
1763 *oat_dir_out,
1764 instruction_set,
1765 true /* is_secondary_dex */,
1766 &oat_file_fd,
1767 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001768 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001769 }
1770
1771 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001772 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1773 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001774
1775 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001776 // Note that we do not do it before the fork since opening the files is required to happen
1777 // after forking.
1778 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1779 vdex_file_fd.get(),
1780 oat_file_fd.get(),
1781 zip_fd.get(),
1782 instruction_set,
1783 compiler_filter, profile_was_updated,
1784 downgrade,
1785 class_loader_context);
1786 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001787 }
1788
1789 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001790 int result = wait_child(pid);
1791 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001792 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1793 dex_path.c_str(),
1794 result);
1795 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001796 return false;
1797 }
1798 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001799 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001800 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1801 result,
1802 dexopt_needed_out,
1803 error_msg);
1804 if (!success) {
1805 LOG(ERROR) << *error_msg;
1806 }
Calin Juravle7d765462017-09-04 15:57:10 -07001807
1808 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1809
Calin Juravle80a21252017-01-17 14:43:25 -08001810 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001811 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1812 // makes the code simpler; force compilation is only needed during tests).
1813 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001814 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001815 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001816 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1817 }
1818
Calin Juravle7d765462017-09-04 15:57:10 -07001819 // Check if we should make the oat file public.
1820 // Note that if the dex file is not public the compiled code cannot be made public.
1821 // It is ok to check this flag outside in the parent process.
1822 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1823
Calin Juravle80a21252017-01-17 14:43:25 -08001824 return success;
1825}
1826
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001827static std::string format_dexopt_error(int status, const char* dex_path) {
1828 if (WIFEXITED(status)) {
1829 int int_code = WEXITSTATUS(status);
1830 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1831 if (code_name != nullptr) {
1832 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1833 }
1834 }
1835 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001836}
1837
Calin Juravlec9eab382017-01-25 01:17:17 -08001838int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001839 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001840 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001841 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001842 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001843 CHECK(pkgname != nullptr);
1844 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001845 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001846 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1847 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001848
Calin Juravled23dee72017-07-06 16:29:11 -07001849 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001850 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001851 return -1;
1852 }
1853
1854 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001855 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1856 class_loader_context);
1857 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001858 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001859 }
1860
Calin Juravleebc8a792017-04-04 20:21:05 -07001861 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001862 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1863 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1864 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001865 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001866 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001867 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001868 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001869 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001870
1871 // Check if we're dealing with a secondary dex file and if we need to compile it.
1872 std::string oat_dir_str;
1873 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001874 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001875 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001876 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001877 oat_dir = oat_dir_str.c_str();
1878 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1879 return 0; // Nothing to do, report success.
1880 }
1881 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001882 if (error_msg->empty()) { // TODO: Make this a CHECK.
1883 *error_msg = "Failed processing secondary.";
1884 }
Calin Juravle80a21252017-01-17 14:43:25 -08001885 return -1; // We had an error, logged in the process method.
1886 }
1887 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001888 // Currently these flags are only use for secondary dex files.
1889 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001890 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1891 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1892 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001893
1894 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001895 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001896 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001897 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1898 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001899 return -1;
1900 }
1901
1902 // Create the output OAT file.
1903 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001904 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001905 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001906 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001907 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001908 return -1;
1909 }
1910
1911 // Open vdex files.
1912 Dex2oatFileWrapper in_vdex_fd;
1913 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001914 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1915 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001916 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001917 return -1;
1918 }
1919
Calin Juravlecb556e32017-04-04 20:22:50 -07001920 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1921 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1922 // fully inherit their parent context).
1923 // Note that for primary apk the oat files are created before, in a separate installd
1924 // call which also does the restorecon. TODO(calin): unify the paths.
1925 if (is_secondary_dex) {
1926 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1927 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001928 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1929 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001930 return -1;
1931 }
1932 }
1933
Jeff Sharkey90aff262016-12-12 14:28:24 -07001934 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001935 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001936
Calin Juravle7a570e82017-01-14 16:23:30 -08001937 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001938 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1939 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001940
Calin Juravle7a570e82017-01-14 16:23:30 -08001941 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001942 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001943 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001944
Calin Juravle62c5a372018-02-01 17:03:23 +00001945 unique_fd dex_metadata_fd;
1946 if (dex_metadata_path != nullptr) {
1947 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1948 if (dex_metadata_fd.get() < 0) {
1949 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1950 }
1951 }
1952
Andreas Gampe023b2242018-02-28 16:03:25 -08001953 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001954
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001955 RunDex2Oat runner(input_fd.get(),
1956 out_oat_fd.get(),
1957 in_vdex_fd.get(),
1958 out_vdex_fd.get(),
1959 image_fd.get(),
1960 dex_path,
1961 out_oat_path,
1962 swap_fd.get(),
1963 instruction_set,
1964 compiler_filter,
1965 debuggable,
1966 boot_complete,
1967 background_job_compile,
1968 reference_profile_fd.get(),
1969 class_loader_context,
1970 target_sdk_version,
1971 enable_hidden_api_checks,
1972 generate_compact_dex,
1973 dex_metadata_fd.get(),
1974 compilation_reason);
1975
Jeff Sharkey90aff262016-12-12 14:28:24 -07001976 pid_t pid = fork();
1977 if (pid == 0) {
1978 /* child -- drop privileges before continuing */
1979 drop_capabilities(uid);
1980
Vladimir Marko1fea89a2019-02-08 15:11:59 +00001981 // Clear BOOTCLASSPATH.
1982 // Let dex2oat use the BCP from boot image, excluding updatable BCP
1983 // modules for AOT to avoid app recompilation after their upgrades.
1984 unsetenv("BOOTCLASSPATH");
1985
Richard Uhler76cc0272016-12-08 10:46:35 +00001986 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001987 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001988 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001989 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001990 }
1991
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001992 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001993 } else {
1994 int res = wait_child(pid);
1995 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001996 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001997 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001998 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1999 << std::hex << std::setw(4) << res << ", process failed";
2000 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002001 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002002 }
2003 }
2004
Calin Juravlec9eab382017-01-25 01:17:17 -08002005 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002006
2007 // We've been successful, don't delete output.
2008 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002009 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002010 image_fd.SetCleanup(false);
2011 reference_profile_fd.SetCleanup(false);
2012
2013 return 0;
2014}
2015
Calin Juravlec9eab382017-01-25 01:17:17 -08002016// Try to remove the given directory. Log an error if the directory exists
2017// and is empty but could not be removed.
2018static bool rmdir_if_empty(const char* dir) {
2019 if (rmdir(dir) == 0) {
2020 return true;
2021 }
2022 if (errno == ENOENT || errno == ENOTEMPTY) {
2023 return true;
2024 }
2025 PLOG(ERROR) << "Failed to remove dir: " << dir;
2026 return false;
2027}
2028
2029// Try to unlink the given file. Log an error if the file exists and could not
2030// be unlinked.
2031static bool unlink_if_exists(const std::string& file) {
2032 if (unlink(file.c_str()) == 0) {
2033 return true;
2034 }
2035 if (errno == ENOENT) {
2036 return true;
2037
2038 }
2039 PLOG(ERROR) << "Could not unlink: " << file;
2040 return false;
2041}
2042
Calin Juravle7d765462017-09-04 15:57:10 -07002043enum ReconcileSecondaryDexResult {
2044 kReconcileSecondaryDexExists = 0,
2045 kReconcileSecondaryDexCleanedUp = 1,
2046 kReconcileSecondaryDexValidationError = 2,
2047 kReconcileSecondaryDexCleanUpError = 3,
2048 kReconcileSecondaryDexAccessIOError = 4,
2049};
Calin Juravlec9eab382017-01-25 01:17:17 -08002050
2051// Reconcile the secondary dex 'dex_path' and its generated oat files.
2052// Return true if all the parameters are valid and the secondary dex file was
2053// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2054// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2055// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2056// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2057// Return false if there were errors during processing. In this case
2058// out_secondary_dex_exists will be set to false.
2059bool reconcile_secondary_dex_file(const std::string& dex_path,
2060 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2061 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2062 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002063 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002064 if (isas.size() == 0) {
2065 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2066 return false;
2067 }
2068
Calin Juravle7d765462017-09-04 15:57:10 -07002069 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2070 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2071 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002072 return false;
2073 }
2074
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002075 // As a security measure we want to unlink art artifacts with the reduced capabilities
2076 // of the package user id. So we fork and drop capabilities in the child.
2077 pid_t pid = fork();
2078 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002079 /* child -- drop privileges before continuing */
2080 drop_capabilities(uid);
2081
2082 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2083 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2084 uid, storage_flag)) {
2085 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2086 _exit(kReconcileSecondaryDexValidationError);
2087 }
2088
2089 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2090 switch (access_check) {
2091 case kSecondaryDexAccessDoesNotExist:
2092 // File does not exist. Proceed with cleaning.
2093 break;
2094 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2095 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2096 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2097 default:
2098 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2099 _exit(kReconcileSecondaryDexValidationError);
2100 }
2101
2102 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002103 char oat_path[PKG_PATH_MAX];
2104 char oat_dir[PKG_PATH_MAX];
2105 char oat_isa_dir[PKG_PATH_MAX];
2106 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002107 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002108 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002109 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002110 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2111 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002112 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002113 }
Calin Juravle51314092017-05-18 15:33:05 -07002114
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002115 // Delete oat/vdex/art files.
2116 result = unlink_if_exists(oat_path) && result;
2117 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2118 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002119
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002120 // Delete profiles.
2121 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002122 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002123 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002124 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002125 result = unlink_if_exists(current_profile) && result;
2126 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002127
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002128 // We upgraded once the location of current profile for secondary dex files.
2129 // Check for any previous left-overs and remove them as well.
2130 std::string old_current_profile = dex_path + ".prof";
2131 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002132
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002133 // Try removing the directories as well, they might be empty.
2134 result = rmdir_if_empty(oat_isa_dir) && result;
2135 result = rmdir_if_empty(oat_dir) && result;
2136 }
Calin Juravle7d765462017-09-04 15:57:10 -07002137 if (!result) {
2138 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2139 }
2140 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002141 }
2142
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002143 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002144 if (!WIFEXITED(return_code)) {
2145 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2146 } else {
2147 return_code = WEXITSTATUS(return_code);
2148 }
2149
2150 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2151
2152 switch (return_code) {
2153 case kReconcileSecondaryDexCleanedUp:
2154 case kReconcileSecondaryDexValidationError:
2155 // If we couldn't validate assume the dex file does not exist.
2156 // This will purge the entry from the PM records.
2157 *out_secondary_dex_exists = false;
2158 return true;
2159 case kReconcileSecondaryDexExists:
2160 *out_secondary_dex_exists = true;
2161 return true;
2162 case kReconcileSecondaryDexAccessIOError:
2163 // We had an access IO error.
2164 // Return false so that we can try again.
2165 // The value of out_secondary_dex_exists does not matter in this case and by convention
2166 // is set to false.
2167 *out_secondary_dex_exists = false;
2168 return false;
2169 default:
2170 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2171 *out_secondary_dex_exists = false;
2172 return false;
2173 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002174}
2175
Alan Stokesa25d90c2017-10-16 10:56:00 +01002176// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2177// Returns true if all parameters are valid and the hash successfully computed and stored in
2178// out_secondary_dex_hash.
2179// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2180// the app.
2181// For any other errors (e.g. if any of the parameters are invalid) returns false.
2182bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2183 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2184 std::vector<uint8_t>* out_secondary_dex_hash) {
2185 out_secondary_dex_hash->clear();
2186
2187 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2188
2189 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2190 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2191 << storage_flag;
2192 return false;
2193 }
2194
2195 // Pipe to get the hash result back from our child process.
2196 unique_fd pipe_read, pipe_write;
2197 if (!Pipe(&pipe_read, &pipe_write)) {
2198 PLOG(ERROR) << "Failed to create pipe";
2199 return false;
2200 }
2201
2202 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2203 // access data the app itself can access.
2204 pid_t pid = fork();
2205 if (pid == 0) {
2206 // child -- drop privileges before continuing
2207 drop_capabilities(uid);
2208 pipe_read.reset();
2209
2210 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2211 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002212 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002213 }
2214
2215 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2216 if (fd == -1) {
2217 if (errno == EACCES || errno == ENOENT) {
2218 // Not treated as an error.
2219 _exit(0);
2220 }
2221 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002222 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002223 }
2224
2225 SHA256_CTX ctx;
2226 SHA256_Init(&ctx);
2227
2228 std::vector<uint8_t> buffer(65536);
2229 while (true) {
2230 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2231 if (bytes_read == 0) {
2232 break;
2233 } else if (bytes_read == -1) {
2234 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002235 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002236 }
2237
2238 SHA256_Update(&ctx, buffer.data(), bytes_read);
2239 }
2240
2241 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2242 SHA256_Final(hash.data(), &ctx);
2243 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002244 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002245 }
2246
2247 _exit(0);
2248 }
2249
2250 // parent
2251 pipe_write.reset();
2252
2253 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2254 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2255 out_secondary_dex_hash->clear();
2256 }
2257 return wait_child(pid) == 0;
2258}
2259
Jeff Sharkey90aff262016-12-12 14:28:24 -07002260// Helper for move_ab, so that we can have common failure-case cleanup.
2261static bool unlink_and_rename(const char* from, const char* to) {
2262 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2263 // return a failure.
2264 struct stat s;
2265 if (stat(to, &s) == 0) {
2266 if (!S_ISREG(s.st_mode)) {
2267 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2268 return false;
2269 }
2270 if (unlink(to) != 0) {
2271 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2272 return false;
2273 }
2274 } else {
2275 // This may be a permission problem. We could investigate the error code, but we'll just
2276 // let the rename failure do the work for us.
2277 }
2278
2279 // Try to rename "to" to "from."
2280 if (rename(from, to) != 0) {
2281 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2282 return false;
2283 }
2284 return true;
2285}
2286
2287// Move/rename a B artifact (from) to an A artifact (to).
2288static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2289 // Check whether B exists.
2290 {
2291 struct stat s;
2292 if (stat(b_path.c_str(), &s) != 0) {
2293 // Silently ignore for now. The service calling this isn't smart enough to understand
2294 // lack of artifacts at the moment.
2295 return false;
2296 }
2297 if (!S_ISREG(s.st_mode)) {
2298 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2299 // Try to unlink, but swallow errors.
2300 unlink(b_path.c_str());
2301 return false;
2302 }
2303 }
2304
2305 // Rename B to A.
2306 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2307 // Delete the b_path so we don't try again (or fail earlier).
2308 if (unlink(b_path.c_str()) != 0) {
2309 PLOG(ERROR) << "Could not unlink " << b_path;
2310 }
2311
2312 return false;
2313 }
2314
2315 return true;
2316}
2317
2318bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2319 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002320 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2321 if (slot_suffix.empty()) {
2322 return false;
2323 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002324
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002325 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2326 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2327 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002328 }
2329
2330 // Validate other inputs.
2331 if (validate_apk_path(apk_path) != 0) {
2332 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2333 return false;
2334 }
2335 if (validate_apk_path(oat_dir) != 0) {
2336 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2337 return false;
2338 }
2339
2340 char a_path[PKG_PATH_MAX];
2341 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2342 return false;
2343 }
2344 const std::string a_vdex_path = create_vdex_filename(a_path);
2345 const std::string a_image_path = create_image_filename(a_path);
2346
2347 // B path = A path + slot suffix.
2348 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2349 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2350 const std::string b_image_path = StringPrintf("%s.%s",
2351 a_image_path.c_str(),
2352 slot_suffix.c_str());
2353
2354 bool success = true;
2355 if (move_ab_path(b_path, a_path)) {
2356 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2357 // Note: we can live without an app image. As such, ignore failure to move the image file.
2358 // If we decide to require the app image, or the app image being moved correctly,
2359 // then change accordingly.
2360 constexpr bool kIgnoreAppImageFailure = true;
2361
2362 if (!a_image_path.empty()) {
2363 if (!move_ab_path(b_image_path, a_image_path)) {
2364 unlink(a_image_path.c_str());
2365 if (!kIgnoreAppImageFailure) {
2366 success = false;
2367 }
2368 }
2369 }
2370 } else {
2371 // Cleanup: delete B image, ignore errors.
2372 unlink(b_image_path.c_str());
2373 success = false;
2374 }
2375 } else {
2376 // Cleanup: delete B image, ignore errors.
2377 unlink(b_vdex_path.c_str());
2378 unlink(b_image_path.c_str());
2379 success = false;
2380 }
2381 return success;
2382}
2383
2384bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2385 // Delete the oat/odex file.
2386 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002387 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002388 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002389 return false;
2390 }
2391
2392 // In case of a permission failure report the issue. Otherwise just print a warning.
2393 auto unlink_and_check = [](const char* path) -> bool {
2394 int result = unlink(path);
2395 if (result != 0) {
2396 if (errno == EACCES || errno == EPERM) {
2397 PLOG(ERROR) << "Could not unlink " << path;
2398 return false;
2399 }
2400 PLOG(WARNING) << "Could not unlink " << path;
2401 }
2402 return true;
2403 };
2404
2405 // Delete the oat/odex file.
2406 bool return_value_oat = unlink_and_check(out_path);
2407
2408 // Derive and delete the app image.
2409 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2410
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002411 // Derive and delete the vdex file.
2412 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2413
Jeff Sharkey90aff262016-12-12 14:28:24 -07002414 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002415 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002416}
2417
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002418static bool is_absolute_path(const std::string& path) {
2419 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2420 LOG(ERROR) << "Invalid absolute path " << path;
2421 return false;
2422 } else {
2423 return true;
2424 }
2425}
2426
2427static bool is_valid_instruction_set(const std::string& instruction_set) {
2428 // TODO: add explicit whitelisting of instruction sets
2429 if (instruction_set.find('/') != std::string::npos) {
2430 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2431 return false;
2432 } else {
2433 return true;
2434 }
2435}
2436
2437bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2438 const char *apk_path, const char *instruction_set) {
2439 std::string oat_dir_ = oat_dir;
2440 std::string apk_path_ = apk_path;
2441 std::string instruction_set_ = instruction_set;
2442
2443 if (!is_absolute_path(oat_dir_)) return false;
2444 if (!is_absolute_path(apk_path_)) return false;
2445 if (!is_valid_instruction_set(instruction_set_)) return false;
2446
2447 std::string::size_type end = apk_path_.rfind('.');
2448 std::string::size_type start = apk_path_.rfind('/', end);
2449 if (end == std::string::npos || start == std::string::npos) {
2450 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2451 return false;
2452 }
2453
2454 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2455 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2456 const char* res = res_.c_str();
2457 if (strlen(res) >= PKG_PATH_MAX) {
2458 LOG(ERROR) << "Result too large";
2459 return false;
2460 } else {
2461 strlcpy(path, res, PKG_PATH_MAX);
2462 return true;
2463 }
2464}
2465
2466bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2467 const char *instruction_set) {
2468 std::string apk_path_ = apk_path;
2469 std::string instruction_set_ = instruction_set;
2470
2471 if (!is_absolute_path(apk_path_)) return false;
2472 if (!is_valid_instruction_set(instruction_set_)) return false;
2473
2474 std::string::size_type end = apk_path_.rfind('.');
2475 std::string::size_type start = apk_path_.rfind('/', end);
2476 if (end == std::string::npos || start == std::string::npos) {
2477 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2478 return false;
2479 }
2480
2481 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2482 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2483}
2484
2485bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2486 const char *instruction_set) {
2487 std::string src_ = src;
2488 std::string instruction_set_ = instruction_set;
2489
2490 if (!is_absolute_path(src_)) return false;
2491 if (!is_valid_instruction_set(instruction_set_)) return false;
2492
2493 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2494 if (*it == '/') {
2495 *it = '@';
2496 }
2497 }
2498
2499 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2500 + DALVIK_CACHE_POSTFIX;
2501 const char* res = res_.c_str();
2502 if (strlen(res) >= PKG_PATH_MAX) {
2503 LOG(ERROR) << "Result too large";
2504 return false;
2505 } else {
2506 strlcpy(path, res, PKG_PATH_MAX);
2507 return true;
2508 }
2509}
2510
Calin Juravle59f7ab82018-04-27 17:50:23 -07002511bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2512 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002513 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2514 for (const std::string& elem : classpaths_elems) {
2515 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2516 if (fd < 0) {
2517 PLOG(ERROR) << "Could not open classpath elem " << elem;
2518 return false;
2519 } else {
2520 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002521 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002522 }
2523 }
2524 return true;
2525}
2526
2527static bool create_app_profile_snapshot(int32_t app_id,
2528 const std::string& package_name,
2529 const std::string& profile_name,
2530 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002531 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2532
Calin Juravle824a64d2018-01-18 20:23:17 -08002533 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002534 if (snapshot_fd < 0) {
2535 return false;
2536 }
2537
2538 std::vector<unique_fd> profiles_fd;
2539 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002540 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2541 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002542 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2543 return false;
2544 }
2545
2546 profiles_fd.push_back(std::move(reference_profile_fd));
2547
Calin Juravle0d0a4922018-01-23 19:54:11 -08002548 // Open the class paths elements. These will be used to filter out profile data that does
2549 // not belong to the classpath during merge.
2550 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002551 std::vector<std::string> dex_locations;
2552 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002553 return false;
2554 }
2555
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002556 RunProfman args;
2557 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002558 pid_t pid = fork();
2559 if (pid == 0) {
2560 /* child -- drop privileges before continuing */
2561 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002562 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002563 }
2564
2565 /* parent */
2566 int return_code = wait_child(pid);
2567 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002568 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002569 return false;
2570 }
2571
2572 return true;
2573}
2574
Calin Juravle0d0a4922018-01-23 19:54:11 -08002575static bool create_boot_image_profile_snapshot(const std::string& package_name,
2576 const std::string& profile_name,
2577 const std::string& classpath) {
2578 // The reference profile directory for the android package might not be prepared. Do it now.
2579 const std::string ref_profile_dir =
2580 create_primary_reference_profile_package_dir_path(package_name);
2581 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2582 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2583 return false;
2584 }
2585
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002586 // Return false for empty class path since it may otherwise return true below if profiles is
2587 // empty.
2588 if (classpath.empty()) {
2589 PLOG(ERROR) << "Class path is empty";
2590 return false;
2591 }
2592
Calin Juravle0d0a4922018-01-23 19:54:11 -08002593 // Open and create the snapshot profile.
2594 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2595
2596 // Collect all non empty profiles.
2597 // The collection will traverse all applications profiles and find the non empty files.
2598 // This has the potential of inspecting a large number of files and directories (depending
2599 // on the number of applications and users). So there is a slight increase in the chance
2600 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2601 // fail the snapshot and aggregate whatever profile we could open.
2602 //
2603 // The profile snapshot is a best effort based on available data it's ok if some data
2604 // from some apps is missing. It will be counter productive for the snapshot to fail
2605 // because we could not open or read some of the files.
2606 std::vector<std::string> profiles;
2607 if (!collect_profiles(&profiles)) {
2608 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2609 }
2610
2611 // If we have no profiles return early.
2612 if (profiles.empty()) {
2613 return true;
2614 }
2615
2616 // Open the classpath elements. These will be used to filter out profile data that does
2617 // not belong to the classpath during merge.
2618 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002619 std::vector<std::string> dex_locations;
2620 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002621 return false;
2622 }
2623
2624 // If we could not open any files from the classpath return an error.
2625 if (apk_fds.empty()) {
2626 LOG(ERROR) << "Could not open any of the classpath elements.";
2627 return false;
2628 }
2629
2630 // Aggregate the profiles in batches of kAggregationBatchSize.
2631 // We do this to avoid opening a huge a amount of files.
2632 static constexpr size_t kAggregationBatchSize = 10;
2633
2634 std::vector<unique_fd> profiles_fd;
2635 for (size_t i = 0; i < profiles.size(); ) {
2636 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2637 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2638 if (fd.get() >= 0) {
2639 profiles_fd.push_back(std::move(fd));
2640 }
2641 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002642 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002643 args.SetupMerge(profiles_fd,
2644 snapshot_fd,
2645 apk_fds,
2646 dex_locations,
2647 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002648 pid_t pid = fork();
2649 if (pid == 0) {
2650 /* child -- drop privileges before continuing */
2651 drop_capabilities(AID_SYSTEM);
2652
Calin Juravle59f7ab82018-04-27 17:50:23 -07002653 // The introduction of new access flags into boot jars causes them to
2654 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002655 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002656 }
2657
2658 /* parent */
2659 int return_code = wait_child(pid);
2660 if (!WIFEXITED(return_code)) {
2661 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2662 return false;
2663 }
2664 return true;
2665 }
2666 return true;
2667}
2668
2669bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2670 const std::string& profile_name, const std::string& classpath) {
2671 if (app_id == -1) {
2672 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2673 } else {
2674 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2675 }
2676}
2677
Calin Juravlec3b049e2018-01-18 22:32:58 -08002678bool prepare_app_profile(const std::string& package_name,
2679 userid_t user_id,
2680 appid_t app_id,
2681 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002682 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002683 const std::unique_ptr<std::string>& dex_metadata) {
2684 // Prepare the current profile.
2685 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2686 /*is_secondary_dex*/ false);
2687 uid_t uid = multiuser_get_uid(user_id, app_id);
2688 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2689 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2690 return false;
2691 }
2692
2693 // Check if we need to install the profile from the dex metadata.
2694 if (dex_metadata == nullptr) {
2695 return true;
2696 }
2697
2698 // We have a dex metdata. Merge the profile into the reference profile.
2699 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2700 /*read_write*/ true, /*is_secondary_dex*/ false);
2701 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2702 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002703 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2704 if (apk_fd < 0) {
2705 PLOG(ERROR) << "Could not open code path " << code_path;
2706 return false;
2707 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002708
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002709 RunProfman args;
2710 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2711 std::move(ref_profile_fd),
2712 std::move(apk_fd),
2713 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002714 pid_t pid = fork();
2715 if (pid == 0) {
2716 /* child -- drop privileges before continuing */
2717 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2718 drop_capabilities(app_shared_gid);
2719
Calin Juravlef63d4792018-01-30 17:43:34 +00002720 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002721 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002722 }
2723
2724 /* parent */
2725 int return_code = wait_child(pid);
2726 if (!WIFEXITED(return_code)) {
2727 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2728 return false;
2729 }
2730 return true;
2731}
2732
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002733} // namespace installd
2734} // namespace android