blob: 3c0443595e1e0aa0373803ded629b669b0aecea1 [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 Baumann2271b3e2020-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 Baumann2271b3e2020-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 Baumann2271b3e2020-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
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100399 std::string updatable_bcp_packages =
400 MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
401 "--updatable-bcp-packages-file=%s");
402 if (updatable_bcp_packages.empty()) {
403 // Make dex2oat fail by providing non-existent file name.
404 updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
405 }
406
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800407 std::string resolve_startup_string_arg =
408 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
409 "--resolve-startup-const-strings=%s");
410 if (resolve_startup_string_arg.empty()) {
411 // If empty, fall back to system property.
412 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800413 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
414 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800415 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800416
417 const std::string image_block_size_arg =
418 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
419 "--max-image-block-size=%s");
420
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800421 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700422
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800423 std::string image_format_arg;
424 if (image_fd >= 0) {
425 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000426 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000427
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800428 std::string dex2oat_large_app_threshold_arg =
429 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000430
Calin Juravlef74a7372019-02-28 20:29:41 -0800431
David Sehr6df89a62020-04-15 20:43:48 -0700432
433 // Decide whether to use dex2oat64.
434 bool use_dex2oat64 = false;
435 // Check whether the device even supports 64-bit ABIs.
436 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
437 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
438 }
Calin Juravlef74a7372019-02-28 20:29:41 -0800439 const char* dex2oat_bin = select_execution_binary(
David Sehr6df89a62020-04-15 20:43:48 -0700440 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
441 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
442 background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000443
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800444 bool generate_minidebug_info = kEnableMinidebugInfo &&
445 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000446
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000447 std::string boot_image;
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000448 std::string use_jitzygote_image =
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000449 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000450 ENABLE_JITZYGOTE_IMAGE,
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000451 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700452
453 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
454 profile_boot_class_path =
455 server_configurable_flags::GetServerConfigurableFlag(
456 RUNTIME_NATIVE_BOOT_NAMESPACE,
457 PROFILE_BOOT_CLASS_PATH,
458 /*default_value=*/ profile_boot_class_path);
459
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000460 if (use_jitzygote_image == "true" || profile_boot_class_path == "true") {
461 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000462 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000463 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000464 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000465
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800466 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
467 // use arraysize instead.
468 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
469 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
470 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
471 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
472 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
473 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
474 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
475 std::string dex2oat_compiler_filter_arg;
476 std::string dex2oat_swap_fd;
477 std::string dex2oat_image_fd;
478 std::string target_sdk_version_arg;
479 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000480 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800481 }
482 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000483 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800484 if (class_loader_context != nullptr) {
485 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
486 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000487 if (!class_loader_context_fds.empty()) {
488 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
489 class_loader_context_fds.c_str());
490 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800491 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000492
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800493 if (swap_fd >= 0) {
494 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
495 }
496 if (image_fd >= 0) {
497 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
498 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000499
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800500 // Compute compiler filter.
501 bool have_dex2oat_relocation_skip_flag = false;
502 if (skip_compilation) {
503 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
504 have_dex2oat_relocation_skip_flag = true;
505 } else if (compiler_filter != nullptr) {
506 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
507 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000508
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800509 if (dex2oat_compiler_filter_arg.empty()) {
510 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
511 "--compiler-filter=%s");
512 }
513
514 // Check whether all apps should be compiled debuggable.
515 if (!debuggable) {
516 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
517 }
518 std::string profile_arg;
519 if (profile_fd != -1) {
520 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
521 }
522
523 // Get the directory of the apk to pass as a base classpath directory.
524 std::string base_dir;
525 std::string apk_dir(input_file_name);
526 unsigned long dir_index = apk_dir.rfind('/');
527 bool has_base_dir = dir_index != std::string::npos;
528 if (has_base_dir) {
529 apk_dir = apk_dir.substr(0, dir_index);
530 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
531 }
532
533 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
534
535 std::string compilation_reason_arg = compilation_reason == nullptr
536 ? ""
537 : std::string("--compilation-reason=") + compilation_reason;
538
539 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
540
541 // Disable cdex if update input vdex is true since this combination of options is not
542 // supported.
543 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
544
545 AddArg(zip_fd_arg);
546 AddArg(zip_location_arg);
547 AddArg(input_vdex_fd_arg);
548 AddArg(output_vdex_fd_arg);
549 AddArg(oat_fd_arg);
550 AddArg(oat_location_arg);
551 AddArg(instruction_set_arg);
552
553 AddArg(instruction_set_variant_arg);
554 AddArg(instruction_set_features_arg);
555
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000556 AddArg(boot_image);
557
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000558 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800559 AddRuntimeArg(dex2oat_Xms_arg);
560 AddRuntimeArg(dex2oat_Xmx_arg);
561
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100562 AddArg(updatable_bcp_packages);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800563 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800564 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800565 AddArg(dex2oat_compiler_filter_arg);
566 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000567 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800568 AddArg(dex2oat_swap_fd);
569 AddArg(dex2oat_image_fd);
570
571 if (generate_debug_info) {
572 AddArg("--generate-debug-info");
573 }
574 if (debuggable) {
575 AddArg("--debuggable");
576 }
577 AddArg(image_format_arg);
578 AddArg(dex2oat_large_app_threshold_arg);
579
580 if (have_dex2oat_relocation_skip_flag) {
581 AddRuntimeArg(dex2oat_norelocation);
582 }
583 AddArg(profile_arg);
584 AddArg(base_dir);
585 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000586 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800587 if (generate_minidebug_info) {
588 AddArg(kMinidebugDex2oatFlag);
589 }
590 if (disable_cdex) {
591 AddArg(kDisableCompactDexFlag);
592 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000593 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800594 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100595 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800596 }
597
598 if (dex_metadata_fd > -1) {
599 AddArg(dex_metadata_fd_arg);
600 }
601
602 AddArg(compilation_reason_arg);
603
604 // Do not add args after dex2oat_flags, they should override others for debugging.
605 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
606
607 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000608 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800609};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700610
611/*
612 * Whether dexopt should use a swap file when compiling an APK.
613 *
614 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
615 * itself, anyways).
616 *
617 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
618 *
619 * Otherwise, return true if this is a low-mem device.
620 *
621 * Otherwise, return default value.
622 */
623static bool kAlwaysProvideSwapFile = false;
624static bool kDefaultProvideSwapFile = true;
625
626static bool ShouldUseSwapFileForDexopt() {
627 if (kAlwaysProvideSwapFile) {
628 return true;
629 }
630
631 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700632 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
633 if (!dex2oat_prop_buf.empty()) {
634 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700635 }
636
637 // Shortcut for default value. This is an implementation optimization for the process sketched
638 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
639 // as low-mem is never returning false. The compiler will optimize this away if it can.
640 if (kDefaultProvideSwapFile) {
641 return true;
642 }
643
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700644 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700645 return true;
646 }
647
648 // Default value must be false here.
649 return kDefaultProvideSwapFile;
650}
651
Richard Uhler76cc0272016-12-08 10:46:35 +0000652static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 if (set_to_bg) {
654 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800655 PLOG(ERROR) << "set_sched_policy failed";
656 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700657 }
658 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800659 PLOG(ERROR) << "setpriority failed";
660 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 }
662 }
663}
664
Calin Juravle29591732017-11-20 17:46:19 -0800665static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
666 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800667 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800668 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800669 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800670 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800671 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700672 }
Calin Juravle114f0812017-03-08 19:05:07 -0800673 // Profiles should belong to the app; make sure of that by giving ownership to
674 // the app uid. If we cannot do that, there's no point in returning the fd
675 // since dex2oat/profman will fail with SElinux denials.
676 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000677 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800678 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800679 }
Calin Juravle29591732017-11-20 17:46:19 -0800680 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800681}
682
Calin Juravle29591732017-11-20 17:46:19 -0800683static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800684 // Do not follow symlinks when opening a profile:
685 // - primary profiles should not contain symlinks in their paths
686 // - secondary dex paths should have been already resolved and validated
687 flags |= O_NOFOLLOW;
688
Calin Juravle29591732017-11-20 17:46:19 -0800689 // Check if we need to create the profile
690 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
691 unique_fd fd;
692 if ((flags & O_CREAT) != 0) {
693 fd = create_profile(uid, profile, flags);
694 } else {
695 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
696 }
697
Calin Juravle114f0812017-03-08 19:05:07 -0800698 if (fd.get() < 0) {
699 if (errno != ENOENT) {
700 // Profiles might be missing for various reasons. For example, in a
701 // multi-user environment, the profile directory for one user can be created
702 // after we start a merge. In this case the current profile for that user
703 // will not be found.
704 // Also, the secondary dex profiles might be deleted by the app at any time,
705 // so we can't we need to prepare if they are missing.
706 PLOG(ERROR) << "Failed to open profile " << profile;
707 }
708 return invalid_unique_fd();
709 }
710
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711 return fd;
712}
713
Calin Juravle824a64d2018-01-18 20:23:17 -0800714static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
715 const std::string& location, bool is_secondary_dex) {
716 std::string profile = create_current_profile_path(user, package_name, location,
717 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800718 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800719}
720
Calin Juravle824a64d2018-01-18 20:23:17 -0800721static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
722 const std::string& location, bool read_write, bool is_secondary_dex) {
723 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800724 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
725}
726
727static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800728 const std::string& location) {
729 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800730 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800731}
732
Calin Juravle824a64d2018-01-18 20:23:17 -0800733static void open_profile_files(uid_t uid, const std::string& package_name,
734 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800735 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700736 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800737 *reference_profile_fd = open_reference_profile(uid, package_name, location,
738 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700739
Calin Juravle114f0812017-03-08 19:05:07 -0800740 // For secondary dex files, we don't really need the user but we use it for sanity checks.
741 // Note: the user owning the dex file should be the current user.
742 std::vector<userid_t> users;
743 if (is_secondary_dex){
744 users.push_back(multiuser_get_user_id(uid));
745 } else {
746 users = get_known_users(/*volume_uuid*/ nullptr);
747 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700748 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800749 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
750 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700751 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800752 if (profile_fd.get() >= 0) {
753 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700754 }
755 }
756}
757
Calin Juravle76561322019-11-14 09:08:52 -0800758static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
759static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
760static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
761static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
762static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
763static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
764static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700765
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800766class RunProfman : public ExecVHelper {
767 public:
768 void SetupArgs(const std::vector<unique_fd>& profile_fds,
769 const unique_fd& reference_profile_fd,
770 const std::vector<unique_fd>& apk_fds,
771 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800772 bool copy_and_update,
773 bool for_snapshot,
774 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800775
776 // TODO(calin): Assume for now we run in the bg compile job (which is in
777 // most of the invocation). With the current data flow, is not very easy or
778 // clean to discover this in RunProfman (it will require quite a messy refactoring).
779 const char* profman_bin = select_execution_binary(
780 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700781
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800782 if (copy_and_update) {
783 CHECK_EQ(1u, profile_fds.size());
784 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000785 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800786 if (reference_profile_fd != -1) {
787 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000788 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800789
790 for (const unique_fd& fd : profile_fds) {
791 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
792 }
793
794 for (const unique_fd& fd : apk_fds) {
795 AddArg("--apk-fd=" + std::to_string(fd.get()));
796 }
797
798 for (const std::string& dex_location : dex_locations) {
799 AddArg("--dex-location=" + dex_location);
800 }
801
802 if (copy_and_update) {
803 AddArg("--copy-and-update-profile-key");
804 }
805
Calin Juravle78728f32019-11-08 17:55:46 -0800806 if (for_snapshot) {
807 AddArg("--force-merge");
808 }
809
810 if (for_boot_image) {
811 AddArg("--boot-image-merge");
812 }
813
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800814 // Do not add after dex2oat_flags, they should override others for debugging.
815 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800816 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800818 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
819 const unique_fd& reference_profile_fd,
820 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800821 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
822 bool for_snapshot = false,
823 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800824 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800825 reference_profile_fd,
826 apk_fds,
827 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800828 /*copy_and_update=*/ false,
829 for_snapshot,
830 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800831 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700832
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800833 void SetupCopyAndUpdate(unique_fd&& profile_fd,
834 unique_fd&& reference_profile_fd,
835 unique_fd&& apk_fd,
836 const std::string& dex_location) {
837 // The fds need to stay open longer than the scope of the function, so put them into a local
838 // variable vector.
839 profiles_fd_.push_back(std::move(profile_fd));
840 apk_fds_.push_back(std::move(apk_fd));
841 reference_profile_fd_ = std::move(reference_profile_fd);
842 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800843 SetupArgs(profiles_fd_,
844 reference_profile_fd_,
845 apk_fds_,
846 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800847 /*copy_and_update=*/true,
848 /*for_snapshot*/false,
849 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800850 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000851
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800852 void SetupDump(const std::vector<unique_fd>& profiles_fd,
853 const unique_fd& reference_profile_fd,
854 const std::vector<std::string>& dex_locations,
855 const std::vector<unique_fd>& apk_fds,
856 const unique_fd& output_fd) {
857 AddArg("--dump-only");
858 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800859 SetupArgs(profiles_fd,
860 reference_profile_fd,
861 apk_fds,
862 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800863 /*copy_and_update=*/false,
864 /*for_snapshot*/false,
865 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800866 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000867
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800868 void Exec() {
869 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
870 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000871
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800872 private:
873 unique_fd reference_profile_fd_;
874 std::vector<unique_fd> profiles_fd_;
875 std::vector<unique_fd> apk_fds_;
876};
Mathieu Chartier31636522018-11-09 23:53:07 +0000877
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800878
Calin Juravlef63d4792018-01-30 17:43:34 +0000879
Jeff Sharkey90aff262016-12-12 14:28:24 -0700880// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800881// The location is the package name for primary apks or the dex path for secondary dex files.
882// Returns true if there is enough information in the current profiles that makes it
883// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884// If the return value is true all the current profiles would have been merged into
885// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800886static bool analyze_profiles(uid_t uid, const std::string& package_name,
887 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800888 std::vector<unique_fd> profiles_fd;
889 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800890 open_profile_files(uid, package_name, location, is_secondary_dex,
891 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800892 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700893 // Skip profile guided compilation because no profiles were found.
894 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700895 return false;
896 }
897
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800898 RunProfman profman_merge;
899 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700900 pid_t pid = fork();
901 if (pid == 0) {
902 /* child -- drop privileges before continuing */
903 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800904 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700905 }
906 /* parent */
907 int return_code = wait_child(pid);
908 bool need_to_compile = false;
909 bool should_clear_current_profiles = false;
910 bool should_clear_reference_profile = false;
911 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800912 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700913 } else {
914 return_code = WEXITSTATUS(return_code);
915 switch (return_code) {
916 case PROFMAN_BIN_RETURN_CODE_COMPILE:
917 need_to_compile = true;
918 should_clear_current_profiles = true;
919 should_clear_reference_profile = false;
920 break;
921 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
922 need_to_compile = false;
923 should_clear_current_profiles = false;
924 should_clear_reference_profile = false;
925 break;
926 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800927 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700928 need_to_compile = false;
929 should_clear_current_profiles = true;
930 should_clear_reference_profile = true;
931 break;
932 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
933 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
934 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800935 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700936 need_to_compile = false;
937 should_clear_current_profiles = false;
938 should_clear_reference_profile = false;
939 break;
Calin Juravle76561322019-11-14 09:08:52 -0800940 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
941 need_to_compile = false;
942 should_clear_current_profiles = true;
943 should_clear_reference_profile = true;
944 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700945 default:
946 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800947 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800948 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700949 need_to_compile = false;
950 should_clear_current_profiles = true;
951 should_clear_reference_profile = true;
952 break;
953 }
954 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800955
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800957 if (is_secondary_dex) {
958 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800959 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
960 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800961 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800962 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800963 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964 }
965 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800966 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967 }
968 return need_to_compile;
969}
970
Calin Juravle114f0812017-03-08 19:05:07 -0800971// Decides if profile guided compilation is needed or not based on existing profiles.
972// The analysis is done for the primary apks of the given package.
973// Returns true if there is enough information in the current profiles that makes it
974// worth to recompile the package.
975// If the return value is true all the current profiles would have been merged into
976// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800977bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
978 const std::string& profile_name) {
979 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800980}
981
Calin Juravle408cd4a2018-01-20 23:34:18 -0800982bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
983 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800984 std::vector<unique_fd> profile_fds;
985 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800986 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
987 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988
Calin Juravle408cd4a2018-01-20 23:34:18 -0800989 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800990 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700991
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800992 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700993 const bool has_profiles = !profile_fds.empty();
994
995 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800996 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700997 return false;
998 }
999
Calin Juravle114f0812017-03-08 19:05:07 -08001000 unique_fd output_fd(open(out_file_name.c_str(),
1001 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -08001003 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 return false;
1005 }
Calin Juravle408cd4a2018-01-20 23:34:18 -08001006
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001008 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -08001009 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
1010 if (apk_fd == -1) {
1011 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
1012 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001013 }
Calin Juravle408cd4a2018-01-20 23:34:18 -08001014 dex_locations.push_back(get_location_from_path(code_path.c_str()));
1015 apk_fds.push_back(std::move(apk_fd));
1016
Jeff Sharkey90aff262016-12-12 14:28:24 -07001017
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001018 RunProfman profman_dump;
1019 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001020 pid_t pid = fork();
1021 if (pid == 0) {
1022 /* child -- drop privileges before continuing */
1023 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001024 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001025 }
1026 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001027 int return_code = wait_child(pid);
1028 if (!WIFEXITED(return_code)) {
1029 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1030 << return_code;
1031 return false;
1032 }
1033 return true;
1034}
1035
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001036bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001037 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001038 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1039 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001040 package_name,
1041 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001042 /*read_write*/ true,
1043 /*secondary*/ false));
1044 if (in_fd.get() < 0) {
1045 PLOG(WARNING) << "Could not open profile " << system_profile;
1046 return false;
1047 }
1048 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001049 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001050 return false;
1051 }
1052
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001053 // As a security measure we want to write the profile information with the reduced capabilities
1054 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001055 pid_t pid = fork();
1056 if (pid == 0) {
1057 /* child -- drop privileges before continuing */
1058 drop_capabilities(packageUid);
1059
1060 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1061 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001062 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001063 }
1064 // This implies that the app owning this profile is running
1065 // (and has acquired the lock).
1066 //
1067 // The app never acquires the lock for the reference profiles of primary apks.
1068 // Only dex2oat from installd will do that. Since installd is single threaded
1069 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001070 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001071 return false;
1072 }
1073
1074 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1075 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001076 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001077 }
1078
1079 // Copy over data.
1080 static constexpr size_t kBufferSize = 4 * 1024;
1081 char buffer[kBufferSize];
1082 while (true) {
1083 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1084 if (bytes == 0) {
1085 break;
1086 }
1087 write(out_fd.get(), buffer, bytes);
1088 }
1089 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001090 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001091 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001092 // Use _exit since we don't want to run the global destructors in the child.
1093 // b/62597429
1094 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001095 }
1096 /* parent */
1097 int return_code = wait_child(pid);
1098 return return_code == 0;
1099}
1100
Jeff Sharkey90aff262016-12-12 14:28:24 -07001101static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1102 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1103 if (EndsWith(oat_path, ".dex")) {
1104 std::string new_path = oat_path;
1105 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001106 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001107 return new_path;
1108 }
1109
1110 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1111 // case (where the base name will have an extension for the B artifact).
1112 size_t odex_pos = oat_path.rfind(".odex");
1113 if (odex_pos != std::string::npos) {
1114 std::string new_path = oat_path;
1115 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1116 CHECK_NE(new_path.find(new_ext), std::string::npos);
1117 return new_path;
1118 }
1119
1120 // Don't know how to handle this.
1121 return "";
1122}
1123
1124// Translate the given oat path to an art (app image) path. An empty string
1125// denotes an error.
1126static std::string create_image_filename(const std::string& oat_path) {
1127 return replace_file_extension(oat_path, ".art");
1128}
1129
1130// Translate the given oat path to a vdex path. An empty string denotes an error.
1131static std::string create_vdex_filename(const std::string& oat_path) {
1132 return replace_file_extension(oat_path, ".vdex");
1133}
1134
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135static int open_output_file(const char* file_name, bool recreate, int permissions) {
1136 int flags = O_RDWR | O_CREAT;
1137 if (recreate) {
1138 if (unlink(file_name) < 0) {
1139 if (errno != ENOENT) {
1140 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1141 }
1142 }
1143 flags |= O_EXCL;
1144 }
1145 return open(file_name, flags, permissions);
1146}
1147
Calin Juravle2289c0a2017-02-15 12:44:14 -08001148static bool set_permissions_and_ownership(
1149 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1150 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1151 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001152 if (fchmod(fd,
1153 S_IRUSR|S_IWUSR|S_IRGRP |
1154 (is_public ? S_IROTH : 0)) < 0) {
1155 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1156 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001157 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1159 return false;
1160 }
1161 return true;
1162}
1163
1164static bool IsOutputDalvikCache(const char* oat_dir) {
1165 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1166 // into '!'. Play it safe by handling it both.
1167 // TODO: ensure we never get null.
1168 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1169 return oat_dir == nullptr || oat_dir[0] == '!';
1170}
1171
Calin Juravled23dee72017-07-06 16:29:11 -07001172// Best-effort check whether we can fit the the path into our buffers.
1173// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1174// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1175// extension to the cache path (5 bytes).
1176// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1177static bool validate_dex_path_size(const std::string& dex_path) {
1178 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1179 LOG(ERROR) << "dex_path too long: " << dex_path;
1180 return false;
1181 }
1182 return true;
1183}
1184
Jeff Sharkey90aff262016-12-12 14:28:24 -07001185static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001186 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001187 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001188 return false;
1189 }
1190
1191 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001192 // Oat dirs for secondary dex files are already validated.
1193 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001194 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1195 return false;
1196 }
1197 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1198 return false;
1199 }
1200 } else {
1201 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1202 return false;
1203 }
1204 }
1205 return true;
1206}
1207
1208// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1209// on destruction. It will also run the given cleanup (unless told not to) after closing.
1210//
1211// Usage example:
1212//
Calin Juravle7a570e82017-01-14 16:23:30 -08001213// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001214// [name]() {
1215// unlink(name.c_str());
1216// });
1217// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1218// wrapper if captured as a reference.
1219//
1220// if (file.get() == -1) {
1221// // Error opening...
1222// }
1223//
1224// ...
1225// if (error) {
1226// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1227// // and delete the file (after the fd is closed).
1228// return -1;
1229// }
1230//
1231// (Success case)
1232// file.SetCleanup(false);
1233// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1234// // (leaving the file around; after the fd is closed).
1235//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001236class Dex2oatFileWrapper {
1237 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001238 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001239 }
1240
Calin Juravle7a570e82017-01-14 16:23:30 -08001241 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1242 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1243
1244 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1245 value_ = other.value_;
1246 cleanup_ = other.cleanup_;
1247 do_cleanup_ = other.do_cleanup_;
1248 auto_close_ = other.auto_close_;
1249 other.release();
1250 }
1251
1252 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1253 value_ = other.value_;
1254 cleanup_ = other.cleanup_;
1255 do_cleanup_ = other.do_cleanup_;
1256 auto_close_ = other.auto_close_;
1257 other.release();
1258 return *this;
1259 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260
1261 ~Dex2oatFileWrapper() {
1262 reset(-1);
1263 }
1264
1265 int get() {
1266 return value_;
1267 }
1268
1269 void SetCleanup(bool cleanup) {
1270 do_cleanup_ = cleanup;
1271 }
1272
1273 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001274 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001275 close(value_);
1276 }
1277 if (do_cleanup_ && cleanup_ != nullptr) {
1278 cleanup_();
1279 }
1280
1281 value_ = new_value;
1282 }
1283
Calin Juravle7a570e82017-01-14 16:23:30 -08001284 void reset(int new_value, std::function<void ()> new_cleanup) {
1285 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001286 close(value_);
1287 }
1288 if (do_cleanup_ && cleanup_ != nullptr) {
1289 cleanup_();
1290 }
1291
1292 value_ = new_value;
1293 cleanup_ = new_cleanup;
1294 }
1295
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 void DisableAutoClose() {
1297 auto_close_ = false;
1298 }
1299
Jeff Sharkey90aff262016-12-12 14:28:24 -07001300 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001301 void release() {
1302 value_ = -1;
1303 do_cleanup_ = false;
1304 cleanup_ = nullptr;
1305 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001306 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001307 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001308 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001309 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001310};
1311
Calin Juravle7a570e82017-01-14 16:23:30 -08001312// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001313Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1314 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001315
Calin Juravle7a570e82017-01-14 16:23:30 -08001316 const std::string image_path = create_image_filename(out_oat_path);
1317 if (image_path.empty()) {
1318 // Happens when the out_oat_path has an unknown extension.
1319 return Dex2oatFileWrapper();
1320 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001321
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001322 // In case there is a stale image, remove it now. Ignore any error.
1323 unlink(image_path.c_str());
1324
1325 // Not enabled, exit.
1326 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001327 return Dex2oatFileWrapper();
1328 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001329 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1330 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001331 return Dex2oatFileWrapper();
1332 }
1333 // Recreate is true since we do not want to modify a mapped image. If the app is
1334 // already running and we modify the image file, it can cause crashes (b/27493510).
1335 Dex2oatFileWrapper wrapper_fd(
1336 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1337 [image_path]() { unlink(image_path.c_str()); });
1338 if (wrapper_fd.get() < 0) {
1339 // Could not create application image file. Go on since we can compile without it.
1340 LOG(ERROR) << "installd could not create '" << image_path
1341 << "' for image file during dexopt";
1342 // If we have a valid image file path but no image fd, explicitly erase the image file.
1343 if (unlink(image_path.c_str()) < 0) {
1344 if (errno != ENOENT) {
1345 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1346 }
1347 }
1348 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001349 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001350 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1351 wrapper_fd.reset(-1);
1352 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001353
Calin Juravle7a570e82017-01-14 16:23:30 -08001354 return wrapper_fd;
1355}
1356
1357// Creates the dexopt swap file if necessary and return its fd.
1358// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001359unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001360 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001361 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001362 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001363 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001364 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001365 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001366 if (swap_fd.get() < 0) {
1367 // Could not create swap file. Optimistically go on and hope that we can compile
1368 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001369 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001370 } else {
1371 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001372 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001373 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1374 }
1375 }
1376 return swap_fd;
1377}
1378
1379// Opens the reference profiles if needed.
1380// 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 -08001381Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001382 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001383 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001384 // If we are not profile guided compilation, or we are compiling system server
1385 // do not bother to open the profiles; we won't be using them.
1386 if (!profile_guided || (pkgname[0] == '*')) {
1387 return Dex2oatFileWrapper();
1388 }
1389
1390 // If this is a secondary dex path which is public do not open the profile.
1391 // We cannot compile public secondary dex paths with profiles. That's because
1392 // it will expose how the dex files are used by their owner.
1393 //
1394 // Note that the PackageManager is responsible to set the is_public flag for
1395 // primary apks and we do not check it here. In some cases, e.g. when
1396 // compiling with a public profile from the .dm file the PackageManager will
1397 // set is_public toghether with the profile guided compilation.
1398 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001399 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001400 }
Calin Juravle114f0812017-03-08 19:05:07 -08001401
1402 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001403 std::string location;
1404 if (is_secondary_dex) {
1405 location = dex_path;
1406 } else {
1407 if (profile_name == nullptr) {
1408 // This path is taken for system server re-compilation lunched from ZygoteInit.
1409 return Dex2oatFileWrapper();
1410 } else {
1411 location = profile_name;
1412 }
1413 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001414 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1415 is_secondary_dex);
1416 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1417 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001418 };
1419 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001420}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001421
Calin Juravle7a570e82017-01-14 16:23:30 -08001422// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1423// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001424bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001425 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001426 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001427 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1428 CHECK(in_vdex_wrapper_fd != nullptr);
1429 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001430 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1431 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001432 char in_odex_path[PKG_PATH_MAX];
1433 int dexopt_action = abs(dexopt_needed);
1434 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001435 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001436
1437 // Infer the name of the output VDEX.
1438 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1439 if (out_vdex_path_str.empty()) {
1440 return false;
1441 }
1442
1443 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001444 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001445 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1446 const char* path = nullptr;
1447 if (is_odex_location) {
1448 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1449 path = in_odex_path;
1450 } else {
1451 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001452 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001453 }
1454 } else {
1455 path = out_oat_path;
1456 }
1457 in_vdex_path_str = create_vdex_filename(path);
1458 if (in_vdex_path_str.empty()) {
1459 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001460 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001461 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001462 // We can update in place when all these conditions are met:
1463 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1464 // on /system typically cannot be updated in place).
1465 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1466 // cannot be currently used by a running process.
1467 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1468 // different vdex files to operate.
1469 update_vdex_in_place =
1470 (in_vdex_path_str == out_vdex_path_str) &&
1471 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1472 !profile_guided;
1473 if (update_vdex_in_place) {
1474 // Open the file read-write to be able to update it.
1475 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1476 if (in_vdex_wrapper_fd->get() == -1) {
1477 // If we failed to open the file, we cannot update it in place.
1478 update_vdex_in_place = false;
1479 }
1480 } else {
1481 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1482 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001483 }
1484
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001485 // If we are updating the vdex in place, we do not need to recreate a vdex,
1486 // and can use the same existing one.
1487 if (update_vdex_in_place) {
1488 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1489 // have bogus stale vdex files.
1490 out_vdex_wrapper_fd->reset(
1491 in_vdex_wrapper_fd->get(),
1492 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1493 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1494 // wrapper).
1495 in_vdex_wrapper_fd->DisableAutoClose();
1496 } else {
1497 out_vdex_wrapper_fd->reset(
1498 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1499 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1500 if (out_vdex_wrapper_fd->get() < 0) {
1501 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1502 return false;
1503 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001504 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001505 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001506 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001507 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1508 return false;
1509 }
1510
1511 // If we got here we successfully opened the vdex files.
1512 return true;
1513}
1514
1515// Opens the output oat file for the given apk.
1516// If successful it stores the output path into out_oat_path and returns true.
1517Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001518 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1519 char* out_oat_path) {
1520 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001521 return Dex2oatFileWrapper();
1522 }
1523 const std::string out_oat_path_str(out_oat_path);
1524 Dex2oatFileWrapper wrapper_fd(
1525 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1526 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1527 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001528 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001529 } else if (!set_permissions_and_ownership(
1530 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001531 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1532 wrapper_fd.reset(-1);
1533 }
1534 return wrapper_fd;
1535}
1536
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001537// Creates RDONLY fds for oat and vdex files, if exist.
1538// Returns false if it fails to create oat out path for the given apk path.
1539// Note that the method returns true even if the files could not be opened.
1540bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1541 const std::string& oat_dir,
1542 const std::string& instruction_set,
1543 bool is_secondary_dex,
1544 unique_fd* oat_file_fd,
1545 unique_fd* vdex_file_fd) {
1546 char oat_path[PKG_PATH_MAX];
1547 if (!create_oat_out_path(apk_path.c_str(),
1548 instruction_set.c_str(),
1549 oat_dir.c_str(),
1550 is_secondary_dex,
1551 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001552 LOG(ERROR) << "Could not create oat out path for "
1553 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001554 return false;
1555 }
1556 oat_file_fd->reset(open(oat_path, O_RDONLY));
1557 if (oat_file_fd->get() < 0) {
1558 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1559 }
1560
1561 std::string vdex_filename = create_vdex_filename(oat_path);
1562 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1563 if (vdex_file_fd->get() < 0) {
1564 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1565 }
1566
1567 return true;
1568}
1569
Calin Juravle7a570e82017-01-14 16:23:30 -08001570// Updates the access times of out_oat_path based on those from apk_path.
1571void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1572 struct stat input_stat;
1573 memset(&input_stat, 0, sizeof(input_stat));
1574 if (stat(apk_path, &input_stat) != 0) {
1575 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1576 return;
1577 }
1578
1579 struct utimbuf ut;
1580 ut.actime = input_stat.st_atime;
1581 ut.modtime = input_stat.st_mtime;
1582 if (utime(out_oat_path, &ut) != 0) {
1583 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1584 }
1585}
1586
Calin Juravle80a21252017-01-17 14:43:25 -08001587// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001588// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1589// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1590// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001591class RunDexoptAnalyzer : public ExecVHelper {
1592 public:
1593 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001594 int vdex_fd,
1595 int oat_fd,
1596 int zip_fd,
1597 const std::string& instruction_set,
1598 const std::string& compiler_filter,
1599 bool profile_was_updated,
1600 bool downgrade,
1601 const char* class_loader_context,
1602 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001603 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001604
1605 // We always run the analyzer in the background job.
1606 const char* dexoptanalyzer_bin = select_execution_binary(
1607 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001608
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001609 std::string dex_file_arg = "--dex-file=" + dex_file;
1610 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1611 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1612 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1613 std::string isa_arg = "--isa=" + instruction_set;
1614 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1615 const char* assume_profile_changed = "--assume-profile-changed";
1616 const char* downgrade_flag = "--downgrade";
1617 std::string class_loader_context_arg = "--class-loader-context=";
1618 if (class_loader_context != nullptr) {
1619 class_loader_context_arg += class_loader_context;
1620 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001621 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1622 if (!class_loader_context_fds.empty()) {
1623 class_loader_context_fds_arg += class_loader_context_fds;
1624 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001625
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001626 // program name, dex file, isa, filter
1627 AddArg(dex_file_arg);
1628 AddArg(isa_arg);
1629 AddArg(compiler_filter_arg);
1630 if (oat_fd >= 0) {
1631 AddArg(oat_fd_arg);
1632 }
1633 if (vdex_fd >= 0) {
1634 AddArg(vdex_fd_arg);
1635 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001636 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001637 if (profile_was_updated) {
1638 AddArg(assume_profile_changed);
1639 }
1640 if (downgrade) {
1641 AddArg(downgrade_flag);
1642 }
1643 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001644 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001645 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001646 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001647 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001648 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001649
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001650 PrepareArgs(dexoptanalyzer_bin);
1651 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001652
1653 // Dexoptanalyzer mode which flattens the given class loader context and
1654 // prints a list of its dex files in that flattened order.
1655 RunDexoptAnalyzer(const char* class_loader_context) {
1656 CHECK(class_loader_context != nullptr);
1657
1658 // We always run the analyzer in the background job.
1659 const char* dexoptanalyzer_bin = select_execution_binary(
1660 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1661
1662 AddArg("--flatten-class-loader-context");
1663 AddArg(std::string("--class-loader-context=") + class_loader_context);
1664 PrepareArgs(dexoptanalyzer_bin);
1665 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001666};
Calin Juravle80a21252017-01-17 14:43:25 -08001667
1668// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001669static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001670 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001671 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001672 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001673 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001674 return false;
1675 }
Calin Juravle114f0812017-03-08 19:05:07 -08001676 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001677
Calin Juravle80a21252017-01-17 14:43:25 -08001678 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001679 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1680 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001681 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001682 return false;
1683 }
1684
1685 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001686 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001687
Calin Juravle7d765462017-09-04 15:57:10 -07001688 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001689 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001690 return false;
1691 }
1692
1693 return true;
1694}
1695
Calin Juravle7d765462017-09-04 15:57:10 -07001696// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1697// secondary dex files. This return codes are returned by the child process created for
1698// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001699
Andreas Gampe194fe422018-02-28 20:16:19 -08001700enum DexoptAnalyzerSkipCodes {
1701 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001702 // Specific errors are encoded in the name.
1703 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1704 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1705 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1706 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1707 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001708 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001709 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001710};
Calin Juravle7d765462017-09-04 15:57:10 -07001711
1712// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001713// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1714// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001715// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1716// of dexoptanalyzer.
1717static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001718 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001719 // The result values are defined in dexoptanalyzer.
1720 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001721 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001722 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001723 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001724 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001725 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001726 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001727 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001728 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001729 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1730 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001731 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1732 " Expected odex file status for secondary dex %s"
1733 " : dexoptanalyzer result=%d",
1734 dex_path.c_str(),
1735 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001736 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001737 }
1738
1739 // Use a second switch for enum switch-case analysis.
1740 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001741 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001742 // If the file does not exist there's no need for dexopt.
1743 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1744 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001745
1746 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1747 *error_msg = "Dexoptanalyzer path validation failed";
1748 return false;
1749 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1750 *error_msg = "Dexoptanalyzer open zip failed";
1751 return false;
1752 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1753 *error_msg = "Dexoptanalyzer dir preparation failed";
1754 return false;
1755 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1756 *error_msg = "Dexoptanalyzer open output failed";
1757 return false;
1758 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1759 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001760 return false;
1761 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001762
1763 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1764 dex_path.c_str(),
1765 result);
1766 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001767}
1768
Calin Juravle7d765462017-09-04 15:57:10 -07001769enum SecondaryDexAccess {
1770 kSecondaryDexAccessReadOk = 0,
1771 kSecondaryDexAccessDoesNotExist = 1,
1772 kSecondaryDexAccessPermissionError = 2,
1773 kSecondaryDexAccessIOError = 3
1774};
1775
1776static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1777 // Check if the path exists and can be read. If not, there's nothing to do.
1778 if (access(dex_path.c_str(), R_OK) == 0) {
1779 return kSecondaryDexAccessReadOk;
1780 } else {
1781 if (errno == ENOENT) {
1782 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1783 return kSecondaryDexAccessDoesNotExist;
1784 } else {
1785 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1786 return errno == EACCES
1787 ? kSecondaryDexAccessPermissionError
1788 : kSecondaryDexAccessIOError;
1789 }
1790 }
1791}
1792
1793static bool is_file_public(const std::string& filename) {
1794 struct stat file_stat;
1795 if (stat(filename.c_str(), &file_stat) == 0) {
1796 return (file_stat.st_mode & S_IROTH) != 0;
1797 }
1798 return false;
1799}
1800
1801// Create the oat file structure for the secondary dex 'dex_path' and assign
1802// the individual path component to the 'out_' parameters.
1803static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001804 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001805 size_t dirIndex = dex_path.rfind('/');
1806 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001807 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001808 return false;
1809 }
1810 // TODO(calin): we have similar computations in at lest 3 other places
1811 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1812 // using string append.
1813 std::string apk_dir = dex_path.substr(0, dirIndex);
1814 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1815 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1816
1817 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1818 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001819 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001820 return false;
1821 }
1822 return true;
1823}
1824
1825// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1826// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001827static bool validate_dexopt_storage_flags(int dexopt_flags,
1828 int* out_storage_flag,
1829 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001830 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1831 *out_storage_flag = FLAG_STORAGE_CE;
1832 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001833 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001834 return false;
1835 }
1836 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1837 *out_storage_flag = FLAG_STORAGE_DE;
1838 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001839 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001840 return false;
1841 }
1842 return true;
1843}
1844
David Brazdil4f6027a2019-03-19 11:44:21 +00001845static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1846 /* out */ std::vector<std::string>* context_dex_paths) {
1847 if (class_loader_context == nullptr) {
1848 return true;
1849 }
1850
1851 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1852
1853 // Pipe to get the hash result back from our child process.
1854 unique_fd pipe_read, pipe_write;
1855 if (!Pipe(&pipe_read, &pipe_write)) {
1856 PLOG(ERROR) << "Failed to create pipe";
1857 return false;
1858 }
1859
1860 pid_t pid = fork();
1861 if (pid == 0) {
1862 // child -- drop privileges before continuing.
1863 drop_capabilities(uid);
1864
1865 // Route stdout to `pipe_write`
1866 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1867 pipe_write.reset();
1868 pipe_read.reset();
1869
1870 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1871 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1872 }
1873
1874 /* parent */
1875 pipe_write.reset();
1876
1877 std::string str_dex_paths;
1878 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1879 PLOG(ERROR) << "Failed to read from pipe";
1880 return false;
1881 }
1882 pipe_read.reset();
1883
1884 int return_code = wait_child(pid);
1885 if (!WIFEXITED(return_code)) {
1886 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1887 return false;
1888 }
1889
1890 constexpr int kFlattenClassLoaderContextSuccess = 50;
1891 return_code = WEXITSTATUS(return_code);
1892 if (return_code != kFlattenClassLoaderContextSuccess) {
1893 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1894 return false;
1895 }
1896
1897 if (!str_dex_paths.empty()) {
1898 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1899 }
1900 return true;
1901}
1902
1903static int open_dex_paths(const std::vector<std::string>& dex_paths,
1904 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1905 for (const std::string& dex_path : dex_paths) {
1906 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1907 if (zip_fds->back().get() < 0) {
1908 *error_msg = StringPrintf(
1909 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1910 if (errno == ENOENT) {
1911 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1912 } else {
1913 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1914 }
1915 }
1916 }
1917 return 0;
1918}
1919
1920static std::string join_fds(const std::vector<unique_fd>& fds) {
1921 std::stringstream ss;
1922 bool is_first = true;
1923 for (const unique_fd& fd : fds) {
1924 if (is_first) {
1925 is_first = false;
1926 } else {
1927 ss << ":";
1928 }
1929 ss << fd.get();
1930 }
1931 return ss.str();
1932}
1933
Calin Juravlec9eab382017-01-25 01:17:17 -08001934// 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 -08001935// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1936// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001937// When returning true, the output parameters will be:
1938// - is_public_out: whether or not the oat file should not be made public
1939// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1940// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001941static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001942 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001943 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001944 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001945 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001946 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001947 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001948 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1949 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001950 return false;
1951 }
Calin Juravle7d765462017-09-04 15:57:10 -07001952 // Compute the oat dir as it's not easy to extract it from the child computation.
1953 char oat_path[PKG_PATH_MAX];
1954 char oat_dir[PKG_PATH_MAX];
1955 char oat_isa_dir[PKG_PATH_MAX];
1956 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001957 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1958 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001959 return false;
1960 }
Calin Juravle7d765462017-09-04 15:57:10 -07001961 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001962
Calin Juravle80a21252017-01-17 14:43:25 -08001963 pid_t pid = fork();
1964 if (pid == 0) {
1965 // child -- drop privileges before continuing.
1966 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001967
1968 // Validate the path structure.
1969 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1970 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001971 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001972 }
1973
1974 // Open the dex file.
1975 unique_fd zip_fd;
1976 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1977 if (zip_fd.get() < 0) {
1978 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001979 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001980 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001981 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001982 }
1983 }
1984
David Brazdil4f6027a2019-03-19 11:44:21 +00001985 // Open class loader context dex files.
1986 std::vector<unique_fd> context_zip_fds;
1987 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1988 if (open_dex_paths_rc != 0) {
1989 _exit(open_dex_paths_rc);
1990 }
1991
Calin Juravle7d765462017-09-04 15:57:10 -07001992 // Prepare the oat directories.
1993 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001994 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001995 }
1996
1997 // Open the vdex/oat files if any.
1998 unique_fd oat_file_fd;
1999 unique_fd vdex_file_fd;
2000 if (!maybe_open_oat_and_vdex_file(dex_path,
2001 *oat_dir_out,
2002 instruction_set,
2003 true /* is_secondary_dex */,
2004 &oat_file_fd,
2005 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002006 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07002007 }
2008
2009 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08002010 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
2011 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07002012
2013 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002014 // Note that we do not do it before the fork since opening the files is required to happen
2015 // after forking.
2016 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
2017 vdex_file_fd.get(),
2018 oat_file_fd.get(),
2019 zip_fd.get(),
2020 instruction_set,
2021 compiler_filter, profile_was_updated,
2022 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00002023 class_loader_context,
2024 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002025 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08002026 }
2027
2028 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08002029 int result = wait_child(pid);
2030 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002031 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2032 dex_path.c_str(),
2033 result);
2034 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002035 return false;
2036 }
2037 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002038 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002039 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2040 result,
2041 dexopt_needed_out,
2042 error_msg);
2043 if (!success) {
2044 LOG(ERROR) << *error_msg;
2045 }
Calin Juravle7d765462017-09-04 15:57:10 -07002046
2047 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2048
Calin Juravle80a21252017-01-17 14:43:25 -08002049 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002050 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2051 // makes the code simpler; force compilation is only needed during tests).
2052 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002053 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002054 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002055 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2056 }
2057
Calin Juravle7d765462017-09-04 15:57:10 -07002058 // Check if we should make the oat file public.
2059 // Note that if the dex file is not public the compiled code cannot be made public.
2060 // It is ok to check this flag outside in the parent process.
2061 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2062
Calin Juravle80a21252017-01-17 14:43:25 -08002063 return success;
2064}
2065
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002066static std::string format_dexopt_error(int status, const char* dex_path) {
2067 if (WIFEXITED(status)) {
2068 int int_code = WEXITSTATUS(status);
2069 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2070 if (code_name != nullptr) {
2071 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2072 }
2073 }
2074 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002075}
2076
Calin Juravlec9eab382017-01-25 01:17:17 -08002077int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002078 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002079 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002080 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002081 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002082 CHECK(pkgname != nullptr);
2083 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002084 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002085 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2086 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002087
Calin Juravled23dee72017-07-06 16:29:11 -07002088 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002089 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002090 return -1;
2091 }
2092
2093 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002094 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2095 class_loader_context);
2096 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002097 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002098 }
2099
Calin Juravleebc8a792017-04-04 20:21:05 -07002100 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002101 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2102 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2103 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002104 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002105 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002106 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002107 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002108 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002109 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002110
2111 // Check if we're dealing with a secondary dex file and if we need to compile it.
2112 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002113 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002114 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002115 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2116 *error_msg = "Failed acquiring context dex paths";
2117 return -1; // We had an error, logged in the process method.
2118 }
2119
Calin Juravlec9eab382017-01-25 01:17:17 -08002120 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002121 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002122 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002123 oat_dir = oat_dir_str.c_str();
2124 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2125 return 0; // Nothing to do, report success.
2126 }
2127 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002128 if (error_msg->empty()) { // TODO: Make this a CHECK.
2129 *error_msg = "Failed processing secondary.";
2130 }
Calin Juravle80a21252017-01-17 14:43:25 -08002131 return -1; // We had an error, logged in the process method.
2132 }
2133 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002134 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002135 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002136 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2137 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2138 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002139
2140 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002141 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002142 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002143 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2144 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002145 return -1;
2146 }
2147
David Brazdil4f6027a2019-03-19 11:44:21 +00002148 // Open class loader context dex files.
2149 std::vector<unique_fd> context_input_fds;
2150 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2151 LOG(ERROR) << *error_msg;
2152 return -1;
2153 }
2154
Calin Juravle7a570e82017-01-14 16:23:30 -08002155 // Create the output OAT file.
2156 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002157 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002158 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002159 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002160 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002161 return -1;
2162 }
2163
2164 // Open vdex files.
2165 Dex2oatFileWrapper in_vdex_fd;
2166 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002167 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2168 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002169 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002170 return -1;
2171 }
2172
Calin Juravlecb556e32017-04-04 20:22:50 -07002173 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2174 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2175 // fully inherit their parent context).
2176 // Note that for primary apk the oat files are created before, in a separate installd
2177 // call which also does the restorecon. TODO(calin): unify the paths.
2178 if (is_secondary_dex) {
2179 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2180 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002181 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2182 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002183 return -1;
2184 }
2185 }
2186
Jeff Sharkey90aff262016-12-12 14:28:24 -07002187 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002188 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002189
Calin Juravle7a570e82017-01-14 16:23:30 -08002190 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002191 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002192 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002193
liulvping61907742018-08-21 09:36:52 +08002194 if (reference_profile_fd.get() == -1) {
2195 // We don't create an app image without reference profile since there is no speedup from
2196 // loading it in that case and instead will be a small overhead.
2197 generate_app_image = false;
2198 }
2199
2200 // Create the app image file if needed.
2201 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2202 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2203
Calin Juravle62c5a372018-02-01 17:03:23 +00002204 unique_fd dex_metadata_fd;
2205 if (dex_metadata_path != nullptr) {
2206 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2207 if (dex_metadata_fd.get() < 0) {
2208 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2209 }
2210 }
2211
Andreas Gampe023b2242018-02-28 16:03:25 -08002212 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002213
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002214 RunDex2Oat runner(input_fd.get(),
2215 out_oat_fd.get(),
2216 in_vdex_fd.get(),
2217 out_vdex_fd.get(),
2218 image_fd.get(),
2219 dex_path,
2220 out_oat_path,
2221 swap_fd.get(),
2222 instruction_set,
2223 compiler_filter,
2224 debuggable,
2225 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002226 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002227 background_job_compile,
2228 reference_profile_fd.get(),
2229 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002230 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002231 target_sdk_version,
2232 enable_hidden_api_checks,
2233 generate_compact_dex,
2234 dex_metadata_fd.get(),
2235 compilation_reason);
2236
Jeff Sharkey90aff262016-12-12 14:28:24 -07002237 pid_t pid = fork();
2238 if (pid == 0) {
2239 /* child -- drop privileges before continuing */
2240 drop_capabilities(uid);
2241
Richard Uhler76cc0272016-12-08 10:46:35 +00002242 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002243 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002244 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002245 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002246 }
2247
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002248 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002249 } else {
2250 int res = wait_child(pid);
2251 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002252 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002253 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002254 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2255 << std::hex << std::setw(4) << res << ", process failed";
2256 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002257 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002258 }
2259 }
2260
Calin Juravlec9eab382017-01-25 01:17:17 -08002261 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002262
2263 // We've been successful, don't delete output.
2264 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002265 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002266 image_fd.SetCleanup(false);
2267 reference_profile_fd.SetCleanup(false);
2268
2269 return 0;
2270}
2271
Calin Juravlec9eab382017-01-25 01:17:17 -08002272// Try to remove the given directory. Log an error if the directory exists
2273// and is empty but could not be removed.
2274static bool rmdir_if_empty(const char* dir) {
2275 if (rmdir(dir) == 0) {
2276 return true;
2277 }
2278 if (errno == ENOENT || errno == ENOTEMPTY) {
2279 return true;
2280 }
2281 PLOG(ERROR) << "Failed to remove dir: " << dir;
2282 return false;
2283}
2284
2285// Try to unlink the given file. Log an error if the file exists and could not
2286// be unlinked.
2287static bool unlink_if_exists(const std::string& file) {
2288 if (unlink(file.c_str()) == 0) {
2289 return true;
2290 }
2291 if (errno == ENOENT) {
2292 return true;
2293
2294 }
2295 PLOG(ERROR) << "Could not unlink: " << file;
2296 return false;
2297}
2298
Calin Juravle7d765462017-09-04 15:57:10 -07002299enum ReconcileSecondaryDexResult {
2300 kReconcileSecondaryDexExists = 0,
2301 kReconcileSecondaryDexCleanedUp = 1,
2302 kReconcileSecondaryDexValidationError = 2,
2303 kReconcileSecondaryDexCleanUpError = 3,
2304 kReconcileSecondaryDexAccessIOError = 4,
2305};
Calin Juravlec9eab382017-01-25 01:17:17 -08002306
2307// Reconcile the secondary dex 'dex_path' and its generated oat files.
2308// Return true if all the parameters are valid and the secondary dex file was
2309// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2310// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2311// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2312// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2313// Return false if there were errors during processing. In this case
2314// out_secondary_dex_exists will be set to false.
2315bool reconcile_secondary_dex_file(const std::string& dex_path,
2316 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002317 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002318 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002319 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002320 if (isas.size() == 0) {
2321 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2322 return false;
2323 }
2324
Calin Juravle7d765462017-09-04 15:57:10 -07002325 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2326 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2327 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002328 return false;
2329 }
2330
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002331 // As a security measure we want to unlink art artifacts with the reduced capabilities
2332 // of the package user id. So we fork and drop capabilities in the child.
2333 pid_t pid = fork();
2334 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002335 /* child -- drop privileges before continuing */
2336 drop_capabilities(uid);
2337
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002338 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002339 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002340 uid, storage_flag)) {
2341 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2342 _exit(kReconcileSecondaryDexValidationError);
2343 }
2344
2345 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2346 switch (access_check) {
2347 case kSecondaryDexAccessDoesNotExist:
2348 // File does not exist. Proceed with cleaning.
2349 break;
2350 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2351 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2352 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2353 default:
2354 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2355 _exit(kReconcileSecondaryDexValidationError);
2356 }
2357
2358 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002359 char oat_path[PKG_PATH_MAX];
2360 char oat_dir[PKG_PATH_MAX];
2361 char oat_isa_dir[PKG_PATH_MAX];
2362 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002363 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002364 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002365 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002366 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2367 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002368 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002369 }
Calin Juravle51314092017-05-18 15:33:05 -07002370
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002371 // Delete oat/vdex/art files.
2372 result = unlink_if_exists(oat_path) && result;
2373 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2374 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002375
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002376 // Delete profiles.
2377 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002378 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002379 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002380 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002381 result = unlink_if_exists(current_profile) && result;
2382 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002383
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002384 // We upgraded once the location of current profile for secondary dex files.
2385 // Check for any previous left-overs and remove them as well.
2386 std::string old_current_profile = dex_path + ".prof";
2387 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002388
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002389 // Try removing the directories as well, they might be empty.
2390 result = rmdir_if_empty(oat_isa_dir) && result;
2391 result = rmdir_if_empty(oat_dir) && result;
2392 }
Calin Juravle7d765462017-09-04 15:57:10 -07002393 if (!result) {
2394 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2395 }
2396 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002397 }
2398
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002399 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002400 if (!WIFEXITED(return_code)) {
2401 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2402 } else {
2403 return_code = WEXITSTATUS(return_code);
2404 }
2405
2406 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2407
2408 switch (return_code) {
2409 case kReconcileSecondaryDexCleanedUp:
2410 case kReconcileSecondaryDexValidationError:
2411 // If we couldn't validate assume the dex file does not exist.
2412 // This will purge the entry from the PM records.
2413 *out_secondary_dex_exists = false;
2414 return true;
2415 case kReconcileSecondaryDexExists:
2416 *out_secondary_dex_exists = true;
2417 return true;
2418 case kReconcileSecondaryDexAccessIOError:
2419 // We had an access IO error.
2420 // Return false so that we can try again.
2421 // The value of out_secondary_dex_exists does not matter in this case and by convention
2422 // is set to false.
2423 *out_secondary_dex_exists = false;
2424 return false;
2425 default:
2426 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2427 *out_secondary_dex_exists = false;
2428 return false;
2429 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002430}
2431
Alan Stokesa25d90c2017-10-16 10:56:00 +01002432// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2433// Returns true if all parameters are valid and the hash successfully computed and stored in
2434// out_secondary_dex_hash.
2435// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2436// the app.
2437// For any other errors (e.g. if any of the parameters are invalid) returns false.
2438bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002439 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002440 std::vector<uint8_t>* out_secondary_dex_hash) {
2441 out_secondary_dex_hash->clear();
2442
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002443 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002444
2445 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2446 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2447 << storage_flag;
2448 return false;
2449 }
2450
2451 // Pipe to get the hash result back from our child process.
2452 unique_fd pipe_read, pipe_write;
2453 if (!Pipe(&pipe_read, &pipe_write)) {
2454 PLOG(ERROR) << "Failed to create pipe";
2455 return false;
2456 }
2457
2458 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2459 // access data the app itself can access.
2460 pid_t pid = fork();
2461 if (pid == 0) {
2462 // child -- drop privileges before continuing
2463 drop_capabilities(uid);
2464 pipe_read.reset();
2465
2466 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2467 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002468 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002469 }
2470
2471 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2472 if (fd == -1) {
2473 if (errno == EACCES || errno == ENOENT) {
2474 // Not treated as an error.
2475 _exit(0);
2476 }
2477 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002478 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002479 }
2480
2481 SHA256_CTX ctx;
2482 SHA256_Init(&ctx);
2483
2484 std::vector<uint8_t> buffer(65536);
2485 while (true) {
2486 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2487 if (bytes_read == 0) {
2488 break;
2489 } else if (bytes_read == -1) {
2490 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002491 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002492 }
2493
2494 SHA256_Update(&ctx, buffer.data(), bytes_read);
2495 }
2496
2497 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2498 SHA256_Final(hash.data(), &ctx);
2499 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002500 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002501 }
2502
2503 _exit(0);
2504 }
2505
2506 // parent
2507 pipe_write.reset();
2508
2509 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2510 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2511 out_secondary_dex_hash->clear();
2512 }
2513 return wait_child(pid) == 0;
2514}
2515
Jeff Sharkey90aff262016-12-12 14:28:24 -07002516// Helper for move_ab, so that we can have common failure-case cleanup.
2517static bool unlink_and_rename(const char* from, const char* to) {
2518 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2519 // return a failure.
2520 struct stat s;
2521 if (stat(to, &s) == 0) {
2522 if (!S_ISREG(s.st_mode)) {
2523 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2524 return false;
2525 }
2526 if (unlink(to) != 0) {
2527 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2528 return false;
2529 }
2530 } else {
2531 // This may be a permission problem. We could investigate the error code, but we'll just
2532 // let the rename failure do the work for us.
2533 }
2534
2535 // Try to rename "to" to "from."
2536 if (rename(from, to) != 0) {
2537 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2538 return false;
2539 }
2540 return true;
2541}
2542
2543// Move/rename a B artifact (from) to an A artifact (to).
2544static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2545 // Check whether B exists.
2546 {
2547 struct stat s;
2548 if (stat(b_path.c_str(), &s) != 0) {
2549 // Silently ignore for now. The service calling this isn't smart enough to understand
2550 // lack of artifacts at the moment.
2551 return false;
2552 }
2553 if (!S_ISREG(s.st_mode)) {
2554 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2555 // Try to unlink, but swallow errors.
2556 unlink(b_path.c_str());
2557 return false;
2558 }
2559 }
2560
2561 // Rename B to A.
2562 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2563 // Delete the b_path so we don't try again (or fail earlier).
2564 if (unlink(b_path.c_str()) != 0) {
2565 PLOG(ERROR) << "Could not unlink " << b_path;
2566 }
2567
2568 return false;
2569 }
2570
2571 return true;
2572}
2573
2574bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2575 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002576 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2577 if (slot_suffix.empty()) {
2578 return false;
2579 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002580
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002581 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2582 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2583 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002584 }
2585
2586 // Validate other inputs.
2587 if (validate_apk_path(apk_path) != 0) {
2588 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2589 return false;
2590 }
2591 if (validate_apk_path(oat_dir) != 0) {
2592 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2593 return false;
2594 }
2595
2596 char a_path[PKG_PATH_MAX];
2597 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2598 return false;
2599 }
2600 const std::string a_vdex_path = create_vdex_filename(a_path);
2601 const std::string a_image_path = create_image_filename(a_path);
2602
2603 // B path = A path + slot suffix.
2604 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2605 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2606 const std::string b_image_path = StringPrintf("%s.%s",
2607 a_image_path.c_str(),
2608 slot_suffix.c_str());
2609
2610 bool success = true;
2611 if (move_ab_path(b_path, a_path)) {
2612 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2613 // Note: we can live without an app image. As such, ignore failure to move the image file.
2614 // If we decide to require the app image, or the app image being moved correctly,
2615 // then change accordingly.
2616 constexpr bool kIgnoreAppImageFailure = true;
2617
2618 if (!a_image_path.empty()) {
2619 if (!move_ab_path(b_image_path, a_image_path)) {
2620 unlink(a_image_path.c_str());
2621 if (!kIgnoreAppImageFailure) {
2622 success = false;
2623 }
2624 }
2625 }
2626 } else {
2627 // Cleanup: delete B image, ignore errors.
2628 unlink(b_image_path.c_str());
2629 success = false;
2630 }
2631 } else {
2632 // Cleanup: delete B image, ignore errors.
2633 unlink(b_vdex_path.c_str());
2634 unlink(b_image_path.c_str());
2635 success = false;
2636 }
2637 return success;
2638}
2639
2640bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2641 // Delete the oat/odex file.
2642 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002643 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002644 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002645 return false;
2646 }
2647
2648 // In case of a permission failure report the issue. Otherwise just print a warning.
2649 auto unlink_and_check = [](const char* path) -> bool {
2650 int result = unlink(path);
2651 if (result != 0) {
2652 if (errno == EACCES || errno == EPERM) {
2653 PLOG(ERROR) << "Could not unlink " << path;
2654 return false;
2655 }
2656 PLOG(WARNING) << "Could not unlink " << path;
2657 }
2658 return true;
2659 };
2660
2661 // Delete the oat/odex file.
2662 bool return_value_oat = unlink_and_check(out_path);
2663
2664 // Derive and delete the app image.
2665 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2666
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002667 // Derive and delete the vdex file.
2668 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2669
Jeff Sharkey90aff262016-12-12 14:28:24 -07002670 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002671 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002672}
2673
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002674static bool is_absolute_path(const std::string& path) {
2675 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2676 LOG(ERROR) << "Invalid absolute path " << path;
2677 return false;
2678 } else {
2679 return true;
2680 }
2681}
2682
2683static bool is_valid_instruction_set(const std::string& instruction_set) {
2684 // TODO: add explicit whitelisting of instruction sets
2685 if (instruction_set.find('/') != std::string::npos) {
2686 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2687 return false;
2688 } else {
2689 return true;
2690 }
2691}
2692
2693bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2694 const char *apk_path, const char *instruction_set) {
2695 std::string oat_dir_ = oat_dir;
2696 std::string apk_path_ = apk_path;
2697 std::string instruction_set_ = instruction_set;
2698
2699 if (!is_absolute_path(oat_dir_)) return false;
2700 if (!is_absolute_path(apk_path_)) return false;
2701 if (!is_valid_instruction_set(instruction_set_)) return false;
2702
2703 std::string::size_type end = apk_path_.rfind('.');
2704 std::string::size_type start = apk_path_.rfind('/', end);
2705 if (end == std::string::npos || start == std::string::npos) {
2706 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2707 return false;
2708 }
2709
2710 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2711 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2712 const char* res = res_.c_str();
2713 if (strlen(res) >= PKG_PATH_MAX) {
2714 LOG(ERROR) << "Result too large";
2715 return false;
2716 } else {
2717 strlcpy(path, res, PKG_PATH_MAX);
2718 return true;
2719 }
2720}
2721
2722bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2723 const char *instruction_set) {
2724 std::string apk_path_ = apk_path;
2725 std::string instruction_set_ = instruction_set;
2726
2727 if (!is_absolute_path(apk_path_)) return false;
2728 if (!is_valid_instruction_set(instruction_set_)) return false;
2729
2730 std::string::size_type end = apk_path_.rfind('.');
2731 std::string::size_type start = apk_path_.rfind('/', end);
2732 if (end == std::string::npos || start == std::string::npos) {
2733 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2734 return false;
2735 }
2736
2737 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2738 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2739}
2740
2741bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2742 const char *instruction_set) {
2743 std::string src_ = src;
2744 std::string instruction_set_ = instruction_set;
2745
2746 if (!is_absolute_path(src_)) return false;
2747 if (!is_valid_instruction_set(instruction_set_)) return false;
2748
2749 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2750 if (*it == '/') {
2751 *it = '@';
2752 }
2753 }
2754
2755 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2756 + DALVIK_CACHE_POSTFIX;
2757 const char* res = res_.c_str();
2758 if (strlen(res) >= PKG_PATH_MAX) {
2759 LOG(ERROR) << "Result too large";
2760 return false;
2761 } else {
2762 strlcpy(path, res, PKG_PATH_MAX);
2763 return true;
2764 }
2765}
2766
Calin Juravle59f7ab82018-04-27 17:50:23 -07002767bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2768 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002769 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2770 for (const std::string& elem : classpaths_elems) {
2771 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2772 if (fd < 0) {
2773 PLOG(ERROR) << "Could not open classpath elem " << elem;
2774 return false;
2775 } else {
2776 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002777 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002778 }
2779 }
2780 return true;
2781}
2782
2783static bool create_app_profile_snapshot(int32_t app_id,
2784 const std::string& package_name,
2785 const std::string& profile_name,
2786 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002787 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2788
Calin Juravle824a64d2018-01-18 20:23:17 -08002789 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002790 if (snapshot_fd < 0) {
2791 return false;
2792 }
2793
2794 std::vector<unique_fd> profiles_fd;
2795 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002796 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2797 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002798 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2799 return false;
2800 }
2801
2802 profiles_fd.push_back(std::move(reference_profile_fd));
2803
Calin Juravle0d0a4922018-01-23 19:54:11 -08002804 // Open the class paths elements. These will be used to filter out profile data that does
2805 // not belong to the classpath during merge.
2806 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002807 std::vector<std::string> dex_locations;
2808 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002809 return false;
2810 }
2811
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002812 RunProfman args;
Calin Juravle78728f32019-11-08 17:55:46 -08002813 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations, /*for_snapshot=*/true);
Calin Juravle29591732017-11-20 17:46:19 -08002814 pid_t pid = fork();
2815 if (pid == 0) {
2816 /* child -- drop privileges before continuing */
2817 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002818 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002819 }
2820
2821 /* parent */
2822 int return_code = wait_child(pid);
2823 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002824 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002825 return false;
2826 }
2827
Calin Juravle78728f32019-11-08 17:55:46 -08002828 // Verify that profman finished successfully.
2829 int profman_code = WEXITSTATUS(return_code);
2830 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2831 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2832 << ":" << profman_code;
2833 return false;
2834 }
Calin Juravle29591732017-11-20 17:46:19 -08002835 return true;
2836}
2837
Calin Juravle0d0a4922018-01-23 19:54:11 -08002838static bool create_boot_image_profile_snapshot(const std::string& package_name,
2839 const std::string& profile_name,
2840 const std::string& classpath) {
2841 // The reference profile directory for the android package might not be prepared. Do it now.
2842 const std::string ref_profile_dir =
2843 create_primary_reference_profile_package_dir_path(package_name);
2844 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2845 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2846 return false;
2847 }
2848
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002849 // Return false for empty class path since it may otherwise return true below if profiles is
2850 // empty.
2851 if (classpath.empty()) {
2852 PLOG(ERROR) << "Class path is empty";
2853 return false;
2854 }
2855
Calin Juravle0d0a4922018-01-23 19:54:11 -08002856 // Open and create the snapshot profile.
2857 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2858
2859 // Collect all non empty profiles.
2860 // The collection will traverse all applications profiles and find the non empty files.
2861 // This has the potential of inspecting a large number of files and directories (depending
2862 // on the number of applications and users). So there is a slight increase in the chance
2863 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2864 // fail the snapshot and aggregate whatever profile we could open.
2865 //
2866 // The profile snapshot is a best effort based on available data it's ok if some data
2867 // from some apps is missing. It will be counter productive for the snapshot to fail
2868 // because we could not open or read some of the files.
2869 std::vector<std::string> profiles;
2870 if (!collect_profiles(&profiles)) {
2871 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2872 }
2873
2874 // If we have no profiles return early.
2875 if (profiles.empty()) {
2876 return true;
2877 }
2878
2879 // Open the classpath elements. These will be used to filter out profile data that does
2880 // not belong to the classpath during merge.
2881 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002882 std::vector<std::string> dex_locations;
2883 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002884 return false;
2885 }
2886
2887 // If we could not open any files from the classpath return an error.
2888 if (apk_fds.empty()) {
2889 LOG(ERROR) << "Could not open any of the classpath elements.";
2890 return false;
2891 }
2892
2893 // Aggregate the profiles in batches of kAggregationBatchSize.
2894 // We do this to avoid opening a huge a amount of files.
2895 static constexpr size_t kAggregationBatchSize = 10;
2896
Calin Juravle0d0a4922018-01-23 19:54:11 -08002897 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002898 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002899 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2900 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2901 if (fd.get() >= 0) {
2902 profiles_fd.push_back(std::move(fd));
2903 }
2904 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002905
2906 // We aggregate (read & write) into the same fd multiple times in a row.
2907 // We need to reset the cursor every time to ensure we read the whole file every time.
2908 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2909 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2910 return false;
2911 }
2912
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002913 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002914 args.SetupMerge(profiles_fd,
2915 snapshot_fd,
2916 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002917 dex_locations,
2918 /*for_snapshot=*/true,
2919 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002920 pid_t pid = fork();
2921 if (pid == 0) {
2922 /* child -- drop privileges before continuing */
2923 drop_capabilities(AID_SYSTEM);
2924
Calin Juravle59f7ab82018-04-27 17:50:23 -07002925 // The introduction of new access flags into boot jars causes them to
2926 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002927 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002928 }
2929
2930 /* parent */
2931 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002932
Calin Juravle0d0a4922018-01-23 19:54:11 -08002933 if (!WIFEXITED(return_code)) {
2934 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2935 return false;
2936 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002937
2938 // Verify that profman finished successfully.
2939 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002940 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2941 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2942 << ":" << profman_code;
2943 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002944 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002945 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002946
Calin Juravle0d0a4922018-01-23 19:54:11 -08002947 return true;
2948}
2949
2950bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2951 const std::string& profile_name, const std::string& classpath) {
2952 if (app_id == -1) {
2953 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2954 } else {
2955 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2956 }
2957}
2958
Calin Juravlec3b049e2018-01-18 22:32:58 -08002959bool prepare_app_profile(const std::string& package_name,
2960 userid_t user_id,
2961 appid_t app_id,
2962 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002963 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002964 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002965 // Prepare the current profile.
2966 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2967 /*is_secondary_dex*/ false);
2968 uid_t uid = multiuser_get_uid(user_id, app_id);
2969 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2970 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2971 return false;
2972 }
2973
2974 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002975 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002976 return true;
2977 }
2978
2979 // We have a dex metdata. Merge the profile into the reference profile.
2980 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2981 /*read_write*/ true, /*is_secondary_dex*/ false);
2982 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2983 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002984 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2985 if (apk_fd < 0) {
2986 PLOG(ERROR) << "Could not open code path " << code_path;
2987 return false;
2988 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002989
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002990 RunProfman args;
2991 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2992 std::move(ref_profile_fd),
2993 std::move(apk_fd),
2994 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002995 pid_t pid = fork();
2996 if (pid == 0) {
2997 /* child -- drop privileges before continuing */
2998 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2999 drop_capabilities(app_shared_gid);
3000
Calin Juravlef63d4792018-01-30 17:43:34 +00003001 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003002 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08003003 }
3004
3005 /* parent */
3006 int return_code = wait_child(pid);
3007 if (!WIFEXITED(return_code)) {
3008 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
3009 return false;
3010 }
3011 return true;
3012}
3013
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003014} // namespace installd
3015} // namespace android