blob: 6bd41562e5d5c4c5c9ffb0ddfadfacdd90c1b778 [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
Calin Juravlef85ddb92020-05-01 14:05:40 -0700321static bool IsBootClassPathProfilingEnable() {
322 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
323 profile_boot_class_path =
324 server_configurable_flags::GetServerConfigurableFlag(
325 RUNTIME_NATIVE_BOOT_NAMESPACE,
326 PROFILE_BOOT_CLASS_PATH,
327 /*default_value=*/ profile_boot_class_path);
328 return profile_boot_class_path == "true";
329}
330
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800331class RunDex2Oat : public ExecVHelper {
332 public:
333 RunDex2Oat(int zip_fd,
334 int oat_fd,
335 int input_vdex_fd,
336 int output_vdex_fd,
337 int image_fd,
338 const char* input_file_name,
339 const char* output_file_name,
340 int swap_fd,
341 const char* instruction_set,
342 const char* compiler_filter,
343 bool debuggable,
344 bool post_bootcomplete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700345 bool for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800346 bool background_job_compile,
347 int profile_fd,
348 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000349 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800350 int target_sdk_version,
351 bool enable_hidden_api_checks,
352 bool generate_compact_dex,
353 int dex_metadata_fd,
Victor Hsieh8948a862020-08-07 11:30:55 -0700354 bool use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800355 const char* compilation_reason) {
356 // Get the relative path to the input file.
357 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700358
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800359 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
360 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700361
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700362 std::string threads_format = "-j%s";
363 std::string dex2oat_threads_arg = post_bootcomplete
364 ? (for_restore
365 ? MapPropertyToArgWithBackup(
366 "dalvik.vm.restore-dex2oat-threads",
367 "dalvik.vm.dex2oat-threads",
368 threads_format)
369 : MapPropertyToArg("dalvik.vm.dex2oat-threads", threads_format))
370 : MapPropertyToArg("dalvik.vm.boot-dex2oat-threads", threads_format);
371 std::string cpu_set_format = "--cpu-set=%s";
372 std::string dex2oat_cpu_set_arg = post_bootcomplete
373 ? (for_restore
374 ? MapPropertyToArgWithBackup(
375 "dalvik.vm.restore-dex2oat-cpu-set",
376 "dalvik.vm.dex2oat-cpu-set",
377 cpu_set_format)
378 : MapPropertyToArg("dalvik.vm.dex2oat-cpu-set", cpu_set_format))
379 : MapPropertyToArg("dalvik.vm.boot-dex2oat-cpu-set", cpu_set_format);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700380
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000381 std::string bootclasspath;
382 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
383 if (dex2oat_bootclasspath != nullptr) {
384 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
385 }
386 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
387 // BOOTCLASSPATH.
388
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800389 const std::string dex2oat_isa_features_key =
390 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
391 std::string instruction_set_features_arg =
392 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700393
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800394 const std::string dex2oat_isa_variant_key =
395 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
396 std::string instruction_set_variant_arg =
397 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700398
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800399 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700400
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800401 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
402 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
403 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700404
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800405 // If we are booting without the real /data, don't spend time compiling.
406 std::string vold_decrypt = GetProperty("vold.decrypt", "");
407 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
408 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700409
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100410 std::string updatable_bcp_packages =
411 MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
412 "--updatable-bcp-packages-file=%s");
413 if (updatable_bcp_packages.empty()) {
414 // Make dex2oat fail by providing non-existent file name.
415 updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
416 }
417
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800418 std::string resolve_startup_string_arg =
419 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
420 "--resolve-startup-const-strings=%s");
421 if (resolve_startup_string_arg.empty()) {
422 // If empty, fall back to system property.
423 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800424 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
425 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800426 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800427
428 const std::string image_block_size_arg =
429 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
430 "--max-image-block-size=%s");
431
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800432 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700433
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800434 std::string image_format_arg;
435 if (image_fd >= 0) {
436 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000437 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000438
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800439 std::string dex2oat_large_app_threshold_arg =
440 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000441
Calin Juravlef74a7372019-02-28 20:29:41 -0800442
David Sehr6df89a62020-04-15 20:43:48 -0700443
444 // Decide whether to use dex2oat64.
445 bool use_dex2oat64 = false;
446 // Check whether the device even supports 64-bit ABIs.
447 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
448 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
449 }
Calin Juravlef74a7372019-02-28 20:29:41 -0800450 const char* dex2oat_bin = select_execution_binary(
David Sehr6df89a62020-04-15 20:43:48 -0700451 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
452 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
453 background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000454
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800455 bool generate_minidebug_info = kEnableMinidebugInfo &&
456 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000457
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000458 std::string boot_image;
Victor Hsieh8948a862020-08-07 11:30:55 -0700459 if (use_jitzygote_image) {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000460 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000461 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000462 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000463 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000464
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800465 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
466 // use arraysize instead.
467 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
468 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
469 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
470 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
471 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
472 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
473 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
474 std::string dex2oat_compiler_filter_arg;
475 std::string dex2oat_swap_fd;
476 std::string dex2oat_image_fd;
477 std::string target_sdk_version_arg;
478 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000479 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800480 }
481 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000482 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800483 if (class_loader_context != nullptr) {
484 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
485 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000486 if (!class_loader_context_fds.empty()) {
487 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
488 class_loader_context_fds.c_str());
489 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800490 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000491
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800492 if (swap_fd >= 0) {
493 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
494 }
495 if (image_fd >= 0) {
496 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
497 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000498
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800499 // Compute compiler filter.
500 bool have_dex2oat_relocation_skip_flag = false;
501 if (skip_compilation) {
502 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
503 have_dex2oat_relocation_skip_flag = true;
504 } else if (compiler_filter != nullptr) {
505 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
506 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000507
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800508 if (dex2oat_compiler_filter_arg.empty()) {
509 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
510 "--compiler-filter=%s");
511 }
512
513 // Check whether all apps should be compiled debuggable.
514 if (!debuggable) {
515 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
516 }
517 std::string profile_arg;
518 if (profile_fd != -1) {
519 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
520 }
521
522 // Get the directory of the apk to pass as a base classpath directory.
523 std::string base_dir;
524 std::string apk_dir(input_file_name);
525 unsigned long dir_index = apk_dir.rfind('/');
526 bool has_base_dir = dir_index != std::string::npos;
527 if (has_base_dir) {
528 apk_dir = apk_dir.substr(0, dir_index);
529 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
530 }
531
532 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
533
534 std::string compilation_reason_arg = compilation_reason == nullptr
535 ? ""
536 : std::string("--compilation-reason=") + compilation_reason;
537
538 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
539
540 // Disable cdex if update input vdex is true since this combination of options is not
541 // supported.
542 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
543
544 AddArg(zip_fd_arg);
545 AddArg(zip_location_arg);
546 AddArg(input_vdex_fd_arg);
547 AddArg(output_vdex_fd_arg);
548 AddArg(oat_fd_arg);
549 AddArg(oat_location_arg);
550 AddArg(instruction_set_arg);
551
552 AddArg(instruction_set_variant_arg);
553 AddArg(instruction_set_features_arg);
554
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000555 AddArg(boot_image);
556
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000557 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800558 AddRuntimeArg(dex2oat_Xms_arg);
559 AddRuntimeArg(dex2oat_Xmx_arg);
560
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100561 AddArg(updatable_bcp_packages);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800562 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800563 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800564 AddArg(dex2oat_compiler_filter_arg);
565 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000566 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800567 AddArg(dex2oat_swap_fd);
568 AddArg(dex2oat_image_fd);
569
570 if (generate_debug_info) {
571 AddArg("--generate-debug-info");
572 }
573 if (debuggable) {
574 AddArg("--debuggable");
575 }
576 AddArg(image_format_arg);
577 AddArg(dex2oat_large_app_threshold_arg);
578
579 if (have_dex2oat_relocation_skip_flag) {
580 AddRuntimeArg(dex2oat_norelocation);
581 }
582 AddArg(profile_arg);
583 AddArg(base_dir);
584 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000585 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800586 if (generate_minidebug_info) {
587 AddArg(kMinidebugDex2oatFlag);
588 }
589 if (disable_cdex) {
590 AddArg(kDisableCompactDexFlag);
591 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000592 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800593 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100594 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800595 }
596
597 if (dex_metadata_fd > -1) {
598 AddArg(dex_metadata_fd_arg);
599 }
600
601 AddArg(compilation_reason_arg);
602
603 // Do not add args after dex2oat_flags, they should override others for debugging.
604 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
605
606 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000607 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800608};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700609
610/*
611 * Whether dexopt should use a swap file when compiling an APK.
612 *
613 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
614 * itself, anyways).
615 *
616 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
617 *
618 * Otherwise, return true if this is a low-mem device.
619 *
620 * Otherwise, return default value.
621 */
622static bool kAlwaysProvideSwapFile = false;
623static bool kDefaultProvideSwapFile = true;
624
625static bool ShouldUseSwapFileForDexopt() {
626 if (kAlwaysProvideSwapFile) {
627 return true;
628 }
629
630 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700631 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
632 if (!dex2oat_prop_buf.empty()) {
633 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700634 }
635
636 // Shortcut for default value. This is an implementation optimization for the process sketched
637 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
638 // as low-mem is never returning false. The compiler will optimize this away if it can.
639 if (kDefaultProvideSwapFile) {
640 return true;
641 }
642
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700643 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644 return true;
645 }
646
647 // Default value must be false here.
648 return kDefaultProvideSwapFile;
649}
650
Richard Uhler76cc0272016-12-08 10:46:35 +0000651static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700652 if (set_to_bg) {
653 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800654 PLOG(ERROR) << "set_sched_policy failed";
655 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 }
657 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800658 PLOG(ERROR) << "setpriority failed";
659 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700660 }
661 }
662}
663
Calin Juravle29591732017-11-20 17:46:19 -0800664static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
665 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800666 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800667 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800668 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800669 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800670 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700671 }
Calin Juravle114f0812017-03-08 19:05:07 -0800672 // Profiles should belong to the app; make sure of that by giving ownership to
673 // the app uid. If we cannot do that, there's no point in returning the fd
674 // since dex2oat/profman will fail with SElinux denials.
675 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000676 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800677 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800678 }
Calin Juravle29591732017-11-20 17:46:19 -0800679 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800680}
681
Calin Juravle29591732017-11-20 17:46:19 -0800682static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800683 // Do not follow symlinks when opening a profile:
684 // - primary profiles should not contain symlinks in their paths
685 // - secondary dex paths should have been already resolved and validated
686 flags |= O_NOFOLLOW;
687
Calin Juravle29591732017-11-20 17:46:19 -0800688 // Check if we need to create the profile
689 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
690 unique_fd fd;
691 if ((flags & O_CREAT) != 0) {
692 fd = create_profile(uid, profile, flags);
693 } else {
694 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
695 }
696
Calin Juravle114f0812017-03-08 19:05:07 -0800697 if (fd.get() < 0) {
698 if (errno != ENOENT) {
699 // Profiles might be missing for various reasons. For example, in a
700 // multi-user environment, the profile directory for one user can be created
701 // after we start a merge. In this case the current profile for that user
702 // will not be found.
703 // Also, the secondary dex profiles might be deleted by the app at any time,
704 // so we can't we need to prepare if they are missing.
705 PLOG(ERROR) << "Failed to open profile " << profile;
706 }
707 return invalid_unique_fd();
708 }
709
Jeff Sharkey90aff262016-12-12 14:28:24 -0700710 return fd;
711}
712
Calin Juravle824a64d2018-01-18 20:23:17 -0800713static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
714 const std::string& location, bool is_secondary_dex) {
715 std::string profile = create_current_profile_path(user, package_name, location,
716 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800717 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800718}
719
Calin Juravle824a64d2018-01-18 20:23:17 -0800720static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
721 const std::string& location, bool read_write, bool is_secondary_dex) {
722 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800723 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
724}
725
726static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800727 const std::string& location) {
728 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800729 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800730}
731
Calin Juravle824a64d2018-01-18 20:23:17 -0800732static void open_profile_files(uid_t uid, const std::string& package_name,
733 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800734 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800736 *reference_profile_fd = open_reference_profile(uid, package_name, location,
737 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700738
Calin Juravle114f0812017-03-08 19:05:07 -0800739 // For secondary dex files, we don't really need the user but we use it for sanity checks.
740 // Note: the user owning the dex file should be the current user.
741 std::vector<userid_t> users;
742 if (is_secondary_dex){
743 users.push_back(multiuser_get_user_id(uid));
744 } else {
745 users = get_known_users(/*volume_uuid*/ nullptr);
746 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800748 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
749 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800751 if (profile_fd.get() >= 0) {
752 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700753 }
754 }
755}
756
Calin Juravle76561322019-11-14 09:08:52 -0800757static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
758static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
759static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
760static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
761static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
762static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
763static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700764
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800765class RunProfman : public ExecVHelper {
766 public:
767 void SetupArgs(const std::vector<unique_fd>& profile_fds,
768 const unique_fd& reference_profile_fd,
769 const std::vector<unique_fd>& apk_fds,
770 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800771 bool copy_and_update,
772 bool for_snapshot,
773 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800774
775 // TODO(calin): Assume for now we run in the bg compile job (which is in
776 // most of the invocation). With the current data flow, is not very easy or
777 // clean to discover this in RunProfman (it will require quite a messy refactoring).
778 const char* profman_bin = select_execution_binary(
779 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700780
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800781 if (copy_and_update) {
782 CHECK_EQ(1u, profile_fds.size());
783 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000784 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800785 if (reference_profile_fd != -1) {
786 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000787 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800788
789 for (const unique_fd& fd : profile_fds) {
790 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
791 }
792
793 for (const unique_fd& fd : apk_fds) {
794 AddArg("--apk-fd=" + std::to_string(fd.get()));
795 }
796
797 for (const std::string& dex_location : dex_locations) {
798 AddArg("--dex-location=" + dex_location);
799 }
800
801 if (copy_and_update) {
802 AddArg("--copy-and-update-profile-key");
803 }
804
Calin Juravle78728f32019-11-08 17:55:46 -0800805 if (for_snapshot) {
806 AddArg("--force-merge");
807 }
808
809 if (for_boot_image) {
810 AddArg("--boot-image-merge");
811 }
812
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800813 // Do not add after dex2oat_flags, they should override others for debugging.
814 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800815 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800817 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
818 const unique_fd& reference_profile_fd,
819 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800820 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
821 bool for_snapshot = false,
822 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800823 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800824 reference_profile_fd,
825 apk_fds,
826 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800827 /*copy_and_update=*/ false,
828 for_snapshot,
829 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800830 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700831
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800832 void SetupCopyAndUpdate(unique_fd&& profile_fd,
833 unique_fd&& reference_profile_fd,
834 unique_fd&& apk_fd,
835 const std::string& dex_location) {
836 // The fds need to stay open longer than the scope of the function, so put them into a local
837 // variable vector.
838 profiles_fd_.push_back(std::move(profile_fd));
839 apk_fds_.push_back(std::move(apk_fd));
840 reference_profile_fd_ = std::move(reference_profile_fd);
841 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800842 SetupArgs(profiles_fd_,
843 reference_profile_fd_,
844 apk_fds_,
845 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800846 /*copy_and_update=*/true,
847 /*for_snapshot*/false,
848 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800849 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000850
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800851 void SetupDump(const std::vector<unique_fd>& profiles_fd,
852 const unique_fd& reference_profile_fd,
853 const std::vector<std::string>& dex_locations,
854 const std::vector<unique_fd>& apk_fds,
855 const unique_fd& output_fd) {
856 AddArg("--dump-only");
857 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800858 SetupArgs(profiles_fd,
859 reference_profile_fd,
860 apk_fds,
861 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800862 /*copy_and_update=*/false,
863 /*for_snapshot*/false,
864 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800865 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000866
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800867 void Exec() {
868 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
869 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000870
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800871 private:
872 unique_fd reference_profile_fd_;
873 std::vector<unique_fd> profiles_fd_;
874 std::vector<unique_fd> apk_fds_;
875};
Mathieu Chartier31636522018-11-09 23:53:07 +0000876
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800877
Calin Juravlef63d4792018-01-30 17:43:34 +0000878
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800880// The location is the package name for primary apks or the dex path for secondary dex files.
881// Returns true if there is enough information in the current profiles that makes it
882// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883// If the return value is true all the current profiles would have been merged into
884// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800885static bool analyze_profiles(uid_t uid, const std::string& package_name,
886 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800887 std::vector<unique_fd> profiles_fd;
888 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800889 open_profile_files(uid, package_name, location, is_secondary_dex,
890 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800891 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700892 // Skip profile guided compilation because no profiles were found.
893 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 return false;
895 }
896
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800897 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700898 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
899 const std::vector<std::string>& dex_locations = std::vector<std::string>();
900 profman_merge.SetupMerge(
901 profiles_fd,
902 reference_profile_fd,
903 apk_fds,
904 dex_locations,
905 /* for_snapshot= */ false,
906 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700907 pid_t pid = fork();
908 if (pid == 0) {
909 /* child -- drop privileges before continuing */
910 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800911 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700912 }
913 /* parent */
914 int return_code = wait_child(pid);
915 bool need_to_compile = false;
916 bool should_clear_current_profiles = false;
917 bool should_clear_reference_profile = false;
918 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800919 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700920 } else {
921 return_code = WEXITSTATUS(return_code);
922 switch (return_code) {
923 case PROFMAN_BIN_RETURN_CODE_COMPILE:
924 need_to_compile = true;
925 should_clear_current_profiles = true;
926 should_clear_reference_profile = false;
927 break;
928 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
929 need_to_compile = false;
930 should_clear_current_profiles = false;
931 should_clear_reference_profile = false;
932 break;
933 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800934 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935 need_to_compile = false;
936 should_clear_current_profiles = true;
937 should_clear_reference_profile = true;
938 break;
939 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
940 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
941 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800942 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700943 need_to_compile = false;
944 should_clear_current_profiles = false;
945 should_clear_reference_profile = false;
946 break;
Calin Juravle76561322019-11-14 09:08:52 -0800947 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
948 need_to_compile = false;
949 should_clear_current_profiles = true;
950 should_clear_reference_profile = true;
951 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700952 default:
953 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800954 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800955 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956 need_to_compile = false;
957 should_clear_current_profiles = true;
958 should_clear_reference_profile = true;
959 break;
960 }
961 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800962
Jeff Sharkey90aff262016-12-12 14:28:24 -0700963 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800964 if (is_secondary_dex) {
965 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800966 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
967 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800968 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800969 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800970 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700971 }
972 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800973 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700974 }
975 return need_to_compile;
976}
977
Calin Juravle114f0812017-03-08 19:05:07 -0800978// Decides if profile guided compilation is needed or not based on existing profiles.
979// The analysis is done for the primary apks of the given package.
980// Returns true if there is enough information in the current profiles that makes it
981// worth to recompile the package.
982// If the return value is true all the current profiles would have been merged into
983// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800984bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
985 const std::string& profile_name) {
986 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800987}
988
Calin Juravle408cd4a2018-01-20 23:34:18 -0800989bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
990 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800991 std::vector<unique_fd> profile_fds;
992 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800993 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
994 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700995
Calin Juravle408cd4a2018-01-20 23:34:18 -0800996 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800997 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700998
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800999 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001000 const bool has_profiles = !profile_fds.empty();
1001
1002 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -08001003 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 return false;
1005 }
1006
Calin Juravle114f0812017-03-08 19:05:07 -08001007 unique_fd output_fd(open(out_file_name.c_str(),
1008 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -08001010 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001011 return false;
1012 }
Calin Juravle408cd4a2018-01-20 23:34:18 -08001013
Jeff Sharkey90aff262016-12-12 14:28:24 -07001014 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001015 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -08001016 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
1017 if (apk_fd == -1) {
1018 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
1019 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001020 }
Calin Juravle408cd4a2018-01-20 23:34:18 -08001021 dex_locations.push_back(get_location_from_path(code_path.c_str()));
1022 apk_fds.push_back(std::move(apk_fd));
1023
Jeff Sharkey90aff262016-12-12 14:28:24 -07001024
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001025 RunProfman profman_dump;
1026 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001027 pid_t pid = fork();
1028 if (pid == 0) {
1029 /* child -- drop privileges before continuing */
1030 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001031 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001032 }
1033 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001034 int return_code = wait_child(pid);
1035 if (!WIFEXITED(return_code)) {
1036 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1037 << return_code;
1038 return false;
1039 }
1040 return true;
1041}
1042
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001043bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001044 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001045 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1046 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001047 package_name,
1048 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001049 /*read_write*/ true,
1050 /*secondary*/ false));
1051 if (in_fd.get() < 0) {
1052 PLOG(WARNING) << "Could not open profile " << system_profile;
1053 return false;
1054 }
1055 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001056 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001057 return false;
1058 }
1059
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001060 // As a security measure we want to write the profile information with the reduced capabilities
1061 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001062 pid_t pid = fork();
1063 if (pid == 0) {
1064 /* child -- drop privileges before continuing */
1065 drop_capabilities(packageUid);
1066
1067 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1068 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001069 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001070 }
1071 // This implies that the app owning this profile is running
1072 // (and has acquired the lock).
1073 //
1074 // The app never acquires the lock for the reference profiles of primary apks.
1075 // Only dex2oat from installd will do that. Since installd is single threaded
1076 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001077 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001078 return false;
1079 }
1080
1081 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1082 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001083 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001084 }
1085
1086 // Copy over data.
1087 static constexpr size_t kBufferSize = 4 * 1024;
1088 char buffer[kBufferSize];
1089 while (true) {
1090 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1091 if (bytes == 0) {
1092 break;
1093 }
1094 write(out_fd.get(), buffer, bytes);
1095 }
1096 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001097 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001098 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001099 // Use _exit since we don't want to run the global destructors in the child.
1100 // b/62597429
1101 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001102 }
1103 /* parent */
1104 int return_code = wait_child(pid);
1105 return return_code == 0;
1106}
1107
Jeff Sharkey90aff262016-12-12 14:28:24 -07001108static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1109 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1110 if (EndsWith(oat_path, ".dex")) {
1111 std::string new_path = oat_path;
1112 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001113 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001114 return new_path;
1115 }
1116
1117 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1118 // case (where the base name will have an extension for the B artifact).
1119 size_t odex_pos = oat_path.rfind(".odex");
1120 if (odex_pos != std::string::npos) {
1121 std::string new_path = oat_path;
1122 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1123 CHECK_NE(new_path.find(new_ext), std::string::npos);
1124 return new_path;
1125 }
1126
1127 // Don't know how to handle this.
1128 return "";
1129}
1130
1131// Translate the given oat path to an art (app image) path. An empty string
1132// denotes an error.
1133static std::string create_image_filename(const std::string& oat_path) {
1134 return replace_file_extension(oat_path, ".art");
1135}
1136
1137// Translate the given oat path to a vdex path. An empty string denotes an error.
1138static std::string create_vdex_filename(const std::string& oat_path) {
1139 return replace_file_extension(oat_path, ".vdex");
1140}
1141
Jeff Sharkey90aff262016-12-12 14:28:24 -07001142static int open_output_file(const char* file_name, bool recreate, int permissions) {
1143 int flags = O_RDWR | O_CREAT;
1144 if (recreate) {
1145 if (unlink(file_name) < 0) {
1146 if (errno != ENOENT) {
1147 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1148 }
1149 }
1150 flags |= O_EXCL;
1151 }
1152 return open(file_name, flags, permissions);
1153}
1154
Calin Juravle2289c0a2017-02-15 12:44:14 -08001155static bool set_permissions_and_ownership(
1156 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1157 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1158 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001159 if (fchmod(fd,
1160 S_IRUSR|S_IWUSR|S_IRGRP |
1161 (is_public ? S_IROTH : 0)) < 0) {
1162 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1163 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001164 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1166 return false;
1167 }
1168 return true;
1169}
1170
1171static bool IsOutputDalvikCache(const char* oat_dir) {
1172 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1173 // into '!'. Play it safe by handling it both.
1174 // TODO: ensure we never get null.
1175 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1176 return oat_dir == nullptr || oat_dir[0] == '!';
1177}
1178
Calin Juravled23dee72017-07-06 16:29:11 -07001179// Best-effort check whether we can fit the the path into our buffers.
1180// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1181// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1182// extension to the cache path (5 bytes).
1183// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1184static bool validate_dex_path_size(const std::string& dex_path) {
1185 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1186 LOG(ERROR) << "dex_path too long: " << dex_path;
1187 return false;
1188 }
1189 return true;
1190}
1191
Jeff Sharkey90aff262016-12-12 14:28:24 -07001192static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001193 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001194 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001195 return false;
1196 }
1197
1198 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001199 // Oat dirs for secondary dex files are already validated.
1200 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001201 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1202 return false;
1203 }
1204 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1205 return false;
1206 }
1207 } else {
1208 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1209 return false;
1210 }
1211 }
1212 return true;
1213}
1214
1215// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1216// on destruction. It will also run the given cleanup (unless told not to) after closing.
1217//
1218// Usage example:
1219//
Calin Juravle7a570e82017-01-14 16:23:30 -08001220// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001221// [name]() {
1222// unlink(name.c_str());
1223// });
1224// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1225// wrapper if captured as a reference.
1226//
1227// if (file.get() == -1) {
1228// // Error opening...
1229// }
1230//
1231// ...
1232// if (error) {
1233// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1234// // and delete the file (after the fd is closed).
1235// return -1;
1236// }
1237//
1238// (Success case)
1239// file.SetCleanup(false);
1240// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1241// // (leaving the file around; after the fd is closed).
1242//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001243class Dex2oatFileWrapper {
1244 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001245 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001246 }
1247
Calin Juravle7a570e82017-01-14 16:23:30 -08001248 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1249 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1250
1251 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1252 value_ = other.value_;
1253 cleanup_ = other.cleanup_;
1254 do_cleanup_ = other.do_cleanup_;
1255 auto_close_ = other.auto_close_;
1256 other.release();
1257 }
1258
1259 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1260 value_ = other.value_;
1261 cleanup_ = other.cleanup_;
1262 do_cleanup_ = other.do_cleanup_;
1263 auto_close_ = other.auto_close_;
1264 other.release();
1265 return *this;
1266 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001267
1268 ~Dex2oatFileWrapper() {
1269 reset(-1);
1270 }
1271
1272 int get() {
1273 return value_;
1274 }
1275
1276 void SetCleanup(bool cleanup) {
1277 do_cleanup_ = cleanup;
1278 }
1279
1280 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001281 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001282 close(value_);
1283 }
1284 if (do_cleanup_ && cleanup_ != nullptr) {
1285 cleanup_();
1286 }
1287
1288 value_ = new_value;
1289 }
1290
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 void reset(int new_value, std::function<void ()> new_cleanup) {
1292 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001293 close(value_);
1294 }
1295 if (do_cleanup_ && cleanup_ != nullptr) {
1296 cleanup_();
1297 }
1298
1299 value_ = new_value;
1300 cleanup_ = new_cleanup;
1301 }
1302
Calin Juravle7a570e82017-01-14 16:23:30 -08001303 void DisableAutoClose() {
1304 auto_close_ = false;
1305 }
1306
Jeff Sharkey90aff262016-12-12 14:28:24 -07001307 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001308 void release() {
1309 value_ = -1;
1310 do_cleanup_ = false;
1311 cleanup_ = nullptr;
1312 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001313 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001314 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001315 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001316 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001317};
1318
Calin Juravle7a570e82017-01-14 16:23:30 -08001319// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001320Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1321 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001322
Calin Juravle7a570e82017-01-14 16:23:30 -08001323 const std::string image_path = create_image_filename(out_oat_path);
1324 if (image_path.empty()) {
1325 // Happens when the out_oat_path has an unknown extension.
1326 return Dex2oatFileWrapper();
1327 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001328
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001329 // In case there is a stale image, remove it now. Ignore any error.
1330 unlink(image_path.c_str());
1331
1332 // Not enabled, exit.
1333 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001334 return Dex2oatFileWrapper();
1335 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001336 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1337 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001338 return Dex2oatFileWrapper();
1339 }
1340 // Recreate is true since we do not want to modify a mapped image. If the app is
1341 // already running and we modify the image file, it can cause crashes (b/27493510).
1342 Dex2oatFileWrapper wrapper_fd(
1343 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1344 [image_path]() { unlink(image_path.c_str()); });
1345 if (wrapper_fd.get() < 0) {
1346 // Could not create application image file. Go on since we can compile without it.
1347 LOG(ERROR) << "installd could not create '" << image_path
1348 << "' for image file during dexopt";
1349 // If we have a valid image file path but no image fd, explicitly erase the image file.
1350 if (unlink(image_path.c_str()) < 0) {
1351 if (errno != ENOENT) {
1352 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1353 }
1354 }
1355 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001356 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001357 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1358 wrapper_fd.reset(-1);
1359 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001360
Calin Juravle7a570e82017-01-14 16:23:30 -08001361 return wrapper_fd;
1362}
1363
1364// Creates the dexopt swap file if necessary and return its fd.
1365// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001366unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001367 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001368 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001369 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001370 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001371 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001372 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001373 if (swap_fd.get() < 0) {
1374 // Could not create swap file. Optimistically go on and hope that we can compile
1375 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001376 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001377 } else {
1378 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001379 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001380 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1381 }
1382 }
1383 return swap_fd;
1384}
1385
1386// Opens the reference profiles if needed.
1387// 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 -08001388Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001389 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001390 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001391 // If we are not profile guided compilation, or we are compiling system server
1392 // do not bother to open the profiles; we won't be using them.
1393 if (!profile_guided || (pkgname[0] == '*')) {
1394 return Dex2oatFileWrapper();
1395 }
1396
1397 // If this is a secondary dex path which is public do not open the profile.
1398 // We cannot compile public secondary dex paths with profiles. That's because
1399 // it will expose how the dex files are used by their owner.
1400 //
1401 // Note that the PackageManager is responsible to set the is_public flag for
1402 // primary apks and we do not check it here. In some cases, e.g. when
1403 // compiling with a public profile from the .dm file the PackageManager will
1404 // set is_public toghether with the profile guided compilation.
1405 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001406 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001407 }
Calin Juravle114f0812017-03-08 19:05:07 -08001408
1409 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001410 std::string location;
1411 if (is_secondary_dex) {
1412 location = dex_path;
1413 } else {
1414 if (profile_name == nullptr) {
1415 // This path is taken for system server re-compilation lunched from ZygoteInit.
1416 return Dex2oatFileWrapper();
1417 } else {
1418 location = profile_name;
1419 }
1420 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001421 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1422 is_secondary_dex);
1423 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1424 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001425 };
1426 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001427}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001428
Calin Juravle7a570e82017-01-14 16:23:30 -08001429// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1430// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001431bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001432 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001433 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001434 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1435 CHECK(in_vdex_wrapper_fd != nullptr);
1436 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001437 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1438 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001439 char in_odex_path[PKG_PATH_MAX];
1440 int dexopt_action = abs(dexopt_needed);
1441 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001442 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001443
1444 // Infer the name of the output VDEX.
1445 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1446 if (out_vdex_path_str.empty()) {
1447 return false;
1448 }
1449
1450 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001451 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001452 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1453 const char* path = nullptr;
1454 if (is_odex_location) {
1455 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1456 path = in_odex_path;
1457 } else {
1458 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001459 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001460 }
1461 } else {
1462 path = out_oat_path;
1463 }
1464 in_vdex_path_str = create_vdex_filename(path);
1465 if (in_vdex_path_str.empty()) {
1466 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001467 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001468 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001469 // We can update in place when all these conditions are met:
1470 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1471 // on /system typically cannot be updated in place).
1472 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1473 // cannot be currently used by a running process.
1474 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1475 // different vdex files to operate.
1476 update_vdex_in_place =
1477 (in_vdex_path_str == out_vdex_path_str) &&
1478 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1479 !profile_guided;
1480 if (update_vdex_in_place) {
1481 // Open the file read-write to be able to update it.
1482 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1483 if (in_vdex_wrapper_fd->get() == -1) {
1484 // If we failed to open the file, we cannot update it in place.
1485 update_vdex_in_place = false;
1486 }
1487 } else {
1488 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1489 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001490 }
1491
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001492 // If we are updating the vdex in place, we do not need to recreate a vdex,
1493 // and can use the same existing one.
1494 if (update_vdex_in_place) {
1495 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1496 // have bogus stale vdex files.
1497 out_vdex_wrapper_fd->reset(
1498 in_vdex_wrapper_fd->get(),
1499 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1500 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1501 // wrapper).
1502 in_vdex_wrapper_fd->DisableAutoClose();
1503 } else {
1504 out_vdex_wrapper_fd->reset(
1505 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1506 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1507 if (out_vdex_wrapper_fd->get() < 0) {
1508 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1509 return false;
1510 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001511 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001512 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001513 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001514 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1515 return false;
1516 }
1517
1518 // If we got here we successfully opened the vdex files.
1519 return true;
1520}
1521
1522// Opens the output oat file for the given apk.
1523// If successful it stores the output path into out_oat_path and returns true.
1524Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001525 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1526 char* out_oat_path) {
1527 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001528 return Dex2oatFileWrapper();
1529 }
1530 const std::string out_oat_path_str(out_oat_path);
1531 Dex2oatFileWrapper wrapper_fd(
1532 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1533 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1534 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001535 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001536 } else if (!set_permissions_and_ownership(
1537 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001538 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1539 wrapper_fd.reset(-1);
1540 }
1541 return wrapper_fd;
1542}
1543
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001544// Creates RDONLY fds for oat and vdex files, if exist.
1545// Returns false if it fails to create oat out path for the given apk path.
1546// Note that the method returns true even if the files could not be opened.
1547bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1548 const std::string& oat_dir,
1549 const std::string& instruction_set,
1550 bool is_secondary_dex,
1551 unique_fd* oat_file_fd,
1552 unique_fd* vdex_file_fd) {
1553 char oat_path[PKG_PATH_MAX];
1554 if (!create_oat_out_path(apk_path.c_str(),
1555 instruction_set.c_str(),
1556 oat_dir.c_str(),
1557 is_secondary_dex,
1558 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001559 LOG(ERROR) << "Could not create oat out path for "
1560 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001561 return false;
1562 }
1563 oat_file_fd->reset(open(oat_path, O_RDONLY));
1564 if (oat_file_fd->get() < 0) {
1565 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1566 }
1567
1568 std::string vdex_filename = create_vdex_filename(oat_path);
1569 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1570 if (vdex_file_fd->get() < 0) {
1571 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1572 }
1573
1574 return true;
1575}
1576
Calin Juravle7a570e82017-01-14 16:23:30 -08001577// Updates the access times of out_oat_path based on those from apk_path.
1578void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1579 struct stat input_stat;
1580 memset(&input_stat, 0, sizeof(input_stat));
1581 if (stat(apk_path, &input_stat) != 0) {
1582 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1583 return;
1584 }
1585
1586 struct utimbuf ut;
1587 ut.actime = input_stat.st_atime;
1588 ut.modtime = input_stat.st_mtime;
1589 if (utime(out_oat_path, &ut) != 0) {
1590 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1591 }
1592}
1593
Calin Juravle80a21252017-01-17 14:43:25 -08001594// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001595// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1596// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1597// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001598class RunDexoptAnalyzer : public ExecVHelper {
1599 public:
1600 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001601 int vdex_fd,
1602 int oat_fd,
1603 int zip_fd,
1604 const std::string& instruction_set,
1605 const std::string& compiler_filter,
1606 bool profile_was_updated,
1607 bool downgrade,
1608 const char* class_loader_context,
1609 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001610 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001611
1612 // We always run the analyzer in the background job.
1613 const char* dexoptanalyzer_bin = select_execution_binary(
1614 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001615
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001616 std::string dex_file_arg = "--dex-file=" + dex_file;
1617 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1618 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1619 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1620 std::string isa_arg = "--isa=" + instruction_set;
1621 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1622 const char* assume_profile_changed = "--assume-profile-changed";
1623 const char* downgrade_flag = "--downgrade";
1624 std::string class_loader_context_arg = "--class-loader-context=";
1625 if (class_loader_context != nullptr) {
1626 class_loader_context_arg += class_loader_context;
1627 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001628 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1629 if (!class_loader_context_fds.empty()) {
1630 class_loader_context_fds_arg += class_loader_context_fds;
1631 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001632
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001633 // program name, dex file, isa, filter
1634 AddArg(dex_file_arg);
1635 AddArg(isa_arg);
1636 AddArg(compiler_filter_arg);
1637 if (oat_fd >= 0) {
1638 AddArg(oat_fd_arg);
1639 }
1640 if (vdex_fd >= 0) {
1641 AddArg(vdex_fd_arg);
1642 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001643 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001644 if (profile_was_updated) {
1645 AddArg(assume_profile_changed);
1646 }
1647 if (downgrade) {
1648 AddArg(downgrade_flag);
1649 }
1650 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001651 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001652 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001653 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001654 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001655 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001656
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001657 PrepareArgs(dexoptanalyzer_bin);
1658 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001659
1660 // Dexoptanalyzer mode which flattens the given class loader context and
1661 // prints a list of its dex files in that flattened order.
1662 RunDexoptAnalyzer(const char* class_loader_context) {
1663 CHECK(class_loader_context != nullptr);
1664
1665 // We always run the analyzer in the background job.
1666 const char* dexoptanalyzer_bin = select_execution_binary(
1667 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1668
1669 AddArg("--flatten-class-loader-context");
1670 AddArg(std::string("--class-loader-context=") + class_loader_context);
1671 PrepareArgs(dexoptanalyzer_bin);
1672 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001673};
Calin Juravle80a21252017-01-17 14:43:25 -08001674
1675// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001676static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001677 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001678 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001679 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001680 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001681 return false;
1682 }
Calin Juravle114f0812017-03-08 19:05:07 -08001683 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001684
Calin Juravle80a21252017-01-17 14:43:25 -08001685 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001686 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1687 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001688 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001689 return false;
1690 }
1691
1692 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001693 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001694
Calin Juravle7d765462017-09-04 15:57:10 -07001695 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001696 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001697 return false;
1698 }
1699
1700 return true;
1701}
1702
Calin Juravle7d765462017-09-04 15:57:10 -07001703// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1704// secondary dex files. This return codes are returned by the child process created for
1705// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001706
Andreas Gampe194fe422018-02-28 20:16:19 -08001707enum DexoptAnalyzerSkipCodes {
1708 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001709 // Specific errors are encoded in the name.
1710 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1711 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1712 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1713 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1714 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001715 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001716 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001717};
Calin Juravle7d765462017-09-04 15:57:10 -07001718
1719// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001720// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1721// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001722// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1723// of dexoptanalyzer.
1724static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001725 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001726 // The result values are defined in dexoptanalyzer.
1727 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001728 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001729 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001730 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001731 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001732 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001733 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001734 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001735 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001736 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1737 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001738 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1739 " Expected odex file status for secondary dex %s"
1740 " : dexoptanalyzer result=%d",
1741 dex_path.c_str(),
1742 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001743 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001744 }
1745
1746 // Use a second switch for enum switch-case analysis.
1747 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001748 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001749 // If the file does not exist there's no need for dexopt.
1750 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1751 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001752
1753 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1754 *error_msg = "Dexoptanalyzer path validation failed";
1755 return false;
1756 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1757 *error_msg = "Dexoptanalyzer open zip failed";
1758 return false;
1759 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1760 *error_msg = "Dexoptanalyzer dir preparation failed";
1761 return false;
1762 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1763 *error_msg = "Dexoptanalyzer open output failed";
1764 return false;
1765 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1766 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001767 return false;
1768 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001769
1770 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1771 dex_path.c_str(),
1772 result);
1773 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001774}
1775
Calin Juravle7d765462017-09-04 15:57:10 -07001776enum SecondaryDexAccess {
1777 kSecondaryDexAccessReadOk = 0,
1778 kSecondaryDexAccessDoesNotExist = 1,
1779 kSecondaryDexAccessPermissionError = 2,
1780 kSecondaryDexAccessIOError = 3
1781};
1782
1783static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1784 // Check if the path exists and can be read. If not, there's nothing to do.
1785 if (access(dex_path.c_str(), R_OK) == 0) {
1786 return kSecondaryDexAccessReadOk;
1787 } else {
1788 if (errno == ENOENT) {
1789 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1790 return kSecondaryDexAccessDoesNotExist;
1791 } else {
1792 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1793 return errno == EACCES
1794 ? kSecondaryDexAccessPermissionError
1795 : kSecondaryDexAccessIOError;
1796 }
1797 }
1798}
1799
1800static bool is_file_public(const std::string& filename) {
1801 struct stat file_stat;
1802 if (stat(filename.c_str(), &file_stat) == 0) {
1803 return (file_stat.st_mode & S_IROTH) != 0;
1804 }
1805 return false;
1806}
1807
1808// Create the oat file structure for the secondary dex 'dex_path' and assign
1809// the individual path component to the 'out_' parameters.
1810static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001811 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001812 size_t dirIndex = dex_path.rfind('/');
1813 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001814 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001815 return false;
1816 }
1817 // TODO(calin): we have similar computations in at lest 3 other places
1818 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1819 // using string append.
1820 std::string apk_dir = dex_path.substr(0, dirIndex);
1821 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1822 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1823
1824 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1825 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001826 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001827 return false;
1828 }
1829 return true;
1830}
1831
1832// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1833// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001834static bool validate_dexopt_storage_flags(int dexopt_flags,
1835 int* out_storage_flag,
1836 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001837 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1838 *out_storage_flag = FLAG_STORAGE_CE;
1839 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001840 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001841 return false;
1842 }
1843 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1844 *out_storage_flag = FLAG_STORAGE_DE;
1845 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001846 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001847 return false;
1848 }
1849 return true;
1850}
1851
David Brazdil4f6027a2019-03-19 11:44:21 +00001852static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1853 /* out */ std::vector<std::string>* context_dex_paths) {
1854 if (class_loader_context == nullptr) {
1855 return true;
1856 }
1857
1858 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1859
1860 // Pipe to get the hash result back from our child process.
1861 unique_fd pipe_read, pipe_write;
1862 if (!Pipe(&pipe_read, &pipe_write)) {
1863 PLOG(ERROR) << "Failed to create pipe";
1864 return false;
1865 }
1866
1867 pid_t pid = fork();
1868 if (pid == 0) {
1869 // child -- drop privileges before continuing.
1870 drop_capabilities(uid);
1871
1872 // Route stdout to `pipe_write`
1873 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1874 pipe_write.reset();
1875 pipe_read.reset();
1876
1877 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1878 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1879 }
1880
1881 /* parent */
1882 pipe_write.reset();
1883
1884 std::string str_dex_paths;
1885 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1886 PLOG(ERROR) << "Failed to read from pipe";
1887 return false;
1888 }
1889 pipe_read.reset();
1890
1891 int return_code = wait_child(pid);
1892 if (!WIFEXITED(return_code)) {
1893 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1894 return false;
1895 }
1896
1897 constexpr int kFlattenClassLoaderContextSuccess = 50;
1898 return_code = WEXITSTATUS(return_code);
1899 if (return_code != kFlattenClassLoaderContextSuccess) {
1900 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1901 return false;
1902 }
1903
1904 if (!str_dex_paths.empty()) {
1905 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1906 }
1907 return true;
1908}
1909
1910static int open_dex_paths(const std::vector<std::string>& dex_paths,
1911 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1912 for (const std::string& dex_path : dex_paths) {
1913 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1914 if (zip_fds->back().get() < 0) {
1915 *error_msg = StringPrintf(
1916 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1917 if (errno == ENOENT) {
1918 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1919 } else {
1920 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1921 }
1922 }
1923 }
1924 return 0;
1925}
1926
1927static std::string join_fds(const std::vector<unique_fd>& fds) {
1928 std::stringstream ss;
1929 bool is_first = true;
1930 for (const unique_fd& fd : fds) {
1931 if (is_first) {
1932 is_first = false;
1933 } else {
1934 ss << ":";
1935 }
1936 ss << fd.get();
1937 }
1938 return ss.str();
1939}
1940
Calin Juravlec9eab382017-01-25 01:17:17 -08001941// 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 -08001942// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1943// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001944// When returning true, the output parameters will be:
1945// - is_public_out: whether or not the oat file should not be made public
1946// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1947// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001948static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001949 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001950 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001951 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001952 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001953 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001954 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001955 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1956 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001957 return false;
1958 }
Calin Juravle7d765462017-09-04 15:57:10 -07001959 // Compute the oat dir as it's not easy to extract it from the child computation.
1960 char oat_path[PKG_PATH_MAX];
1961 char oat_dir[PKG_PATH_MAX];
1962 char oat_isa_dir[PKG_PATH_MAX];
1963 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001964 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1965 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001966 return false;
1967 }
Calin Juravle7d765462017-09-04 15:57:10 -07001968 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001969
Calin Juravle80a21252017-01-17 14:43:25 -08001970 pid_t pid = fork();
1971 if (pid == 0) {
1972 // child -- drop privileges before continuing.
1973 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001974
1975 // Validate the path structure.
1976 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1977 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001978 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001979 }
1980
1981 // Open the dex file.
1982 unique_fd zip_fd;
1983 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1984 if (zip_fd.get() < 0) {
1985 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001986 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001987 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001988 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001989 }
1990 }
1991
David Brazdil4f6027a2019-03-19 11:44:21 +00001992 // Open class loader context dex files.
1993 std::vector<unique_fd> context_zip_fds;
1994 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1995 if (open_dex_paths_rc != 0) {
1996 _exit(open_dex_paths_rc);
1997 }
1998
Calin Juravle7d765462017-09-04 15:57:10 -07001999 // Prepare the oat directories.
2000 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002001 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07002002 }
2003
2004 // Open the vdex/oat files if any.
2005 unique_fd oat_file_fd;
2006 unique_fd vdex_file_fd;
2007 if (!maybe_open_oat_and_vdex_file(dex_path,
2008 *oat_dir_out,
2009 instruction_set,
2010 true /* is_secondary_dex */,
2011 &oat_file_fd,
2012 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002013 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07002014 }
2015
2016 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08002017 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
2018 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07002019
2020 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002021 // Note that we do not do it before the fork since opening the files is required to happen
2022 // after forking.
2023 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
2024 vdex_file_fd.get(),
2025 oat_file_fd.get(),
2026 zip_fd.get(),
2027 instruction_set,
2028 compiler_filter, profile_was_updated,
2029 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00002030 class_loader_context,
2031 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002032 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08002033 }
2034
2035 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08002036 int result = wait_child(pid);
2037 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002038 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2039 dex_path.c_str(),
2040 result);
2041 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002042 return false;
2043 }
2044 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002045 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002046 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2047 result,
2048 dexopt_needed_out,
2049 error_msg);
2050 if (!success) {
2051 LOG(ERROR) << *error_msg;
2052 }
Calin Juravle7d765462017-09-04 15:57:10 -07002053
2054 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2055
Calin Juravle80a21252017-01-17 14:43:25 -08002056 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002057 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2058 // makes the code simpler; force compilation is only needed during tests).
2059 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002060 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002061 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002062 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2063 }
2064
Calin Juravle7d765462017-09-04 15:57:10 -07002065 // Check if we should make the oat file public.
2066 // Note that if the dex file is not public the compiled code cannot be made public.
2067 // It is ok to check this flag outside in the parent process.
2068 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2069
Calin Juravle80a21252017-01-17 14:43:25 -08002070 return success;
2071}
2072
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002073static std::string format_dexopt_error(int status, const char* dex_path) {
2074 if (WIFEXITED(status)) {
2075 int int_code = WEXITSTATUS(status);
2076 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2077 if (code_name != nullptr) {
2078 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2079 }
2080 }
2081 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002082}
2083
Calin Juravlec9eab382017-01-25 01:17:17 -08002084int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002085 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002086 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002087 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002088 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002089 CHECK(pkgname != nullptr);
2090 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002091 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002092 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2093 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002094
Calin Juravled23dee72017-07-06 16:29:11 -07002095 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002096 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002097 return -1;
2098 }
2099
2100 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002101 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2102 class_loader_context);
2103 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002104 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002105 }
2106
Calin Juravleebc8a792017-04-04 20:21:05 -07002107 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002108 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2109 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2110 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002111 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002112 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002113 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002114 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002115 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002116 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002117
2118 // Check if we're dealing with a secondary dex file and if we need to compile it.
2119 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002120 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002121 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002122 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2123 *error_msg = "Failed acquiring context dex paths";
2124 return -1; // We had an error, logged in the process method.
2125 }
2126
Calin Juravlec9eab382017-01-25 01:17:17 -08002127 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002128 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002129 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002130 oat_dir = oat_dir_str.c_str();
2131 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2132 return 0; // Nothing to do, report success.
2133 }
2134 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002135 if (error_msg->empty()) { // TODO: Make this a CHECK.
2136 *error_msg = "Failed processing secondary.";
2137 }
Calin Juravle80a21252017-01-17 14:43:25 -08002138 return -1; // We had an error, logged in the process method.
2139 }
2140 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002141 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002142 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002143 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2144 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2145 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002146
2147 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002148 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002149 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002150 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2151 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002152 return -1;
2153 }
2154
David Brazdil4f6027a2019-03-19 11:44:21 +00002155 // Open class loader context dex files.
2156 std::vector<unique_fd> context_input_fds;
2157 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2158 LOG(ERROR) << *error_msg;
2159 return -1;
2160 }
2161
Calin Juravle7a570e82017-01-14 16:23:30 -08002162 // Create the output OAT file.
2163 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002164 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002165 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002166 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002167 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002168 return -1;
2169 }
2170
2171 // Open vdex files.
2172 Dex2oatFileWrapper in_vdex_fd;
2173 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002174 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2175 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002176 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002177 return -1;
2178 }
2179
Calin Juravlecb556e32017-04-04 20:22:50 -07002180 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2181 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2182 // fully inherit their parent context).
2183 // Note that for primary apk the oat files are created before, in a separate installd
2184 // call which also does the restorecon. TODO(calin): unify the paths.
2185 if (is_secondary_dex) {
2186 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2187 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002188 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2189 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002190 return -1;
2191 }
2192 }
2193
Jeff Sharkey90aff262016-12-12 14:28:24 -07002194 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002195 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002196
Calin Juravle7a570e82017-01-14 16:23:30 -08002197 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002198 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002199 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002200
liulvping61907742018-08-21 09:36:52 +08002201 if (reference_profile_fd.get() == -1) {
2202 // We don't create an app image without reference profile since there is no speedup from
2203 // loading it in that case and instead will be a small overhead.
2204 generate_app_image = false;
2205 }
2206
2207 // Create the app image file if needed.
2208 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2209 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2210
Calin Juravle62c5a372018-02-01 17:03:23 +00002211 unique_fd dex_metadata_fd;
2212 if (dex_metadata_path != nullptr) {
2213 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2214 if (dex_metadata_fd.get() < 0) {
2215 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2216 }
2217 }
2218
Victor Hsieh8948a862020-08-07 11:30:55 -07002219 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
2220 RUNTIME_NATIVE_BOOT_NAMESPACE,
2221 ENABLE_JITZYGOTE_IMAGE,
2222 /*default_value=*/ "");
2223 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
2224
Andreas Gampe023b2242018-02-28 16:03:25 -08002225 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002226
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002227 RunDex2Oat runner(input_fd.get(),
2228 out_oat_fd.get(),
2229 in_vdex_fd.get(),
2230 out_vdex_fd.get(),
2231 image_fd.get(),
2232 dex_path,
2233 out_oat_path,
2234 swap_fd.get(),
2235 instruction_set,
2236 compiler_filter,
2237 debuggable,
2238 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002239 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002240 background_job_compile,
2241 reference_profile_fd.get(),
2242 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002243 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002244 target_sdk_version,
2245 enable_hidden_api_checks,
2246 generate_compact_dex,
2247 dex_metadata_fd.get(),
Victor Hsieh8948a862020-08-07 11:30:55 -07002248 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002249 compilation_reason);
2250
Jeff Sharkey90aff262016-12-12 14:28:24 -07002251 pid_t pid = fork();
2252 if (pid == 0) {
2253 /* child -- drop privileges before continuing */
2254 drop_capabilities(uid);
2255
Richard Uhler76cc0272016-12-08 10:46:35 +00002256 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002257 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002258 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002259 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002260 }
2261
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002262 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002263 } else {
2264 int res = wait_child(pid);
2265 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002266 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002267 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002268 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2269 << std::hex << std::setw(4) << res << ", process failed";
2270 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002271 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002272 }
2273 }
2274
Calin Juravlec9eab382017-01-25 01:17:17 -08002275 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002276
2277 // We've been successful, don't delete output.
2278 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002279 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002280 image_fd.SetCleanup(false);
2281 reference_profile_fd.SetCleanup(false);
2282
2283 return 0;
2284}
2285
Calin Juravlec9eab382017-01-25 01:17:17 -08002286// Try to remove the given directory. Log an error if the directory exists
2287// and is empty but could not be removed.
2288static bool rmdir_if_empty(const char* dir) {
2289 if (rmdir(dir) == 0) {
2290 return true;
2291 }
2292 if (errno == ENOENT || errno == ENOTEMPTY) {
2293 return true;
2294 }
2295 PLOG(ERROR) << "Failed to remove dir: " << dir;
2296 return false;
2297}
2298
2299// Try to unlink the given file. Log an error if the file exists and could not
2300// be unlinked.
2301static bool unlink_if_exists(const std::string& file) {
2302 if (unlink(file.c_str()) == 0) {
2303 return true;
2304 }
2305 if (errno == ENOENT) {
2306 return true;
2307
2308 }
2309 PLOG(ERROR) << "Could not unlink: " << file;
2310 return false;
2311}
2312
Calin Juravle7d765462017-09-04 15:57:10 -07002313enum ReconcileSecondaryDexResult {
2314 kReconcileSecondaryDexExists = 0,
2315 kReconcileSecondaryDexCleanedUp = 1,
2316 kReconcileSecondaryDexValidationError = 2,
2317 kReconcileSecondaryDexCleanUpError = 3,
2318 kReconcileSecondaryDexAccessIOError = 4,
2319};
Calin Juravlec9eab382017-01-25 01:17:17 -08002320
2321// Reconcile the secondary dex 'dex_path' and its generated oat files.
2322// Return true if all the parameters are valid and the secondary dex file was
2323// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2324// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2325// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2326// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2327// Return false if there were errors during processing. In this case
2328// out_secondary_dex_exists will be set to false.
2329bool reconcile_secondary_dex_file(const std::string& dex_path,
2330 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002331 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002332 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002333 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002334 if (isas.size() == 0) {
2335 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2336 return false;
2337 }
2338
Calin Juravle7d765462017-09-04 15:57:10 -07002339 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2340 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2341 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002342 return false;
2343 }
2344
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002345 // As a security measure we want to unlink art artifacts with the reduced capabilities
2346 // of the package user id. So we fork and drop capabilities in the child.
2347 pid_t pid = fork();
2348 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002349 /* child -- drop privileges before continuing */
2350 drop_capabilities(uid);
2351
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002352 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002353 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002354 uid, storage_flag)) {
2355 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2356 _exit(kReconcileSecondaryDexValidationError);
2357 }
2358
2359 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2360 switch (access_check) {
2361 case kSecondaryDexAccessDoesNotExist:
2362 // File does not exist. Proceed with cleaning.
2363 break;
2364 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2365 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2366 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2367 default:
2368 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2369 _exit(kReconcileSecondaryDexValidationError);
2370 }
2371
2372 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002373 char oat_path[PKG_PATH_MAX];
2374 char oat_dir[PKG_PATH_MAX];
2375 char oat_isa_dir[PKG_PATH_MAX];
2376 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002377 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002378 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002379 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002380 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2381 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002382 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002383 }
Calin Juravle51314092017-05-18 15:33:05 -07002384
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002385 // Delete oat/vdex/art files.
2386 result = unlink_if_exists(oat_path) && result;
2387 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2388 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002389
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002390 // Delete profiles.
2391 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002392 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002393 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002394 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002395 result = unlink_if_exists(current_profile) && result;
2396 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002397
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002398 // We upgraded once the location of current profile for secondary dex files.
2399 // Check for any previous left-overs and remove them as well.
2400 std::string old_current_profile = dex_path + ".prof";
2401 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002402
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002403 // Try removing the directories as well, they might be empty.
2404 result = rmdir_if_empty(oat_isa_dir) && result;
2405 result = rmdir_if_empty(oat_dir) && result;
2406 }
Calin Juravle7d765462017-09-04 15:57:10 -07002407 if (!result) {
2408 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2409 }
2410 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002411 }
2412
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002413 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002414 if (!WIFEXITED(return_code)) {
2415 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2416 } else {
2417 return_code = WEXITSTATUS(return_code);
2418 }
2419
2420 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2421
2422 switch (return_code) {
2423 case kReconcileSecondaryDexCleanedUp:
2424 case kReconcileSecondaryDexValidationError:
2425 // If we couldn't validate assume the dex file does not exist.
2426 // This will purge the entry from the PM records.
2427 *out_secondary_dex_exists = false;
2428 return true;
2429 case kReconcileSecondaryDexExists:
2430 *out_secondary_dex_exists = true;
2431 return true;
2432 case kReconcileSecondaryDexAccessIOError:
2433 // We had an access IO error.
2434 // Return false so that we can try again.
2435 // The value of out_secondary_dex_exists does not matter in this case and by convention
2436 // is set to false.
2437 *out_secondary_dex_exists = false;
2438 return false;
2439 default:
2440 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2441 *out_secondary_dex_exists = false;
2442 return false;
2443 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002444}
2445
Alan Stokesa25d90c2017-10-16 10:56:00 +01002446// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2447// Returns true if all parameters are valid and the hash successfully computed and stored in
2448// out_secondary_dex_hash.
2449// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2450// the app.
2451// For any other errors (e.g. if any of the parameters are invalid) returns false.
2452bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002453 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002454 std::vector<uint8_t>* out_secondary_dex_hash) {
2455 out_secondary_dex_hash->clear();
2456
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002457 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002458
2459 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2460 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2461 << storage_flag;
2462 return false;
2463 }
2464
2465 // Pipe to get the hash result back from our child process.
2466 unique_fd pipe_read, pipe_write;
2467 if (!Pipe(&pipe_read, &pipe_write)) {
2468 PLOG(ERROR) << "Failed to create pipe";
2469 return false;
2470 }
2471
2472 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2473 // access data the app itself can access.
2474 pid_t pid = fork();
2475 if (pid == 0) {
2476 // child -- drop privileges before continuing
2477 drop_capabilities(uid);
2478 pipe_read.reset();
2479
2480 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2481 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002482 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002483 }
2484
2485 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2486 if (fd == -1) {
2487 if (errno == EACCES || errno == ENOENT) {
2488 // Not treated as an error.
2489 _exit(0);
2490 }
2491 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002492 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002493 }
2494
2495 SHA256_CTX ctx;
2496 SHA256_Init(&ctx);
2497
2498 std::vector<uint8_t> buffer(65536);
2499 while (true) {
2500 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2501 if (bytes_read == 0) {
2502 break;
2503 } else if (bytes_read == -1) {
2504 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002505 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002506 }
2507
2508 SHA256_Update(&ctx, buffer.data(), bytes_read);
2509 }
2510
2511 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2512 SHA256_Final(hash.data(), &ctx);
2513 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002514 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002515 }
2516
2517 _exit(0);
2518 }
2519
2520 // parent
2521 pipe_write.reset();
2522
2523 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2524 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2525 out_secondary_dex_hash->clear();
2526 }
2527 return wait_child(pid) == 0;
2528}
2529
Jeff Sharkey90aff262016-12-12 14:28:24 -07002530// Helper for move_ab, so that we can have common failure-case cleanup.
2531static bool unlink_and_rename(const char* from, const char* to) {
2532 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2533 // return a failure.
2534 struct stat s;
2535 if (stat(to, &s) == 0) {
2536 if (!S_ISREG(s.st_mode)) {
2537 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2538 return false;
2539 }
2540 if (unlink(to) != 0) {
2541 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2542 return false;
2543 }
2544 } else {
2545 // This may be a permission problem. We could investigate the error code, but we'll just
2546 // let the rename failure do the work for us.
2547 }
2548
2549 // Try to rename "to" to "from."
2550 if (rename(from, to) != 0) {
2551 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2552 return false;
2553 }
2554 return true;
2555}
2556
2557// Move/rename a B artifact (from) to an A artifact (to).
2558static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2559 // Check whether B exists.
2560 {
2561 struct stat s;
2562 if (stat(b_path.c_str(), &s) != 0) {
2563 // Silently ignore for now. The service calling this isn't smart enough to understand
2564 // lack of artifacts at the moment.
2565 return false;
2566 }
2567 if (!S_ISREG(s.st_mode)) {
2568 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2569 // Try to unlink, but swallow errors.
2570 unlink(b_path.c_str());
2571 return false;
2572 }
2573 }
2574
2575 // Rename B to A.
2576 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2577 // Delete the b_path so we don't try again (or fail earlier).
2578 if (unlink(b_path.c_str()) != 0) {
2579 PLOG(ERROR) << "Could not unlink " << b_path;
2580 }
2581
2582 return false;
2583 }
2584
2585 return true;
2586}
2587
2588bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2589 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002590 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2591 if (slot_suffix.empty()) {
2592 return false;
2593 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002594
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002595 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2596 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2597 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002598 }
2599
2600 // Validate other inputs.
2601 if (validate_apk_path(apk_path) != 0) {
2602 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2603 return false;
2604 }
2605 if (validate_apk_path(oat_dir) != 0) {
2606 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2607 return false;
2608 }
2609
2610 char a_path[PKG_PATH_MAX];
2611 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2612 return false;
2613 }
2614 const std::string a_vdex_path = create_vdex_filename(a_path);
2615 const std::string a_image_path = create_image_filename(a_path);
2616
2617 // B path = A path + slot suffix.
2618 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2619 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2620 const std::string b_image_path = StringPrintf("%s.%s",
2621 a_image_path.c_str(),
2622 slot_suffix.c_str());
2623
2624 bool success = true;
2625 if (move_ab_path(b_path, a_path)) {
2626 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2627 // Note: we can live without an app image. As such, ignore failure to move the image file.
2628 // If we decide to require the app image, or the app image being moved correctly,
2629 // then change accordingly.
2630 constexpr bool kIgnoreAppImageFailure = true;
2631
2632 if (!a_image_path.empty()) {
2633 if (!move_ab_path(b_image_path, a_image_path)) {
2634 unlink(a_image_path.c_str());
2635 if (!kIgnoreAppImageFailure) {
2636 success = false;
2637 }
2638 }
2639 }
2640 } else {
2641 // Cleanup: delete B image, ignore errors.
2642 unlink(b_image_path.c_str());
2643 success = false;
2644 }
2645 } else {
2646 // Cleanup: delete B image, ignore errors.
2647 unlink(b_vdex_path.c_str());
2648 unlink(b_image_path.c_str());
2649 success = false;
2650 }
2651 return success;
2652}
2653
2654bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2655 // Delete the oat/odex file.
2656 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002657 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002658 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002659 return false;
2660 }
2661
2662 // In case of a permission failure report the issue. Otherwise just print a warning.
2663 auto unlink_and_check = [](const char* path) -> bool {
2664 int result = unlink(path);
2665 if (result != 0) {
2666 if (errno == EACCES || errno == EPERM) {
2667 PLOG(ERROR) << "Could not unlink " << path;
2668 return false;
2669 }
2670 PLOG(WARNING) << "Could not unlink " << path;
2671 }
2672 return true;
2673 };
2674
2675 // Delete the oat/odex file.
2676 bool return_value_oat = unlink_and_check(out_path);
2677
2678 // Derive and delete the app image.
2679 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2680
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002681 // Derive and delete the vdex file.
2682 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2683
Jeff Sharkey90aff262016-12-12 14:28:24 -07002684 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002685 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002686}
2687
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002688static bool is_absolute_path(const std::string& path) {
2689 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2690 LOG(ERROR) << "Invalid absolute path " << path;
2691 return false;
2692 } else {
2693 return true;
2694 }
2695}
2696
2697static bool is_valid_instruction_set(const std::string& instruction_set) {
2698 // TODO: add explicit whitelisting of instruction sets
2699 if (instruction_set.find('/') != std::string::npos) {
2700 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2701 return false;
2702 } else {
2703 return true;
2704 }
2705}
2706
2707bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2708 const char *apk_path, const char *instruction_set) {
2709 std::string oat_dir_ = oat_dir;
2710 std::string apk_path_ = apk_path;
2711 std::string instruction_set_ = instruction_set;
2712
2713 if (!is_absolute_path(oat_dir_)) return false;
2714 if (!is_absolute_path(apk_path_)) return false;
2715 if (!is_valid_instruction_set(instruction_set_)) return false;
2716
2717 std::string::size_type end = apk_path_.rfind('.');
2718 std::string::size_type start = apk_path_.rfind('/', end);
2719 if (end == std::string::npos || start == std::string::npos) {
2720 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2721 return false;
2722 }
2723
2724 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2725 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2726 const char* res = res_.c_str();
2727 if (strlen(res) >= PKG_PATH_MAX) {
2728 LOG(ERROR) << "Result too large";
2729 return false;
2730 } else {
2731 strlcpy(path, res, PKG_PATH_MAX);
2732 return true;
2733 }
2734}
2735
2736bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2737 const char *instruction_set) {
2738 std::string apk_path_ = apk_path;
2739 std::string instruction_set_ = instruction_set;
2740
2741 if (!is_absolute_path(apk_path_)) return false;
2742 if (!is_valid_instruction_set(instruction_set_)) return false;
2743
2744 std::string::size_type end = apk_path_.rfind('.');
2745 std::string::size_type start = apk_path_.rfind('/', end);
2746 if (end == std::string::npos || start == std::string::npos) {
2747 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2748 return false;
2749 }
2750
2751 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2752 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2753}
2754
2755bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2756 const char *instruction_set) {
2757 std::string src_ = src;
2758 std::string instruction_set_ = instruction_set;
2759
2760 if (!is_absolute_path(src_)) return false;
2761 if (!is_valid_instruction_set(instruction_set_)) return false;
2762
2763 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2764 if (*it == '/') {
2765 *it = '@';
2766 }
2767 }
2768
2769 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2770 + DALVIK_CACHE_POSTFIX;
2771 const char* res = res_.c_str();
2772 if (strlen(res) >= PKG_PATH_MAX) {
2773 LOG(ERROR) << "Result too large";
2774 return false;
2775 } else {
2776 strlcpy(path, res, PKG_PATH_MAX);
2777 return true;
2778 }
2779}
2780
Calin Juravle59f7ab82018-04-27 17:50:23 -07002781bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2782 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002783 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2784 for (const std::string& elem : classpaths_elems) {
2785 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2786 if (fd < 0) {
2787 PLOG(ERROR) << "Could not open classpath elem " << elem;
2788 return false;
2789 } else {
2790 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002791 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002792 }
2793 }
2794 return true;
2795}
2796
2797static bool create_app_profile_snapshot(int32_t app_id,
2798 const std::string& package_name,
2799 const std::string& profile_name,
2800 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002801 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2802
Calin Juravle824a64d2018-01-18 20:23:17 -08002803 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002804 if (snapshot_fd < 0) {
2805 return false;
2806 }
2807
2808 std::vector<unique_fd> profiles_fd;
2809 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002810 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2811 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002812 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2813 return false;
2814 }
2815
2816 profiles_fd.push_back(std::move(reference_profile_fd));
2817
Calin Juravle0d0a4922018-01-23 19:54:11 -08002818 // Open the class paths elements. These will be used to filter out profile data that does
2819 // not belong to the classpath during merge.
2820 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002821 std::vector<std::string> dex_locations;
2822 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002823 return false;
2824 }
2825
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002826 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002827 // This is specifically a snapshot for an app, so don't use boot image profiles.
2828 args.SetupMerge(profiles_fd,
2829 snapshot_fd,
2830 apk_fds,
2831 dex_locations,
2832 /* for_snapshot= */ true,
2833 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002834 pid_t pid = fork();
2835 if (pid == 0) {
2836 /* child -- drop privileges before continuing */
2837 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002838 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002839 }
2840
2841 /* parent */
2842 int return_code = wait_child(pid);
2843 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002844 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002845 return false;
2846 }
2847
Calin Juravle78728f32019-11-08 17:55:46 -08002848 // Verify that profman finished successfully.
2849 int profman_code = WEXITSTATUS(return_code);
2850 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2851 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2852 << ":" << profman_code;
2853 return false;
2854 }
Calin Juravle29591732017-11-20 17:46:19 -08002855 return true;
2856}
2857
Calin Juravle0d0a4922018-01-23 19:54:11 -08002858static bool create_boot_image_profile_snapshot(const std::string& package_name,
2859 const std::string& profile_name,
2860 const std::string& classpath) {
2861 // The reference profile directory for the android package might not be prepared. Do it now.
2862 const std::string ref_profile_dir =
2863 create_primary_reference_profile_package_dir_path(package_name);
2864 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2865 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2866 return false;
2867 }
2868
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002869 // Return false for empty class path since it may otherwise return true below if profiles is
2870 // empty.
2871 if (classpath.empty()) {
2872 PLOG(ERROR) << "Class path is empty";
2873 return false;
2874 }
2875
Calin Juravle0d0a4922018-01-23 19:54:11 -08002876 // Open and create the snapshot profile.
2877 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2878
2879 // Collect all non empty profiles.
2880 // The collection will traverse all applications profiles and find the non empty files.
2881 // This has the potential of inspecting a large number of files and directories (depending
2882 // on the number of applications and users). So there is a slight increase in the chance
2883 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2884 // fail the snapshot and aggregate whatever profile we could open.
2885 //
2886 // The profile snapshot is a best effort based on available data it's ok if some data
2887 // from some apps is missing. It will be counter productive for the snapshot to fail
2888 // because we could not open or read some of the files.
2889 std::vector<std::string> profiles;
2890 if (!collect_profiles(&profiles)) {
2891 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2892 }
2893
2894 // If we have no profiles return early.
2895 if (profiles.empty()) {
2896 return true;
2897 }
2898
2899 // Open the classpath elements. These will be used to filter out profile data that does
2900 // not belong to the classpath during merge.
2901 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002902 std::vector<std::string> dex_locations;
2903 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002904 return false;
2905 }
2906
2907 // If we could not open any files from the classpath return an error.
2908 if (apk_fds.empty()) {
2909 LOG(ERROR) << "Could not open any of the classpath elements.";
2910 return false;
2911 }
2912
2913 // Aggregate the profiles in batches of kAggregationBatchSize.
2914 // We do this to avoid opening a huge a amount of files.
2915 static constexpr size_t kAggregationBatchSize = 10;
2916
Calin Juravle0d0a4922018-01-23 19:54:11 -08002917 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002918 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002919 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2920 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2921 if (fd.get() >= 0) {
2922 profiles_fd.push_back(std::move(fd));
2923 }
2924 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002925
2926 // We aggregate (read & write) into the same fd multiple times in a row.
2927 // We need to reset the cursor every time to ensure we read the whole file every time.
2928 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2929 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2930 return false;
2931 }
2932
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002933 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002934 args.SetupMerge(profiles_fd,
2935 snapshot_fd,
2936 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002937 dex_locations,
2938 /*for_snapshot=*/true,
2939 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002940 pid_t pid = fork();
2941 if (pid == 0) {
2942 /* child -- drop privileges before continuing */
2943 drop_capabilities(AID_SYSTEM);
2944
Calin Juravle59f7ab82018-04-27 17:50:23 -07002945 // The introduction of new access flags into boot jars causes them to
2946 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002947 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002948 }
2949
2950 /* parent */
2951 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002952
Calin Juravle0d0a4922018-01-23 19:54:11 -08002953 if (!WIFEXITED(return_code)) {
2954 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2955 return false;
2956 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002957
2958 // Verify that profman finished successfully.
2959 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002960 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2961 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2962 << ":" << profman_code;
2963 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002964 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002965 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002966
Calin Juravle0d0a4922018-01-23 19:54:11 -08002967 return true;
2968}
2969
2970bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2971 const std::string& profile_name, const std::string& classpath) {
2972 if (app_id == -1) {
2973 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2974 } else {
2975 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2976 }
2977}
2978
Calin Juravlec3b049e2018-01-18 22:32:58 -08002979bool prepare_app_profile(const std::string& package_name,
2980 userid_t user_id,
2981 appid_t app_id,
2982 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002983 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002984 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002985 // Prepare the current profile.
2986 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2987 /*is_secondary_dex*/ false);
2988 uid_t uid = multiuser_get_uid(user_id, app_id);
2989 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2990 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2991 return false;
2992 }
2993
2994 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002995 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002996 return true;
2997 }
2998
2999 // We have a dex metdata. Merge the profile into the reference profile.
3000 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
3001 /*read_write*/ true, /*is_secondary_dex*/ false);
3002 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
3003 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00003004 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
3005 if (apk_fd < 0) {
3006 PLOG(ERROR) << "Could not open code path " << code_path;
3007 return false;
3008 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08003009
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003010 RunProfman args;
3011 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
3012 std::move(ref_profile_fd),
3013 std::move(apk_fd),
3014 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08003015 pid_t pid = fork();
3016 if (pid == 0) {
3017 /* child -- drop privileges before continuing */
3018 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
3019 drop_capabilities(app_shared_gid);
3020
Calin Juravlef63d4792018-01-30 17:43:34 +00003021 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003022 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08003023 }
3024
3025 /* parent */
3026 int return_code = wait_child(pid);
3027 if (!WIFEXITED(return_code)) {
3028 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
3029 return false;
3030 }
3031 return true;
3032}
3033
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003034} // namespace installd
3035} // namespace android