blob: 07f8ff0a151f7b757ec3dbee27f6e6c0ee4f8d10 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000048#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080052#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060053#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070054#include "installd_deps.h"
55#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070056#include "utils.h"
57
Jeff Sharkey90aff262016-12-12 14:28:24 -070058using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070059using android::base::GetBoolProperty;
60using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000061using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010062using android::base::ReadFully;
63using android::base::StringPrintf;
64using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080065using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066
67namespace android {
68namespace installd {
69
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070070// Should minidebug info be included in compiled artifacts? Even if this value is
71// "true," usage might still be conditional to other constraints, e.g., system
72// property overrides.
73static constexpr bool kEnableMinidebugInfo = true;
74
75static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
76static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
77static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080078static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070079
Andreas Gampefa2dadd2018-02-28 19:52:47 -080080
Calin Juravle114f0812017-03-08 19:05:07 -080081// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
82struct FreeDelete {
83 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
84 void operator()(const void* ptr) const {
85 free(const_cast<void*>(ptr));
86 }
87};
88
89// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
90template <typename T>
91using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
92
Calin Juravle1a0af3b2017-03-09 14:33:33 -080093static unique_fd invalid_unique_fd() {
94 return unique_fd(-1);
95}
96
Andreas Gampe6a9cf722017-07-24 16:49:10 -070097static bool is_debug_runtime() {
98 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
99}
100
David Sehra3b5ab62017-10-25 14:27:29 -0700101static bool is_debuggable_build() {
102 return android::base::GetBoolProperty("ro.debuggable", false);
103}
104
Jeff Sharkey90aff262016-12-12 14:28:24 -0700105static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800106 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700107 if (ufd.get() < 0) {
108 if (errno != ENOENT) {
109 PLOG(WARNING) << "Could not open profile " << profile;
110 return false;
111 } else {
112 // Nothing to clear. That's ok.
113 return true;
114 }
115 }
116
117 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
118 if (errno != EWOULDBLOCK) {
119 PLOG(WARNING) << "Error locking profile " << profile;
120 }
121 // This implies that the app owning this profile is running
122 // (and has acquired the lock).
123 //
124 // If we can't acquire the lock bail out since clearing is useless anyway
125 // (the app will write again to the profile).
126 //
127 // Note:
128 // This does not impact the this is not an issue for the profiling correctness.
129 // In case this is needed because of an app upgrade, profiles will still be
130 // eventually cleared by the app itself due to checksum mismatch.
131 // If this is needed because profman advised, then keeping the data around
132 // until the next run is again not an issue.
133 //
134 // If the app attempts to acquire a lock while we've held one here,
135 // it will simply skip the current write cycle.
136 return false;
137 }
138
139 bool truncated = ftruncate(ufd.get(), 0) == 0;
140 if (!truncated) {
141 PLOG(WARNING) << "Could not truncate " << profile;
142 }
143 if (flock(ufd.get(), LOCK_UN) != 0) {
144 PLOG(WARNING) << "Error unlocking profile " << profile;
145 }
146 return truncated;
147}
148
Calin Juravle114f0812017-03-08 19:05:07 -0800149// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800150// The location is the profile name for primary apks or the dex path for secondary dex files.
151static bool clear_reference_profile(const std::string& package_name, const std::string& location,
152 bool is_secondary_dex) {
153 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154}
155
Calin Juravle114f0812017-03-08 19:05:07 -0800156// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800157// The location is the profile name for primary apks or the dex path for secondary dex files.
158static bool clear_current_profile(const std::string& package_name, const std::string& location,
159 userid_t user, bool is_secondary_dex) {
160 return clear_profile(create_current_profile_path(user, package_name, location,
161 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700162}
163
Calin Juravle114f0812017-03-08 19:05:07 -0800164// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800165// The location is the profile name for primary apks or the dex path for secondary dex files.
166bool clear_primary_reference_profile(const std::string& package_name,
167 const std::string& location) {
168 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800169}
170
171// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800172// The location is the profile name for primary apks or the dex path for secondary dex files.
173bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800175 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700176 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
177 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800178 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700179 }
180 return success;
181}
182
Calin Juravle114f0812017-03-08 19:05:07 -0800183// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800184bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
185 userid_t user) {
186 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800187}
188
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700189static std::vector<std::string> SplitBySpaces(const std::string& str) {
190 if (str.empty()) {
191 return {};
192 }
193 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700194}
195
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700196static const char* get_location_from_path(const char* path) {
197 static constexpr char kLocationSeparator = '/';
198 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700199 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700200 return path;
201 } else {
202 // Skip the separator character.
203 return location + 1;
204 }
205}
206
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800207// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
208// need to be performed between the fork and exec.
209class ExecVHelper {
210 public:
211 // Store a placeholder for the binary name.
212 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800213
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800214 void PrepareArgs(const std::string& bin) {
215 CHECK(!args_.empty());
216 CHECK(args_[0].empty());
217 args_[0] = bin;
218 // Write char* into array.
219 for (const std::string& arg : args_) {
220 argv_.push_back(arg.c_str());
221 }
222 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800223 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800224
225 [[ noreturn ]]
226 void Exec(int exit_code) {
227 execv(argv_[0], (char * const *)&argv_[0]);
228 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
229 exit(exit_code);
230 }
231
232 // Add an arg if it's not empty.
233 void AddArg(const std::string& arg) {
234 if (!arg.empty()) {
235 args_.push_back(arg);
236 }
237 }
238
239 // Add a runtime arg if it's not empty.
240 void AddRuntimeArg(const std::string& arg) {
241 if (!arg.empty()) {
242 args_.push_back("--runtime-arg");
243 args_.push_back(arg);
244 }
245 }
246
247 protected:
248 // Holder arrays for backing arg storage.
249 std::vector<std::string> args_;
250
251 // Argument poiners.
252 std::vector<const char*> argv_;
253};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700254
255static std::string MapPropertyToArg(const std::string& property,
256 const std::string& format,
257 const std::string& default_value = "") {
258 std::string prop = GetProperty(property, default_value);
259 if (!prop.empty()) {
260 return StringPrintf(format.c_str(), prop.c_str());
261 }
262 return "";
263}
264
Patrick Baumann00d3f4f2020-04-14 17:03:00 -0700265static std::string MapPropertyToArgWithBackup(const std::string& property,
266 const std::string& backupProperty,
267 const std::string& format,
268 const std::string& default_value = "") {
269 std::string value = GetProperty(property, default_value);
270 if (!value.empty()) {
271 return StringPrintf(format.c_str(), value.c_str());
272 }
273 return MapPropertyToArg(backupProperty, format, default_value);
274}
275
Calin Juravlef74a7372019-02-28 20:29:41 -0800276// Determines which binary we should use for execution (the debug or non-debug version).
277// e.g. dex2oatd vs dex2oat
278static const char* select_execution_binary(const char* binary, const char* debug_binary,
279 bool background_job_compile) {
280 return select_execution_binary(
281 binary,
282 debug_binary,
283 background_job_compile,
284 is_debug_runtime(),
285 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
286 is_debuggable_build());
287}
288
289// Determines which binary we should use for execution (the debug or non-debug version).
290// e.g. dex2oatd vs dex2oat
291// This is convenient method which is much easier to test because it doesn't read
292// system properties.
293const char* select_execution_binary(
294 const char* binary,
295 const char* debug_binary,
296 bool background_job_compile,
297 bool is_debug_runtime,
298 bool is_release,
299 bool is_debuggable_build) {
300 // Do not use debug binaries for release candidates (to give more soak time).
301 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
302
303 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
304 // the file is present (it may not be on images with very little space available).
305 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
306
307 return useDebug ? debug_binary : binary;
308}
309
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000310// Namespace for Android Runtime flags applied during boot time.
311static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
312// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000313static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
314// Location of the JIT Zygote image.
315static const char* kJitZygoteImage =
316 "boot.art:/nonx/boot-framework.art!/system/etc/boot-image.prof";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000317
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700318// Phenotype property name for enabling profiling the boot class path.
319static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
320
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800321class RunDex2Oat : public ExecVHelper {
322 public:
323 RunDex2Oat(int zip_fd,
324 int oat_fd,
325 int input_vdex_fd,
326 int output_vdex_fd,
327 int image_fd,
328 const char* input_file_name,
329 const char* output_file_name,
330 int swap_fd,
331 const char* instruction_set,
332 const char* compiler_filter,
333 bool debuggable,
334 bool post_bootcomplete,
Patrick Baumann00d3f4f2020-04-14 17:03:00 -0700335 bool for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800336 bool background_job_compile,
337 int profile_fd,
338 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000339 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800340 int target_sdk_version,
341 bool enable_hidden_api_checks,
342 bool generate_compact_dex,
343 int dex_metadata_fd,
344 const char* compilation_reason) {
345 // Get the relative path to the input file.
346 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700347
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800348 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
349 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700350
Patrick Baumann00d3f4f2020-04-14 17:03:00 -0700351 std::string threads_format = "-j%s";
352 std::string dex2oat_threads_arg = post_bootcomplete
353 ? (for_restore
354 ? MapPropertyToArgWithBackup(
355 "dalvik.vm.restore-dex2oat-threads",
356 "dalvik.vm.dex2oat-threads",
357 threads_format)
358 : MapPropertyToArg("dalvik.vm.dex2oat-threads", threads_format))
359 : MapPropertyToArg("dalvik.vm.boot-dex2oat-threads", threads_format);
360 std::string cpu_set_format = "--cpu-set=%s";
361 std::string dex2oat_cpu_set_arg = post_bootcomplete
362 ? (for_restore
363 ? MapPropertyToArgWithBackup(
364 "dalvik.vm.restore-dex2oat-cpu-set",
365 "dalvik.vm.dex2oat-cpu-set",
366 cpu_set_format)
367 : MapPropertyToArg("dalvik.vm.dex2oat-cpu-set", cpu_set_format))
368 : MapPropertyToArg("dalvik.vm.boot-dex2oat-cpu-set", cpu_set_format);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700369
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000370 std::string bootclasspath;
371 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
372 if (dex2oat_bootclasspath != nullptr) {
373 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
374 }
375 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
376 // BOOTCLASSPATH.
377
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800378 const std::string dex2oat_isa_features_key =
379 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
380 std::string instruction_set_features_arg =
381 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700382
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800383 const std::string dex2oat_isa_variant_key =
384 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
385 std::string instruction_set_variant_arg =
386 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700389
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800390 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
391 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
392 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700393
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800394 // If we are booting without the real /data, don't spend time compiling.
395 std::string vold_decrypt = GetProperty("vold.decrypt", "");
396 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
397 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700398
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800399 std::string resolve_startup_string_arg =
400 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
401 "--resolve-startup-const-strings=%s");
402 if (resolve_startup_string_arg.empty()) {
403 // If empty, fall back to system property.
404 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800405 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
406 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800407 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800408
409 const std::string image_block_size_arg =
410 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
411 "--max-image-block-size=%s");
412
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800413 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700414
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800415 std::string image_format_arg;
416 if (image_fd >= 0) {
417 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000418 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000419
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800420 std::string dex2oat_large_app_threshold_arg =
421 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000422
Calin Juravlef74a7372019-02-28 20:29:41 -0800423
424 const char* dex2oat_bin = select_execution_binary(
425 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000426
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800427 bool generate_minidebug_info = kEnableMinidebugInfo &&
428 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000429
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000430 std::string boot_image;
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000431 std::string use_jitzygote_image =
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000432 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000433 ENABLE_JITZYGOTE_IMAGE,
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000434 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700435
436 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
437 profile_boot_class_path =
438 server_configurable_flags::GetServerConfigurableFlag(
439 RUNTIME_NATIVE_BOOT_NAMESPACE,
440 PROFILE_BOOT_CLASS_PATH,
441 /*default_value=*/ profile_boot_class_path);
442
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000443 if (use_jitzygote_image == "true" || profile_boot_class_path == "true") {
444 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000445 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000446 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000447 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000448
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800449 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
450 // use arraysize instead.
451 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
452 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
453 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
454 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
455 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
456 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
457 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
458 std::string dex2oat_compiler_filter_arg;
459 std::string dex2oat_swap_fd;
460 std::string dex2oat_image_fd;
461 std::string target_sdk_version_arg;
462 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000463 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800464 }
465 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000466 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800467 if (class_loader_context != nullptr) {
468 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
469 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000470 if (!class_loader_context_fds.empty()) {
471 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
472 class_loader_context_fds.c_str());
473 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800474 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000475
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800476 if (swap_fd >= 0) {
477 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
478 }
479 if (image_fd >= 0) {
480 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
481 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000482
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800483 // Compute compiler filter.
484 bool have_dex2oat_relocation_skip_flag = false;
485 if (skip_compilation) {
486 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
487 have_dex2oat_relocation_skip_flag = true;
488 } else if (compiler_filter != nullptr) {
489 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
490 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000491
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800492 if (dex2oat_compiler_filter_arg.empty()) {
493 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
494 "--compiler-filter=%s");
495 }
496
497 // Check whether all apps should be compiled debuggable.
498 if (!debuggable) {
499 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
500 }
501 std::string profile_arg;
502 if (profile_fd != -1) {
503 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
504 }
505
506 // Get the directory of the apk to pass as a base classpath directory.
507 std::string base_dir;
508 std::string apk_dir(input_file_name);
509 unsigned long dir_index = apk_dir.rfind('/');
510 bool has_base_dir = dir_index != std::string::npos;
511 if (has_base_dir) {
512 apk_dir = apk_dir.substr(0, dir_index);
513 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
514 }
515
516 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
517
518 std::string compilation_reason_arg = compilation_reason == nullptr
519 ? ""
520 : std::string("--compilation-reason=") + compilation_reason;
521
522 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
523
524 // Disable cdex if update input vdex is true since this combination of options is not
525 // supported.
526 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
527
528 AddArg(zip_fd_arg);
529 AddArg(zip_location_arg);
530 AddArg(input_vdex_fd_arg);
531 AddArg(output_vdex_fd_arg);
532 AddArg(oat_fd_arg);
533 AddArg(oat_location_arg);
534 AddArg(instruction_set_arg);
535
536 AddArg(instruction_set_variant_arg);
537 AddArg(instruction_set_features_arg);
538
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000539 AddArg(boot_image);
540
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000541 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800542 AddRuntimeArg(dex2oat_Xms_arg);
543 AddRuntimeArg(dex2oat_Xmx_arg);
544
545 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800546 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800547 AddArg(dex2oat_compiler_filter_arg);
548 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000549 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800550 AddArg(dex2oat_swap_fd);
551 AddArg(dex2oat_image_fd);
552
553 if (generate_debug_info) {
554 AddArg("--generate-debug-info");
555 }
556 if (debuggable) {
557 AddArg("--debuggable");
558 }
559 AddArg(image_format_arg);
560 AddArg(dex2oat_large_app_threshold_arg);
561
562 if (have_dex2oat_relocation_skip_flag) {
563 AddRuntimeArg(dex2oat_norelocation);
564 }
565 AddArg(profile_arg);
566 AddArg(base_dir);
567 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000568 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800569 if (generate_minidebug_info) {
570 AddArg(kMinidebugDex2oatFlag);
571 }
572 if (disable_cdex) {
573 AddArg(kDisableCompactDexFlag);
574 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000575 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800576 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100577 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800578 }
579
580 if (dex_metadata_fd > -1) {
581 AddArg(dex_metadata_fd_arg);
582 }
583
584 AddArg(compilation_reason_arg);
585
586 // Do not add args after dex2oat_flags, they should override others for debugging.
587 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
588
589 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000590 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800591};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700592
593/*
594 * Whether dexopt should use a swap file when compiling an APK.
595 *
596 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
597 * itself, anyways).
598 *
599 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
600 *
601 * Otherwise, return true if this is a low-mem device.
602 *
603 * Otherwise, return default value.
604 */
605static bool kAlwaysProvideSwapFile = false;
606static bool kDefaultProvideSwapFile = true;
607
608static bool ShouldUseSwapFileForDexopt() {
609 if (kAlwaysProvideSwapFile) {
610 return true;
611 }
612
613 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700614 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
615 if (!dex2oat_prop_buf.empty()) {
616 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 }
618
619 // Shortcut for default value. This is an implementation optimization for the process sketched
620 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
621 // as low-mem is never returning false. The compiler will optimize this away if it can.
622 if (kDefaultProvideSwapFile) {
623 return true;
624 }
625
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700626 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700627 return true;
628 }
629
630 // Default value must be false here.
631 return kDefaultProvideSwapFile;
632}
633
Richard Uhler76cc0272016-12-08 10:46:35 +0000634static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700635 if (set_to_bg) {
636 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800637 PLOG(ERROR) << "set_sched_policy failed";
638 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700639 }
640 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800641 PLOG(ERROR) << "setpriority failed";
642 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700643 }
644 }
645}
646
Calin Juravle29591732017-11-20 17:46:19 -0800647static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
648 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800649 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800650 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800651 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800652 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800653 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700654 }
Calin Juravle114f0812017-03-08 19:05:07 -0800655 // Profiles should belong to the app; make sure of that by giving ownership to
656 // the app uid. If we cannot do that, there's no point in returning the fd
657 // since dex2oat/profman will fail with SElinux denials.
658 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000659 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800660 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800661 }
Calin Juravle29591732017-11-20 17:46:19 -0800662 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800663}
664
Calin Juravle29591732017-11-20 17:46:19 -0800665static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800666 // Do not follow symlinks when opening a profile:
667 // - primary profiles should not contain symlinks in their paths
668 // - secondary dex paths should have been already resolved and validated
669 flags |= O_NOFOLLOW;
670
Calin Juravle29591732017-11-20 17:46:19 -0800671 // Check if we need to create the profile
672 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
673 unique_fd fd;
674 if ((flags & O_CREAT) != 0) {
675 fd = create_profile(uid, profile, flags);
676 } else {
677 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
678 }
679
Calin Juravle114f0812017-03-08 19:05:07 -0800680 if (fd.get() < 0) {
681 if (errno != ENOENT) {
682 // Profiles might be missing for various reasons. For example, in a
683 // multi-user environment, the profile directory for one user can be created
684 // after we start a merge. In this case the current profile for that user
685 // will not be found.
686 // Also, the secondary dex profiles might be deleted by the app at any time,
687 // so we can't we need to prepare if they are missing.
688 PLOG(ERROR) << "Failed to open profile " << profile;
689 }
690 return invalid_unique_fd();
691 }
692
Jeff Sharkey90aff262016-12-12 14:28:24 -0700693 return fd;
694}
695
Calin Juravle824a64d2018-01-18 20:23:17 -0800696static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
697 const std::string& location, bool is_secondary_dex) {
698 std::string profile = create_current_profile_path(user, package_name, location,
699 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800700 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800701}
702
Calin Juravle824a64d2018-01-18 20:23:17 -0800703static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
704 const std::string& location, bool read_write, bool is_secondary_dex) {
705 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800706 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
707}
708
709static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800710 const std::string& location) {
711 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800712 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800713}
714
Calin Juravle824a64d2018-01-18 20:23:17 -0800715static void open_profile_files(uid_t uid, const std::string& package_name,
716 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800717 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700718 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800719 *reference_profile_fd = open_reference_profile(uid, package_name, location,
720 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700721
Calin Juravle114f0812017-03-08 19:05:07 -0800722 // For secondary dex files, we don't really need the user but we use it for sanity checks.
723 // Note: the user owning the dex file should be the current user.
724 std::vector<userid_t> users;
725 if (is_secondary_dex){
726 users.push_back(multiuser_get_user_id(uid));
727 } else {
728 users = get_known_users(/*volume_uuid*/ nullptr);
729 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700730 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800731 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
732 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700733 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800734 if (profile_fd.get() >= 0) {
735 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700736 }
737 }
738}
739
Calin Juravle76561322019-11-14 09:08:52 -0800740static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
741static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
742static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
743static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
744static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
745static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
746static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800748class RunProfman : public ExecVHelper {
749 public:
750 void SetupArgs(const std::vector<unique_fd>& profile_fds,
751 const unique_fd& reference_profile_fd,
752 const std::vector<unique_fd>& apk_fds,
753 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800754 bool copy_and_update,
755 bool for_snapshot,
756 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800757
758 // TODO(calin): Assume for now we run in the bg compile job (which is in
759 // most of the invocation). With the current data flow, is not very easy or
760 // clean to discover this in RunProfman (it will require quite a messy refactoring).
761 const char* profman_bin = select_execution_binary(
762 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800764 if (copy_and_update) {
765 CHECK_EQ(1u, profile_fds.size());
766 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000767 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800768 if (reference_profile_fd != -1) {
769 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000770 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800771
772 for (const unique_fd& fd : profile_fds) {
773 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
774 }
775
776 for (const unique_fd& fd : apk_fds) {
777 AddArg("--apk-fd=" + std::to_string(fd.get()));
778 }
779
780 for (const std::string& dex_location : dex_locations) {
781 AddArg("--dex-location=" + dex_location);
782 }
783
784 if (copy_and_update) {
785 AddArg("--copy-and-update-profile-key");
786 }
787
Calin Juravle78728f32019-11-08 17:55:46 -0800788 if (for_snapshot) {
789 AddArg("--force-merge");
790 }
791
792 if (for_boot_image) {
793 AddArg("--boot-image-merge");
794 }
795
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800796 // Do not add after dex2oat_flags, they should override others for debugging.
797 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800798 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700799
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800800 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
801 const unique_fd& reference_profile_fd,
802 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800803 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
804 bool for_snapshot = false,
805 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800806 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800807 reference_profile_fd,
808 apk_fds,
809 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800810 /*copy_and_update=*/ false,
811 for_snapshot,
812 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800813 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800815 void SetupCopyAndUpdate(unique_fd&& profile_fd,
816 unique_fd&& reference_profile_fd,
817 unique_fd&& apk_fd,
818 const std::string& dex_location) {
819 // The fds need to stay open longer than the scope of the function, so put them into a local
820 // variable vector.
821 profiles_fd_.push_back(std::move(profile_fd));
822 apk_fds_.push_back(std::move(apk_fd));
823 reference_profile_fd_ = std::move(reference_profile_fd);
824 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800825 SetupArgs(profiles_fd_,
826 reference_profile_fd_,
827 apk_fds_,
828 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800829 /*copy_and_update=*/true,
830 /*for_snapshot*/false,
831 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800832 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000833
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800834 void SetupDump(const std::vector<unique_fd>& profiles_fd,
835 const unique_fd& reference_profile_fd,
836 const std::vector<std::string>& dex_locations,
837 const std::vector<unique_fd>& apk_fds,
838 const unique_fd& output_fd) {
839 AddArg("--dump-only");
840 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800841 SetupArgs(profiles_fd,
842 reference_profile_fd,
843 apk_fds,
844 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800845 /*copy_and_update=*/false,
846 /*for_snapshot*/false,
847 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800848 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000849
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800850 void Exec() {
851 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
852 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000853
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800854 private:
855 unique_fd reference_profile_fd_;
856 std::vector<unique_fd> profiles_fd_;
857 std::vector<unique_fd> apk_fds_;
858};
Mathieu Chartier31636522018-11-09 23:53:07 +0000859
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800860
Calin Juravlef63d4792018-01-30 17:43:34 +0000861
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800863// The location is the package name for primary apks or the dex path for secondary dex files.
864// Returns true if there is enough information in the current profiles that makes it
865// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700866// If the return value is true all the current profiles would have been merged into
867// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800868static bool analyze_profiles(uid_t uid, const std::string& package_name,
869 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800870 std::vector<unique_fd> profiles_fd;
871 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800872 open_profile_files(uid, package_name, location, is_secondary_dex,
873 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800874 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700875 // Skip profile guided compilation because no profiles were found.
876 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877 return false;
878 }
879
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800880 RunProfman profman_merge;
881 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 pid_t pid = fork();
883 if (pid == 0) {
884 /* child -- drop privileges before continuing */
885 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800886 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700887 }
888 /* parent */
889 int return_code = wait_child(pid);
890 bool need_to_compile = false;
891 bool should_clear_current_profiles = false;
892 bool should_clear_reference_profile = false;
893 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800894 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700895 } else {
896 return_code = WEXITSTATUS(return_code);
897 switch (return_code) {
898 case PROFMAN_BIN_RETURN_CODE_COMPILE:
899 need_to_compile = true;
900 should_clear_current_profiles = true;
901 should_clear_reference_profile = false;
902 break;
903 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
904 need_to_compile = false;
905 should_clear_current_profiles = false;
906 should_clear_reference_profile = false;
907 break;
908 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800909 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910 need_to_compile = false;
911 should_clear_current_profiles = true;
912 should_clear_reference_profile = true;
913 break;
914 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
915 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
916 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800917 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700918 need_to_compile = false;
919 should_clear_current_profiles = false;
920 should_clear_reference_profile = false;
921 break;
Calin Juravle76561322019-11-14 09:08:52 -0800922 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
923 need_to_compile = false;
924 should_clear_current_profiles = true;
925 should_clear_reference_profile = true;
926 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700927 default:
928 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800929 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800930 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700931 need_to_compile = false;
932 should_clear_current_profiles = true;
933 should_clear_reference_profile = true;
934 break;
935 }
936 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800937
Jeff Sharkey90aff262016-12-12 14:28:24 -0700938 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800939 if (is_secondary_dex) {
940 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800941 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
942 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800943 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800944 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800945 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700946 }
947 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800948 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700949 }
950 return need_to_compile;
951}
952
Calin Juravle114f0812017-03-08 19:05:07 -0800953// Decides if profile guided compilation is needed or not based on existing profiles.
954// The analysis is done for the primary apks of the given package.
955// Returns true if there is enough information in the current profiles that makes it
956// worth to recompile the package.
957// If the return value is true all the current profiles would have been merged into
958// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800959bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
960 const std::string& profile_name) {
961 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800962}
963
Calin Juravle408cd4a2018-01-20 23:34:18 -0800964bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
965 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800966 std::vector<unique_fd> profile_fds;
967 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800968 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
969 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700970
Calin Juravle408cd4a2018-01-20 23:34:18 -0800971 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800972 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800974 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700975 const bool has_profiles = !profile_fds.empty();
976
977 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800978 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700979 return false;
980 }
981
Calin Juravle114f0812017-03-08 19:05:07 -0800982 unique_fd output_fd(open(out_file_name.c_str(),
983 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700984 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800985 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700986 return false;
987 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800988
Jeff Sharkey90aff262016-12-12 14:28:24 -0700989 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800990 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800991 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
992 if (apk_fd == -1) {
993 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
994 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700995 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800996 dex_locations.push_back(get_location_from_path(code_path.c_str()));
997 apk_fds.push_back(std::move(apk_fd));
998
Jeff Sharkey90aff262016-12-12 14:28:24 -0700999
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001000 RunProfman profman_dump;
1001 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 pid_t pid = fork();
1003 if (pid == 0) {
1004 /* child -- drop privileges before continuing */
1005 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001006 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 }
1008 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 int return_code = wait_child(pid);
1010 if (!WIFEXITED(return_code)) {
1011 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1012 << return_code;
1013 return false;
1014 }
1015 return true;
1016}
1017
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001018bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001019 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001020 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1021 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001022 package_name,
1023 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001024 /*read_write*/ true,
1025 /*secondary*/ false));
1026 if (in_fd.get() < 0) {
1027 PLOG(WARNING) << "Could not open profile " << system_profile;
1028 return false;
1029 }
1030 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001031 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001032 return false;
1033 }
1034
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001035 // As a security measure we want to write the profile information with the reduced capabilities
1036 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001037 pid_t pid = fork();
1038 if (pid == 0) {
1039 /* child -- drop privileges before continuing */
1040 drop_capabilities(packageUid);
1041
1042 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1043 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001044 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001045 }
1046 // This implies that the app owning this profile is running
1047 // (and has acquired the lock).
1048 //
1049 // The app never acquires the lock for the reference profiles of primary apks.
1050 // Only dex2oat from installd will do that. Since installd is single threaded
1051 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001052 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001053 return false;
1054 }
1055
1056 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1057 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001058 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001059 }
1060
1061 // Copy over data.
1062 static constexpr size_t kBufferSize = 4 * 1024;
1063 char buffer[kBufferSize];
1064 while (true) {
1065 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1066 if (bytes == 0) {
1067 break;
1068 }
1069 write(out_fd.get(), buffer, bytes);
1070 }
1071 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001072 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001073 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001074 // Use _exit since we don't want to run the global destructors in the child.
1075 // b/62597429
1076 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001077 }
1078 /* parent */
1079 int return_code = wait_child(pid);
1080 return return_code == 0;
1081}
1082
Jeff Sharkey90aff262016-12-12 14:28:24 -07001083static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1084 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1085 if (EndsWith(oat_path, ".dex")) {
1086 std::string new_path = oat_path;
1087 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001088 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 return new_path;
1090 }
1091
1092 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1093 // case (where the base name will have an extension for the B artifact).
1094 size_t odex_pos = oat_path.rfind(".odex");
1095 if (odex_pos != std::string::npos) {
1096 std::string new_path = oat_path;
1097 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1098 CHECK_NE(new_path.find(new_ext), std::string::npos);
1099 return new_path;
1100 }
1101
1102 // Don't know how to handle this.
1103 return "";
1104}
1105
1106// Translate the given oat path to an art (app image) path. An empty string
1107// denotes an error.
1108static std::string create_image_filename(const std::string& oat_path) {
1109 return replace_file_extension(oat_path, ".art");
1110}
1111
1112// Translate the given oat path to a vdex path. An empty string denotes an error.
1113static std::string create_vdex_filename(const std::string& oat_path) {
1114 return replace_file_extension(oat_path, ".vdex");
1115}
1116
Jeff Sharkey90aff262016-12-12 14:28:24 -07001117static int open_output_file(const char* file_name, bool recreate, int permissions) {
1118 int flags = O_RDWR | O_CREAT;
1119 if (recreate) {
1120 if (unlink(file_name) < 0) {
1121 if (errno != ENOENT) {
1122 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1123 }
1124 }
1125 flags |= O_EXCL;
1126 }
1127 return open(file_name, flags, permissions);
1128}
1129
Calin Juravle2289c0a2017-02-15 12:44:14 -08001130static bool set_permissions_and_ownership(
1131 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1132 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1133 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001134 if (fchmod(fd,
1135 S_IRUSR|S_IWUSR|S_IRGRP |
1136 (is_public ? S_IROTH : 0)) < 0) {
1137 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1138 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001139 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001140 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1141 return false;
1142 }
1143 return true;
1144}
1145
1146static bool IsOutputDalvikCache(const char* oat_dir) {
1147 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1148 // into '!'. Play it safe by handling it both.
1149 // TODO: ensure we never get null.
1150 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1151 return oat_dir == nullptr || oat_dir[0] == '!';
1152}
1153
Calin Juravled23dee72017-07-06 16:29:11 -07001154// Best-effort check whether we can fit the the path into our buffers.
1155// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1156// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1157// extension to the cache path (5 bytes).
1158// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1159static bool validate_dex_path_size(const std::string& dex_path) {
1160 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1161 LOG(ERROR) << "dex_path too long: " << dex_path;
1162 return false;
1163 }
1164 return true;
1165}
1166
Jeff Sharkey90aff262016-12-12 14:28:24 -07001167static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001168 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001169 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001170 return false;
1171 }
1172
1173 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001174 // Oat dirs for secondary dex files are already validated.
1175 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001176 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1177 return false;
1178 }
1179 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1180 return false;
1181 }
1182 } else {
1183 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1184 return false;
1185 }
1186 }
1187 return true;
1188}
1189
1190// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1191// on destruction. It will also run the given cleanup (unless told not to) after closing.
1192//
1193// Usage example:
1194//
Calin Juravle7a570e82017-01-14 16:23:30 -08001195// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001196// [name]() {
1197// unlink(name.c_str());
1198// });
1199// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1200// wrapper if captured as a reference.
1201//
1202// if (file.get() == -1) {
1203// // Error opening...
1204// }
1205//
1206// ...
1207// if (error) {
1208// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1209// // and delete the file (after the fd is closed).
1210// return -1;
1211// }
1212//
1213// (Success case)
1214// file.SetCleanup(false);
1215// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1216// // (leaving the file around; after the fd is closed).
1217//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001218class Dex2oatFileWrapper {
1219 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001220 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001221 }
1222
Calin Juravle7a570e82017-01-14 16:23:30 -08001223 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1224 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1225
1226 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1227 value_ = other.value_;
1228 cleanup_ = other.cleanup_;
1229 do_cleanup_ = other.do_cleanup_;
1230 auto_close_ = other.auto_close_;
1231 other.release();
1232 }
1233
1234 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1235 value_ = other.value_;
1236 cleanup_ = other.cleanup_;
1237 do_cleanup_ = other.do_cleanup_;
1238 auto_close_ = other.auto_close_;
1239 other.release();
1240 return *this;
1241 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001242
1243 ~Dex2oatFileWrapper() {
1244 reset(-1);
1245 }
1246
1247 int get() {
1248 return value_;
1249 }
1250
1251 void SetCleanup(bool cleanup) {
1252 do_cleanup_ = cleanup;
1253 }
1254
1255 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001256 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001257 close(value_);
1258 }
1259 if (do_cleanup_ && cleanup_ != nullptr) {
1260 cleanup_();
1261 }
1262
1263 value_ = new_value;
1264 }
1265
Calin Juravle7a570e82017-01-14 16:23:30 -08001266 void reset(int new_value, std::function<void ()> new_cleanup) {
1267 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001268 close(value_);
1269 }
1270 if (do_cleanup_ && cleanup_ != nullptr) {
1271 cleanup_();
1272 }
1273
1274 value_ = new_value;
1275 cleanup_ = new_cleanup;
1276 }
1277
Calin Juravle7a570e82017-01-14 16:23:30 -08001278 void DisableAutoClose() {
1279 auto_close_ = false;
1280 }
1281
Jeff Sharkey90aff262016-12-12 14:28:24 -07001282 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001283 void release() {
1284 value_ = -1;
1285 do_cleanup_ = false;
1286 cleanup_ = nullptr;
1287 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001288 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001289 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001290 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292};
1293
Calin Juravle7a570e82017-01-14 16:23:30 -08001294// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001295Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1296 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001297
Calin Juravle7a570e82017-01-14 16:23:30 -08001298 const std::string image_path = create_image_filename(out_oat_path);
1299 if (image_path.empty()) {
1300 // Happens when the out_oat_path has an unknown extension.
1301 return Dex2oatFileWrapper();
1302 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001303
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001304 // In case there is a stale image, remove it now. Ignore any error.
1305 unlink(image_path.c_str());
1306
1307 // Not enabled, exit.
1308 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001309 return Dex2oatFileWrapper();
1310 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001311 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1312 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001313 return Dex2oatFileWrapper();
1314 }
1315 // Recreate is true since we do not want to modify a mapped image. If the app is
1316 // already running and we modify the image file, it can cause crashes (b/27493510).
1317 Dex2oatFileWrapper wrapper_fd(
1318 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1319 [image_path]() { unlink(image_path.c_str()); });
1320 if (wrapper_fd.get() < 0) {
1321 // Could not create application image file. Go on since we can compile without it.
1322 LOG(ERROR) << "installd could not create '" << image_path
1323 << "' for image file during dexopt";
1324 // If we have a valid image file path but no image fd, explicitly erase the image file.
1325 if (unlink(image_path.c_str()) < 0) {
1326 if (errno != ENOENT) {
1327 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1328 }
1329 }
1330 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001331 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001332 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1333 wrapper_fd.reset(-1);
1334 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001335
Calin Juravle7a570e82017-01-14 16:23:30 -08001336 return wrapper_fd;
1337}
1338
1339// Creates the dexopt swap file if necessary and return its fd.
1340// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001341unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001342 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001343 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001344 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001345 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001346 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001347 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001348 if (swap_fd.get() < 0) {
1349 // Could not create swap file. Optimistically go on and hope that we can compile
1350 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001351 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001352 } else {
1353 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001354 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001355 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1356 }
1357 }
1358 return swap_fd;
1359}
1360
1361// Opens the reference profiles if needed.
1362// 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 -08001363Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001364 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001365 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001366 // If we are not profile guided compilation, or we are compiling system server
1367 // do not bother to open the profiles; we won't be using them.
1368 if (!profile_guided || (pkgname[0] == '*')) {
1369 return Dex2oatFileWrapper();
1370 }
1371
1372 // If this is a secondary dex path which is public do not open the profile.
1373 // We cannot compile public secondary dex paths with profiles. That's because
1374 // it will expose how the dex files are used by their owner.
1375 //
1376 // Note that the PackageManager is responsible to set the is_public flag for
1377 // primary apks and we do not check it here. In some cases, e.g. when
1378 // compiling with a public profile from the .dm file the PackageManager will
1379 // set is_public toghether with the profile guided compilation.
1380 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001381 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001382 }
Calin Juravle114f0812017-03-08 19:05:07 -08001383
1384 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001385 std::string location;
1386 if (is_secondary_dex) {
1387 location = dex_path;
1388 } else {
1389 if (profile_name == nullptr) {
1390 // This path is taken for system server re-compilation lunched from ZygoteInit.
1391 return Dex2oatFileWrapper();
1392 } else {
1393 location = profile_name;
1394 }
1395 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001396 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1397 is_secondary_dex);
1398 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1399 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001400 };
1401 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001402}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001403
Calin Juravle7a570e82017-01-14 16:23:30 -08001404// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1405// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001406bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001407 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001408 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001409 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1410 CHECK(in_vdex_wrapper_fd != nullptr);
1411 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001412 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1413 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001414 char in_odex_path[PKG_PATH_MAX];
1415 int dexopt_action = abs(dexopt_needed);
1416 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001417 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001418
1419 // Infer the name of the output VDEX.
1420 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1421 if (out_vdex_path_str.empty()) {
1422 return false;
1423 }
1424
1425 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001426 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001427 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1428 const char* path = nullptr;
1429 if (is_odex_location) {
1430 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1431 path = in_odex_path;
1432 } else {
1433 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001434 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001435 }
1436 } else {
1437 path = out_oat_path;
1438 }
1439 in_vdex_path_str = create_vdex_filename(path);
1440 if (in_vdex_path_str.empty()) {
1441 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001442 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001443 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001444 // We can update in place when all these conditions are met:
1445 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1446 // on /system typically cannot be updated in place).
1447 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1448 // cannot be currently used by a running process.
1449 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1450 // different vdex files to operate.
1451 update_vdex_in_place =
1452 (in_vdex_path_str == out_vdex_path_str) &&
1453 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1454 !profile_guided;
1455 if (update_vdex_in_place) {
1456 // Open the file read-write to be able to update it.
1457 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1458 if (in_vdex_wrapper_fd->get() == -1) {
1459 // If we failed to open the file, we cannot update it in place.
1460 update_vdex_in_place = false;
1461 }
1462 } else {
1463 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1464 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001465 }
1466
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001467 // If we are updating the vdex in place, we do not need to recreate a vdex,
1468 // and can use the same existing one.
1469 if (update_vdex_in_place) {
1470 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1471 // have bogus stale vdex files.
1472 out_vdex_wrapper_fd->reset(
1473 in_vdex_wrapper_fd->get(),
1474 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1475 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1476 // wrapper).
1477 in_vdex_wrapper_fd->DisableAutoClose();
1478 } else {
1479 out_vdex_wrapper_fd->reset(
1480 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1481 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1482 if (out_vdex_wrapper_fd->get() < 0) {
1483 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1484 return false;
1485 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001486 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001487 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001488 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001489 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1490 return false;
1491 }
1492
1493 // If we got here we successfully opened the vdex files.
1494 return true;
1495}
1496
1497// Opens the output oat file for the given apk.
1498// If successful it stores the output path into out_oat_path and returns true.
1499Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001500 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1501 char* out_oat_path) {
1502 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001503 return Dex2oatFileWrapper();
1504 }
1505 const std::string out_oat_path_str(out_oat_path);
1506 Dex2oatFileWrapper wrapper_fd(
1507 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1508 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1509 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001510 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001511 } else if (!set_permissions_and_ownership(
1512 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001513 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1514 wrapper_fd.reset(-1);
1515 }
1516 return wrapper_fd;
1517}
1518
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001519// Creates RDONLY fds for oat and vdex files, if exist.
1520// Returns false if it fails to create oat out path for the given apk path.
1521// Note that the method returns true even if the files could not be opened.
1522bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1523 const std::string& oat_dir,
1524 const std::string& instruction_set,
1525 bool is_secondary_dex,
1526 unique_fd* oat_file_fd,
1527 unique_fd* vdex_file_fd) {
1528 char oat_path[PKG_PATH_MAX];
1529 if (!create_oat_out_path(apk_path.c_str(),
1530 instruction_set.c_str(),
1531 oat_dir.c_str(),
1532 is_secondary_dex,
1533 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001534 LOG(ERROR) << "Could not create oat out path for "
1535 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001536 return false;
1537 }
1538 oat_file_fd->reset(open(oat_path, O_RDONLY));
1539 if (oat_file_fd->get() < 0) {
1540 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1541 }
1542
1543 std::string vdex_filename = create_vdex_filename(oat_path);
1544 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1545 if (vdex_file_fd->get() < 0) {
1546 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1547 }
1548
1549 return true;
1550}
1551
Calin Juravle7a570e82017-01-14 16:23:30 -08001552// Updates the access times of out_oat_path based on those from apk_path.
1553void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1554 struct stat input_stat;
1555 memset(&input_stat, 0, sizeof(input_stat));
1556 if (stat(apk_path, &input_stat) != 0) {
1557 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1558 return;
1559 }
1560
1561 struct utimbuf ut;
1562 ut.actime = input_stat.st_atime;
1563 ut.modtime = input_stat.st_mtime;
1564 if (utime(out_oat_path, &ut) != 0) {
1565 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1566 }
1567}
1568
Calin Juravle80a21252017-01-17 14:43:25 -08001569// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001570// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1571// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1572// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001573class RunDexoptAnalyzer : public ExecVHelper {
1574 public:
1575 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001576 int vdex_fd,
1577 int oat_fd,
1578 int zip_fd,
1579 const std::string& instruction_set,
1580 const std::string& compiler_filter,
1581 bool profile_was_updated,
1582 bool downgrade,
1583 const char* class_loader_context,
1584 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001585 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001586
1587 // We always run the analyzer in the background job.
1588 const char* dexoptanalyzer_bin = select_execution_binary(
1589 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001590
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001591 std::string dex_file_arg = "--dex-file=" + dex_file;
1592 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1593 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1594 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1595 std::string isa_arg = "--isa=" + instruction_set;
1596 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1597 const char* assume_profile_changed = "--assume-profile-changed";
1598 const char* downgrade_flag = "--downgrade";
1599 std::string class_loader_context_arg = "--class-loader-context=";
1600 if (class_loader_context != nullptr) {
1601 class_loader_context_arg += class_loader_context;
1602 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001603 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1604 if (!class_loader_context_fds.empty()) {
1605 class_loader_context_fds_arg += class_loader_context_fds;
1606 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001607
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001608 // program name, dex file, isa, filter
1609 AddArg(dex_file_arg);
1610 AddArg(isa_arg);
1611 AddArg(compiler_filter_arg);
1612 if (oat_fd >= 0) {
1613 AddArg(oat_fd_arg);
1614 }
1615 if (vdex_fd >= 0) {
1616 AddArg(vdex_fd_arg);
1617 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001618 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001619 if (profile_was_updated) {
1620 AddArg(assume_profile_changed);
1621 }
1622 if (downgrade) {
1623 AddArg(downgrade_flag);
1624 }
1625 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001626 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001627 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001628 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001629 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001630 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001631
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001632 PrepareArgs(dexoptanalyzer_bin);
1633 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001634
1635 // Dexoptanalyzer mode which flattens the given class loader context and
1636 // prints a list of its dex files in that flattened order.
1637 RunDexoptAnalyzer(const char* class_loader_context) {
1638 CHECK(class_loader_context != nullptr);
1639
1640 // We always run the analyzer in the background job.
1641 const char* dexoptanalyzer_bin = select_execution_binary(
1642 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1643
1644 AddArg("--flatten-class-loader-context");
1645 AddArg(std::string("--class-loader-context=") + class_loader_context);
1646 PrepareArgs(dexoptanalyzer_bin);
1647 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001648};
Calin Juravle80a21252017-01-17 14:43:25 -08001649
1650// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001651static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001652 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001653 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001654 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001655 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001656 return false;
1657 }
Calin Juravle114f0812017-03-08 19:05:07 -08001658 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001659
Calin Juravle80a21252017-01-17 14:43:25 -08001660 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001661 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1662 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001663 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001664 return false;
1665 }
1666
1667 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001668 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001669
Calin Juravle7d765462017-09-04 15:57:10 -07001670 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001671 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001672 return false;
1673 }
1674
1675 return true;
1676}
1677
Calin Juravle7d765462017-09-04 15:57:10 -07001678// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1679// secondary dex files. This return codes are returned by the child process created for
1680// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001681
Andreas Gampe194fe422018-02-28 20:16:19 -08001682enum DexoptAnalyzerSkipCodes {
1683 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001684 // Specific errors are encoded in the name.
1685 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1686 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1687 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1688 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1689 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001690 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001691 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001692};
Calin Juravle7d765462017-09-04 15:57:10 -07001693
1694// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001695// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1696// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001697// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1698// of dexoptanalyzer.
1699static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001700 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001701 // The result values are defined in dexoptanalyzer.
1702 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001703 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001704 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001705 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001706 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001707 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001708 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001709 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001710 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001711 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1712 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001713 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1714 " Expected odex file status for secondary dex %s"
1715 " : dexoptanalyzer result=%d",
1716 dex_path.c_str(),
1717 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001718 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001719 }
1720
1721 // Use a second switch for enum switch-case analysis.
1722 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001723 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001724 // If the file does not exist there's no need for dexopt.
1725 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1726 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001727
1728 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1729 *error_msg = "Dexoptanalyzer path validation failed";
1730 return false;
1731 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1732 *error_msg = "Dexoptanalyzer open zip failed";
1733 return false;
1734 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1735 *error_msg = "Dexoptanalyzer dir preparation failed";
1736 return false;
1737 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1738 *error_msg = "Dexoptanalyzer open output failed";
1739 return false;
1740 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1741 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001742 return false;
1743 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001744
1745 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1746 dex_path.c_str(),
1747 result);
1748 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001749}
1750
Calin Juravle7d765462017-09-04 15:57:10 -07001751enum SecondaryDexAccess {
1752 kSecondaryDexAccessReadOk = 0,
1753 kSecondaryDexAccessDoesNotExist = 1,
1754 kSecondaryDexAccessPermissionError = 2,
1755 kSecondaryDexAccessIOError = 3
1756};
1757
1758static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1759 // Check if the path exists and can be read. If not, there's nothing to do.
1760 if (access(dex_path.c_str(), R_OK) == 0) {
1761 return kSecondaryDexAccessReadOk;
1762 } else {
1763 if (errno == ENOENT) {
1764 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1765 return kSecondaryDexAccessDoesNotExist;
1766 } else {
1767 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1768 return errno == EACCES
1769 ? kSecondaryDexAccessPermissionError
1770 : kSecondaryDexAccessIOError;
1771 }
1772 }
1773}
1774
1775static bool is_file_public(const std::string& filename) {
1776 struct stat file_stat;
1777 if (stat(filename.c_str(), &file_stat) == 0) {
1778 return (file_stat.st_mode & S_IROTH) != 0;
1779 }
1780 return false;
1781}
1782
1783// Create the oat file structure for the secondary dex 'dex_path' and assign
1784// the individual path component to the 'out_' parameters.
1785static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001786 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001787 size_t dirIndex = dex_path.rfind('/');
1788 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001789 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001790 return false;
1791 }
1792 // TODO(calin): we have similar computations in at lest 3 other places
1793 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1794 // using string append.
1795 std::string apk_dir = dex_path.substr(0, dirIndex);
1796 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1797 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1798
1799 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1800 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001801 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001802 return false;
1803 }
1804 return true;
1805}
1806
1807// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1808// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001809static bool validate_dexopt_storage_flags(int dexopt_flags,
1810 int* out_storage_flag,
1811 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001812 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1813 *out_storage_flag = FLAG_STORAGE_CE;
1814 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001815 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001816 return false;
1817 }
1818 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1819 *out_storage_flag = FLAG_STORAGE_DE;
1820 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001821 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001822 return false;
1823 }
1824 return true;
1825}
1826
David Brazdil4f6027a2019-03-19 11:44:21 +00001827static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1828 /* out */ std::vector<std::string>* context_dex_paths) {
1829 if (class_loader_context == nullptr) {
1830 return true;
1831 }
1832
1833 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1834
1835 // Pipe to get the hash result back from our child process.
1836 unique_fd pipe_read, pipe_write;
1837 if (!Pipe(&pipe_read, &pipe_write)) {
1838 PLOG(ERROR) << "Failed to create pipe";
1839 return false;
1840 }
1841
1842 pid_t pid = fork();
1843 if (pid == 0) {
1844 // child -- drop privileges before continuing.
1845 drop_capabilities(uid);
1846
1847 // Route stdout to `pipe_write`
1848 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1849 pipe_write.reset();
1850 pipe_read.reset();
1851
1852 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1853 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1854 }
1855
1856 /* parent */
1857 pipe_write.reset();
1858
1859 std::string str_dex_paths;
1860 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1861 PLOG(ERROR) << "Failed to read from pipe";
1862 return false;
1863 }
1864 pipe_read.reset();
1865
1866 int return_code = wait_child(pid);
1867 if (!WIFEXITED(return_code)) {
1868 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1869 return false;
1870 }
1871
1872 constexpr int kFlattenClassLoaderContextSuccess = 50;
1873 return_code = WEXITSTATUS(return_code);
1874 if (return_code != kFlattenClassLoaderContextSuccess) {
1875 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1876 return false;
1877 }
1878
1879 if (!str_dex_paths.empty()) {
1880 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1881 }
1882 return true;
1883}
1884
1885static int open_dex_paths(const std::vector<std::string>& dex_paths,
1886 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1887 for (const std::string& dex_path : dex_paths) {
1888 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1889 if (zip_fds->back().get() < 0) {
1890 *error_msg = StringPrintf(
1891 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1892 if (errno == ENOENT) {
1893 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1894 } else {
1895 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1896 }
1897 }
1898 }
1899 return 0;
1900}
1901
1902static std::string join_fds(const std::vector<unique_fd>& fds) {
1903 std::stringstream ss;
1904 bool is_first = true;
1905 for (const unique_fd& fd : fds) {
1906 if (is_first) {
1907 is_first = false;
1908 } else {
1909 ss << ":";
1910 }
1911 ss << fd.get();
1912 }
1913 return ss.str();
1914}
1915
Calin Juravlec9eab382017-01-25 01:17:17 -08001916// 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 -08001917// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1918// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001919// When returning true, the output parameters will be:
1920// - is_public_out: whether or not the oat file should not be made public
1921// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1922// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001923static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001924 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001925 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001926 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001927 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001928 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001929 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001930 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1931 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001932 return false;
1933 }
Calin Juravle7d765462017-09-04 15:57:10 -07001934 // Compute the oat dir as it's not easy to extract it from the child computation.
1935 char oat_path[PKG_PATH_MAX];
1936 char oat_dir[PKG_PATH_MAX];
1937 char oat_isa_dir[PKG_PATH_MAX];
1938 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001939 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1940 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001941 return false;
1942 }
Calin Juravle7d765462017-09-04 15:57:10 -07001943 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001944
Calin Juravle80a21252017-01-17 14:43:25 -08001945 pid_t pid = fork();
1946 if (pid == 0) {
1947 // child -- drop privileges before continuing.
1948 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001949
1950 // Validate the path structure.
1951 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1952 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001953 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001954 }
1955
1956 // Open the dex file.
1957 unique_fd zip_fd;
1958 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1959 if (zip_fd.get() < 0) {
1960 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001961 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001962 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001963 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001964 }
1965 }
1966
David Brazdil4f6027a2019-03-19 11:44:21 +00001967 // Open class loader context dex files.
1968 std::vector<unique_fd> context_zip_fds;
1969 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1970 if (open_dex_paths_rc != 0) {
1971 _exit(open_dex_paths_rc);
1972 }
1973
Calin Juravle7d765462017-09-04 15:57:10 -07001974 // Prepare the oat directories.
1975 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001976 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001977 }
1978
1979 // Open the vdex/oat files if any.
1980 unique_fd oat_file_fd;
1981 unique_fd vdex_file_fd;
1982 if (!maybe_open_oat_and_vdex_file(dex_path,
1983 *oat_dir_out,
1984 instruction_set,
1985 true /* is_secondary_dex */,
1986 &oat_file_fd,
1987 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001988 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001989 }
1990
1991 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001992 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1993 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001994
1995 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001996 // Note that we do not do it before the fork since opening the files is required to happen
1997 // after forking.
1998 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1999 vdex_file_fd.get(),
2000 oat_file_fd.get(),
2001 zip_fd.get(),
2002 instruction_set,
2003 compiler_filter, profile_was_updated,
2004 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00002005 class_loader_context,
2006 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002007 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08002008 }
2009
2010 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08002011 int result = wait_child(pid);
2012 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002013 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2014 dex_path.c_str(),
2015 result);
2016 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002017 return false;
2018 }
2019 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002020 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002021 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2022 result,
2023 dexopt_needed_out,
2024 error_msg);
2025 if (!success) {
2026 LOG(ERROR) << *error_msg;
2027 }
Calin Juravle7d765462017-09-04 15:57:10 -07002028
2029 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2030
Calin Juravle80a21252017-01-17 14:43:25 -08002031 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002032 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2033 // makes the code simpler; force compilation is only needed during tests).
2034 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002035 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002036 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002037 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2038 }
2039
Calin Juravle7d765462017-09-04 15:57:10 -07002040 // Check if we should make the oat file public.
2041 // Note that if the dex file is not public the compiled code cannot be made public.
2042 // It is ok to check this flag outside in the parent process.
2043 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2044
Calin Juravle80a21252017-01-17 14:43:25 -08002045 return success;
2046}
2047
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002048static std::string format_dexopt_error(int status, const char* dex_path) {
2049 if (WIFEXITED(status)) {
2050 int int_code = WEXITSTATUS(status);
2051 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2052 if (code_name != nullptr) {
2053 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2054 }
2055 }
2056 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002057}
2058
Calin Juravlec9eab382017-01-25 01:17:17 -08002059int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002060 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002061 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002062 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002063 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002064 CHECK(pkgname != nullptr);
2065 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002066 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002067 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2068 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002069
Calin Juravled23dee72017-07-06 16:29:11 -07002070 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002071 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002072 return -1;
2073 }
2074
2075 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002076 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2077 class_loader_context);
2078 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002079 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002080 }
2081
Calin Juravleebc8a792017-04-04 20:21:05 -07002082 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002083 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2084 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2085 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002086 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002087 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002088 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002089 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002090 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann00d3f4f2020-04-14 17:03:00 -07002091 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002092
2093 // Check if we're dealing with a secondary dex file and if we need to compile it.
2094 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002095 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002096 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002097 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2098 *error_msg = "Failed acquiring context dex paths";
2099 return -1; // We had an error, logged in the process method.
2100 }
2101
Calin Juravlec9eab382017-01-25 01:17:17 -08002102 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002103 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002104 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002105 oat_dir = oat_dir_str.c_str();
2106 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2107 return 0; // Nothing to do, report success.
2108 }
2109 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002110 if (error_msg->empty()) { // TODO: Make this a CHECK.
2111 *error_msg = "Failed processing secondary.";
2112 }
Calin Juravle80a21252017-01-17 14:43:25 -08002113 return -1; // We had an error, logged in the process method.
2114 }
2115 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002116 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002117 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002118 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2119 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2120 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002121
2122 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002123 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002124 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002125 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2126 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002127 return -1;
2128 }
2129
David Brazdil4f6027a2019-03-19 11:44:21 +00002130 // Open class loader context dex files.
2131 std::vector<unique_fd> context_input_fds;
2132 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2133 LOG(ERROR) << *error_msg;
2134 return -1;
2135 }
2136
Calin Juravle7a570e82017-01-14 16:23:30 -08002137 // Create the output OAT file.
2138 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002139 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002140 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002141 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002142 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002143 return -1;
2144 }
2145
2146 // Open vdex files.
2147 Dex2oatFileWrapper in_vdex_fd;
2148 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002149 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2150 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002151 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002152 return -1;
2153 }
2154
Calin Juravlecb556e32017-04-04 20:22:50 -07002155 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2156 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2157 // fully inherit their parent context).
2158 // Note that for primary apk the oat files are created before, in a separate installd
2159 // call which also does the restorecon. TODO(calin): unify the paths.
2160 if (is_secondary_dex) {
2161 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2162 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002163 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2164 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002165 return -1;
2166 }
2167 }
2168
Jeff Sharkey90aff262016-12-12 14:28:24 -07002169 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002170 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002171
Calin Juravle7a570e82017-01-14 16:23:30 -08002172 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002173 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002174 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002175
liulvping61907742018-08-21 09:36:52 +08002176 if (reference_profile_fd.get() == -1) {
2177 // We don't create an app image without reference profile since there is no speedup from
2178 // loading it in that case and instead will be a small overhead.
2179 generate_app_image = false;
2180 }
2181
2182 // Create the app image file if needed.
2183 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2184 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2185
Calin Juravle62c5a372018-02-01 17:03:23 +00002186 unique_fd dex_metadata_fd;
2187 if (dex_metadata_path != nullptr) {
2188 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2189 if (dex_metadata_fd.get() < 0) {
2190 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2191 }
2192 }
2193
Andreas Gampe023b2242018-02-28 16:03:25 -08002194 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002195
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002196 RunDex2Oat runner(input_fd.get(),
2197 out_oat_fd.get(),
2198 in_vdex_fd.get(),
2199 out_vdex_fd.get(),
2200 image_fd.get(),
2201 dex_path,
2202 out_oat_path,
2203 swap_fd.get(),
2204 instruction_set,
2205 compiler_filter,
2206 debuggable,
2207 boot_complete,
Patrick Baumann00d3f4f2020-04-14 17:03:00 -07002208 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002209 background_job_compile,
2210 reference_profile_fd.get(),
2211 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002212 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002213 target_sdk_version,
2214 enable_hidden_api_checks,
2215 generate_compact_dex,
2216 dex_metadata_fd.get(),
2217 compilation_reason);
2218
Jeff Sharkey90aff262016-12-12 14:28:24 -07002219 pid_t pid = fork();
2220 if (pid == 0) {
2221 /* child -- drop privileges before continuing */
2222 drop_capabilities(uid);
2223
Richard Uhler76cc0272016-12-08 10:46:35 +00002224 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002225 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002226 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002227 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002228 }
2229
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002230 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002231 } else {
2232 int res = wait_child(pid);
2233 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002234 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002235 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002236 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2237 << std::hex << std::setw(4) << res << ", process failed";
2238 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002239 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002240 }
2241 }
2242
Calin Juravlec9eab382017-01-25 01:17:17 -08002243 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002244
2245 // We've been successful, don't delete output.
2246 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002247 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002248 image_fd.SetCleanup(false);
2249 reference_profile_fd.SetCleanup(false);
2250
2251 return 0;
2252}
2253
Calin Juravlec9eab382017-01-25 01:17:17 -08002254// Try to remove the given directory. Log an error if the directory exists
2255// and is empty but could not be removed.
2256static bool rmdir_if_empty(const char* dir) {
2257 if (rmdir(dir) == 0) {
2258 return true;
2259 }
2260 if (errno == ENOENT || errno == ENOTEMPTY) {
2261 return true;
2262 }
2263 PLOG(ERROR) << "Failed to remove dir: " << dir;
2264 return false;
2265}
2266
2267// Try to unlink the given file. Log an error if the file exists and could not
2268// be unlinked.
2269static bool unlink_if_exists(const std::string& file) {
2270 if (unlink(file.c_str()) == 0) {
2271 return true;
2272 }
2273 if (errno == ENOENT) {
2274 return true;
2275
2276 }
2277 PLOG(ERROR) << "Could not unlink: " << file;
2278 return false;
2279}
2280
Calin Juravle7d765462017-09-04 15:57:10 -07002281enum ReconcileSecondaryDexResult {
2282 kReconcileSecondaryDexExists = 0,
2283 kReconcileSecondaryDexCleanedUp = 1,
2284 kReconcileSecondaryDexValidationError = 2,
2285 kReconcileSecondaryDexCleanUpError = 3,
2286 kReconcileSecondaryDexAccessIOError = 4,
2287};
Calin Juravlec9eab382017-01-25 01:17:17 -08002288
2289// Reconcile the secondary dex 'dex_path' and its generated oat files.
2290// Return true if all the parameters are valid and the secondary dex file was
2291// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2292// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2293// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2294// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2295// Return false if there were errors during processing. In this case
2296// out_secondary_dex_exists will be set to false.
2297bool reconcile_secondary_dex_file(const std::string& dex_path,
2298 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2299 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2300 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002301 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002302 if (isas.size() == 0) {
2303 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2304 return false;
2305 }
2306
Calin Juravle7d765462017-09-04 15:57:10 -07002307 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2308 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2309 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002310 return false;
2311 }
2312
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002313 // As a security measure we want to unlink art artifacts with the reduced capabilities
2314 // of the package user id. So we fork and drop capabilities in the child.
2315 pid_t pid = fork();
2316 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002317 /* child -- drop privileges before continuing */
2318 drop_capabilities(uid);
2319
2320 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Greg Kaiser8042c372019-03-26 06:23:19 -07002321 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002322 uid, storage_flag)) {
2323 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2324 _exit(kReconcileSecondaryDexValidationError);
2325 }
2326
2327 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2328 switch (access_check) {
2329 case kSecondaryDexAccessDoesNotExist:
2330 // File does not exist. Proceed with cleaning.
2331 break;
2332 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2333 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2334 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2335 default:
2336 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2337 _exit(kReconcileSecondaryDexValidationError);
2338 }
2339
2340 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002341 char oat_path[PKG_PATH_MAX];
2342 char oat_dir[PKG_PATH_MAX];
2343 char oat_isa_dir[PKG_PATH_MAX];
2344 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002345 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002346 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002347 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002348 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2349 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002350 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002351 }
Calin Juravle51314092017-05-18 15:33:05 -07002352
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002353 // Delete oat/vdex/art files.
2354 result = unlink_if_exists(oat_path) && result;
2355 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2356 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002357
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002358 // Delete profiles.
2359 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002360 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002361 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002362 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002363 result = unlink_if_exists(current_profile) && result;
2364 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002365
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002366 // We upgraded once the location of current profile for secondary dex files.
2367 // Check for any previous left-overs and remove them as well.
2368 std::string old_current_profile = dex_path + ".prof";
2369 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002370
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002371 // Try removing the directories as well, they might be empty.
2372 result = rmdir_if_empty(oat_isa_dir) && result;
2373 result = rmdir_if_empty(oat_dir) && result;
2374 }
Calin Juravle7d765462017-09-04 15:57:10 -07002375 if (!result) {
2376 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2377 }
2378 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002379 }
2380
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002381 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002382 if (!WIFEXITED(return_code)) {
2383 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2384 } else {
2385 return_code = WEXITSTATUS(return_code);
2386 }
2387
2388 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2389
2390 switch (return_code) {
2391 case kReconcileSecondaryDexCleanedUp:
2392 case kReconcileSecondaryDexValidationError:
2393 // If we couldn't validate assume the dex file does not exist.
2394 // This will purge the entry from the PM records.
2395 *out_secondary_dex_exists = false;
2396 return true;
2397 case kReconcileSecondaryDexExists:
2398 *out_secondary_dex_exists = true;
2399 return true;
2400 case kReconcileSecondaryDexAccessIOError:
2401 // We had an access IO error.
2402 // Return false so that we can try again.
2403 // The value of out_secondary_dex_exists does not matter in this case and by convention
2404 // is set to false.
2405 *out_secondary_dex_exists = false;
2406 return false;
2407 default:
2408 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2409 *out_secondary_dex_exists = false;
2410 return false;
2411 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002412}
2413
Alan Stokesa25d90c2017-10-16 10:56:00 +01002414// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2415// Returns true if all parameters are valid and the hash successfully computed and stored in
2416// out_secondary_dex_hash.
2417// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2418// the app.
2419// For any other errors (e.g. if any of the parameters are invalid) returns false.
2420bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2421 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2422 std::vector<uint8_t>* out_secondary_dex_hash) {
2423 out_secondary_dex_hash->clear();
2424
2425 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2426
2427 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2428 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2429 << storage_flag;
2430 return false;
2431 }
2432
2433 // Pipe to get the hash result back from our child process.
2434 unique_fd pipe_read, pipe_write;
2435 if (!Pipe(&pipe_read, &pipe_write)) {
2436 PLOG(ERROR) << "Failed to create pipe";
2437 return false;
2438 }
2439
2440 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2441 // access data the app itself can access.
2442 pid_t pid = fork();
2443 if (pid == 0) {
2444 // child -- drop privileges before continuing
2445 drop_capabilities(uid);
2446 pipe_read.reset();
2447
2448 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2449 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002450 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002451 }
2452
2453 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2454 if (fd == -1) {
2455 if (errno == EACCES || errno == ENOENT) {
2456 // Not treated as an error.
2457 _exit(0);
2458 }
2459 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002460 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002461 }
2462
2463 SHA256_CTX ctx;
2464 SHA256_Init(&ctx);
2465
2466 std::vector<uint8_t> buffer(65536);
2467 while (true) {
2468 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2469 if (bytes_read == 0) {
2470 break;
2471 } else if (bytes_read == -1) {
2472 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002473 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002474 }
2475
2476 SHA256_Update(&ctx, buffer.data(), bytes_read);
2477 }
2478
2479 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2480 SHA256_Final(hash.data(), &ctx);
2481 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002482 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002483 }
2484
2485 _exit(0);
2486 }
2487
2488 // parent
2489 pipe_write.reset();
2490
2491 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2492 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2493 out_secondary_dex_hash->clear();
2494 }
2495 return wait_child(pid) == 0;
2496}
2497
Jeff Sharkey90aff262016-12-12 14:28:24 -07002498// Helper for move_ab, so that we can have common failure-case cleanup.
2499static bool unlink_and_rename(const char* from, const char* to) {
2500 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2501 // return a failure.
2502 struct stat s;
2503 if (stat(to, &s) == 0) {
2504 if (!S_ISREG(s.st_mode)) {
2505 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2506 return false;
2507 }
2508 if (unlink(to) != 0) {
2509 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2510 return false;
2511 }
2512 } else {
2513 // This may be a permission problem. We could investigate the error code, but we'll just
2514 // let the rename failure do the work for us.
2515 }
2516
2517 // Try to rename "to" to "from."
2518 if (rename(from, to) != 0) {
2519 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2520 return false;
2521 }
2522 return true;
2523}
2524
2525// Move/rename a B artifact (from) to an A artifact (to).
2526static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2527 // Check whether B exists.
2528 {
2529 struct stat s;
2530 if (stat(b_path.c_str(), &s) != 0) {
2531 // Silently ignore for now. The service calling this isn't smart enough to understand
2532 // lack of artifacts at the moment.
2533 return false;
2534 }
2535 if (!S_ISREG(s.st_mode)) {
2536 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2537 // Try to unlink, but swallow errors.
2538 unlink(b_path.c_str());
2539 return false;
2540 }
2541 }
2542
2543 // Rename B to A.
2544 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2545 // Delete the b_path so we don't try again (or fail earlier).
2546 if (unlink(b_path.c_str()) != 0) {
2547 PLOG(ERROR) << "Could not unlink " << b_path;
2548 }
2549
2550 return false;
2551 }
2552
2553 return true;
2554}
2555
2556bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2557 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002558 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2559 if (slot_suffix.empty()) {
2560 return false;
2561 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002562
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002563 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2564 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2565 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002566 }
2567
2568 // Validate other inputs.
2569 if (validate_apk_path(apk_path) != 0) {
2570 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2571 return false;
2572 }
2573 if (validate_apk_path(oat_dir) != 0) {
2574 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2575 return false;
2576 }
2577
2578 char a_path[PKG_PATH_MAX];
2579 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2580 return false;
2581 }
2582 const std::string a_vdex_path = create_vdex_filename(a_path);
2583 const std::string a_image_path = create_image_filename(a_path);
2584
2585 // B path = A path + slot suffix.
2586 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2587 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2588 const std::string b_image_path = StringPrintf("%s.%s",
2589 a_image_path.c_str(),
2590 slot_suffix.c_str());
2591
2592 bool success = true;
2593 if (move_ab_path(b_path, a_path)) {
2594 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2595 // Note: we can live without an app image. As such, ignore failure to move the image file.
2596 // If we decide to require the app image, or the app image being moved correctly,
2597 // then change accordingly.
2598 constexpr bool kIgnoreAppImageFailure = true;
2599
2600 if (!a_image_path.empty()) {
2601 if (!move_ab_path(b_image_path, a_image_path)) {
2602 unlink(a_image_path.c_str());
2603 if (!kIgnoreAppImageFailure) {
2604 success = false;
2605 }
2606 }
2607 }
2608 } else {
2609 // Cleanup: delete B image, ignore errors.
2610 unlink(b_image_path.c_str());
2611 success = false;
2612 }
2613 } else {
2614 // Cleanup: delete B image, ignore errors.
2615 unlink(b_vdex_path.c_str());
2616 unlink(b_image_path.c_str());
2617 success = false;
2618 }
2619 return success;
2620}
2621
2622bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2623 // Delete the oat/odex file.
2624 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002625 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002626 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002627 return false;
2628 }
2629
2630 // In case of a permission failure report the issue. Otherwise just print a warning.
2631 auto unlink_and_check = [](const char* path) -> bool {
2632 int result = unlink(path);
2633 if (result != 0) {
2634 if (errno == EACCES || errno == EPERM) {
2635 PLOG(ERROR) << "Could not unlink " << path;
2636 return false;
2637 }
2638 PLOG(WARNING) << "Could not unlink " << path;
2639 }
2640 return true;
2641 };
2642
2643 // Delete the oat/odex file.
2644 bool return_value_oat = unlink_and_check(out_path);
2645
2646 // Derive and delete the app image.
2647 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2648
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002649 // Derive and delete the vdex file.
2650 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2651
Jeff Sharkey90aff262016-12-12 14:28:24 -07002652 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002653 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002654}
2655
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002656static bool is_absolute_path(const std::string& path) {
2657 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2658 LOG(ERROR) << "Invalid absolute path " << path;
2659 return false;
2660 } else {
2661 return true;
2662 }
2663}
2664
2665static bool is_valid_instruction_set(const std::string& instruction_set) {
2666 // TODO: add explicit whitelisting of instruction sets
2667 if (instruction_set.find('/') != std::string::npos) {
2668 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2669 return false;
2670 } else {
2671 return true;
2672 }
2673}
2674
2675bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2676 const char *apk_path, const char *instruction_set) {
2677 std::string oat_dir_ = oat_dir;
2678 std::string apk_path_ = apk_path;
2679 std::string instruction_set_ = instruction_set;
2680
2681 if (!is_absolute_path(oat_dir_)) return false;
2682 if (!is_absolute_path(apk_path_)) return false;
2683 if (!is_valid_instruction_set(instruction_set_)) return false;
2684
2685 std::string::size_type end = apk_path_.rfind('.');
2686 std::string::size_type start = apk_path_.rfind('/', end);
2687 if (end == std::string::npos || start == std::string::npos) {
2688 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2689 return false;
2690 }
2691
2692 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2693 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2694 const char* res = res_.c_str();
2695 if (strlen(res) >= PKG_PATH_MAX) {
2696 LOG(ERROR) << "Result too large";
2697 return false;
2698 } else {
2699 strlcpy(path, res, PKG_PATH_MAX);
2700 return true;
2701 }
2702}
2703
2704bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2705 const char *instruction_set) {
2706 std::string apk_path_ = apk_path;
2707 std::string instruction_set_ = instruction_set;
2708
2709 if (!is_absolute_path(apk_path_)) return false;
2710 if (!is_valid_instruction_set(instruction_set_)) return false;
2711
2712 std::string::size_type end = apk_path_.rfind('.');
2713 std::string::size_type start = apk_path_.rfind('/', end);
2714 if (end == std::string::npos || start == std::string::npos) {
2715 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2716 return false;
2717 }
2718
2719 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2720 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2721}
2722
2723bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2724 const char *instruction_set) {
2725 std::string src_ = src;
2726 std::string instruction_set_ = instruction_set;
2727
2728 if (!is_absolute_path(src_)) return false;
2729 if (!is_valid_instruction_set(instruction_set_)) return false;
2730
2731 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2732 if (*it == '/') {
2733 *it = '@';
2734 }
2735 }
2736
2737 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2738 + DALVIK_CACHE_POSTFIX;
2739 const char* res = res_.c_str();
2740 if (strlen(res) >= PKG_PATH_MAX) {
2741 LOG(ERROR) << "Result too large";
2742 return false;
2743 } else {
2744 strlcpy(path, res, PKG_PATH_MAX);
2745 return true;
2746 }
2747}
2748
Calin Juravle59f7ab82018-04-27 17:50:23 -07002749bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2750 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002751 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2752 for (const std::string& elem : classpaths_elems) {
2753 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2754 if (fd < 0) {
2755 PLOG(ERROR) << "Could not open classpath elem " << elem;
2756 return false;
2757 } else {
2758 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002759 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002760 }
2761 }
2762 return true;
2763}
2764
2765static bool create_app_profile_snapshot(int32_t app_id,
2766 const std::string& package_name,
2767 const std::string& profile_name,
2768 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002769 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2770
Calin Juravle824a64d2018-01-18 20:23:17 -08002771 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002772 if (snapshot_fd < 0) {
2773 return false;
2774 }
2775
2776 std::vector<unique_fd> profiles_fd;
2777 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002778 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2779 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002780 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2781 return false;
2782 }
2783
2784 profiles_fd.push_back(std::move(reference_profile_fd));
2785
Calin Juravle0d0a4922018-01-23 19:54:11 -08002786 // Open the class paths elements. These will be used to filter out profile data that does
2787 // not belong to the classpath during merge.
2788 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002789 std::vector<std::string> dex_locations;
2790 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002791 return false;
2792 }
2793
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002794 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002795 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002796 pid_t pid = fork();
2797 if (pid == 0) {
2798 /* child -- drop privileges before continuing */
2799 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002800 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002801 }
2802
2803 /* parent */
2804 int return_code = wait_child(pid);
2805 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002806 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002807 return false;
2808 }
2809
Calin Juravle78728f32019-11-08 17:55:46 -08002810 // Verify that profman finished successfully.
2811 int profman_code = WEXITSTATUS(return_code);
2812 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2813 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2814 << ":" << profman_code;
2815 return false;
2816 }
Calin Juravle29591732017-11-20 17:46:19 -08002817 return true;
2818}
2819
Calin Juravle0d0a4922018-01-23 19:54:11 -08002820static bool create_boot_image_profile_snapshot(const std::string& package_name,
2821 const std::string& profile_name,
2822 const std::string& classpath) {
2823 // The reference profile directory for the android package might not be prepared. Do it now.
2824 const std::string ref_profile_dir =
2825 create_primary_reference_profile_package_dir_path(package_name);
2826 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2827 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2828 return false;
2829 }
2830
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002831 // Return false for empty class path since it may otherwise return true below if profiles is
2832 // empty.
2833 if (classpath.empty()) {
2834 PLOG(ERROR) << "Class path is empty";
2835 return false;
2836 }
2837
Calin Juravle0d0a4922018-01-23 19:54:11 -08002838 // Open and create the snapshot profile.
2839 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2840
2841 // Collect all non empty profiles.
2842 // The collection will traverse all applications profiles and find the non empty files.
2843 // This has the potential of inspecting a large number of files and directories (depending
2844 // on the number of applications and users). So there is a slight increase in the chance
2845 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2846 // fail the snapshot and aggregate whatever profile we could open.
2847 //
2848 // The profile snapshot is a best effort based on available data it's ok if some data
2849 // from some apps is missing. It will be counter productive for the snapshot to fail
2850 // because we could not open or read some of the files.
2851 std::vector<std::string> profiles;
2852 if (!collect_profiles(&profiles)) {
2853 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2854 }
2855
2856 // If we have no profiles return early.
2857 if (profiles.empty()) {
2858 return true;
2859 }
2860
2861 // Open the classpath elements. These will be used to filter out profile data that does
2862 // not belong to the classpath during merge.
2863 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002864 std::vector<std::string> dex_locations;
2865 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002866 return false;
2867 }
2868
2869 // If we could not open any files from the classpath return an error.
2870 if (apk_fds.empty()) {
2871 LOG(ERROR) << "Could not open any of the classpath elements.";
2872 return false;
2873 }
2874
2875 // Aggregate the profiles in batches of kAggregationBatchSize.
2876 // We do this to avoid opening a huge a amount of files.
2877 static constexpr size_t kAggregationBatchSize = 10;
2878
Calin Juravle0d0a4922018-01-23 19:54:11 -08002879 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002880 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002881 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2882 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2883 if (fd.get() >= 0) {
2884 profiles_fd.push_back(std::move(fd));
2885 }
2886 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002887
2888 // We aggregate (read & write) into the same fd multiple times in a row.
2889 // We need to reset the cursor every time to ensure we read the whole file every time.
2890 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2891 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2892 return false;
2893 }
2894
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002895 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002896 args.SetupMerge(profiles_fd,
2897 snapshot_fd,
2898 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002899 dex_locations,
2900 /*for_snapshot=*/true,
2901 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002902 pid_t pid = fork();
2903 if (pid == 0) {
2904 /* child -- drop privileges before continuing */
2905 drop_capabilities(AID_SYSTEM);
2906
Calin Juravle59f7ab82018-04-27 17:50:23 -07002907 // The introduction of new access flags into boot jars causes them to
2908 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002909 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002910 }
2911
2912 /* parent */
2913 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002914
Calin Juravle0d0a4922018-01-23 19:54:11 -08002915 if (!WIFEXITED(return_code)) {
2916 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2917 return false;
2918 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002919
2920 // Verify that profman finished successfully.
2921 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002922 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2923 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2924 << ":" << profman_code;
2925 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002926 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002927 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002928
Calin Juravle0d0a4922018-01-23 19:54:11 -08002929 return true;
2930}
2931
2932bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2933 const std::string& profile_name, const std::string& classpath) {
2934 if (app_id == -1) {
2935 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2936 } else {
2937 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2938 }
2939}
2940
Calin Juravlec3b049e2018-01-18 22:32:58 -08002941bool prepare_app_profile(const std::string& package_name,
2942 userid_t user_id,
2943 appid_t app_id,
2944 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002945 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002946 const std::unique_ptr<std::string>& dex_metadata) {
2947 // Prepare the current profile.
2948 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2949 /*is_secondary_dex*/ false);
2950 uid_t uid = multiuser_get_uid(user_id, app_id);
2951 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2952 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2953 return false;
2954 }
2955
2956 // Check if we need to install the profile from the dex metadata.
2957 if (dex_metadata == nullptr) {
2958 return true;
2959 }
2960
2961 // We have a dex metdata. Merge the profile into the reference profile.
2962 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2963 /*read_write*/ true, /*is_secondary_dex*/ false);
2964 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2965 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002966 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2967 if (apk_fd < 0) {
2968 PLOG(ERROR) << "Could not open code path " << code_path;
2969 return false;
2970 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002971
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002972 RunProfman args;
2973 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2974 std::move(ref_profile_fd),
2975 std::move(apk_fd),
2976 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002977 pid_t pid = fork();
2978 if (pid == 0) {
2979 /* child -- drop privileges before continuing */
2980 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2981 drop_capabilities(app_shared_gid);
2982
Calin Juravlef63d4792018-01-30 17:43:34 +00002983 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002984 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002985 }
2986
2987 /* parent */
2988 int return_code = wait_child(pid);
2989 if (!WIFEXITED(return_code)) {
2990 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2991 return false;
2992 }
2993 return true;
2994}
2995
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002996} // namespace installd
2997} // namespace android