blob: dfdcab8c0f00d33f52cbd5b4da262931ce95f2e0 [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
Victor Hsieh76f19ba2020-08-10 14:37:26 -070058using android::base::Basename;
Jeff Sharkey90aff262016-12-12 14:28:24 -070059using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070060using android::base::GetBoolProperty;
61using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000062using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010063using android::base::ReadFully;
64using android::base::StringPrintf;
65using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080066using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067
68namespace android {
69namespace installd {
70
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070071// Should minidebug info be included in compiled artifacts? Even if this value is
72// "true," usage might still be conditional to other constraints, e.g., system
73// property overrides.
74static constexpr bool kEnableMinidebugInfo = true;
75
76static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
77static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
78static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080079static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070080
Andreas Gampefa2dadd2018-02-28 19:52:47 -080081
Calin Juravle114f0812017-03-08 19:05:07 -080082// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
83struct FreeDelete {
84 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
85 void operator()(const void* ptr) const {
86 free(const_cast<void*>(ptr));
87 }
88};
89
90// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
91template <typename T>
92using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
93
Calin Juravle1a0af3b2017-03-09 14:33:33 -080094static unique_fd invalid_unique_fd() {
95 return unique_fd(-1);
96}
97
Andreas Gampe6a9cf722017-07-24 16:49:10 -070098static bool is_debug_runtime() {
99 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
100}
101
David Sehra3b5ab62017-10-25 14:27:29 -0700102static bool is_debuggable_build() {
103 return android::base::GetBoolProperty("ro.debuggable", false);
104}
105
Jeff Sharkey90aff262016-12-12 14:28:24 -0700106static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800107 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700108 if (ufd.get() < 0) {
109 if (errno != ENOENT) {
110 PLOG(WARNING) << "Could not open profile " << profile;
111 return false;
112 } else {
113 // Nothing to clear. That's ok.
114 return true;
115 }
116 }
117
118 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
119 if (errno != EWOULDBLOCK) {
120 PLOG(WARNING) << "Error locking profile " << profile;
121 }
122 // This implies that the app owning this profile is running
123 // (and has acquired the lock).
124 //
125 // If we can't acquire the lock bail out since clearing is useless anyway
126 // (the app will write again to the profile).
127 //
128 // Note:
129 // This does not impact the this is not an issue for the profiling correctness.
130 // In case this is needed because of an app upgrade, profiles will still be
131 // eventually cleared by the app itself due to checksum mismatch.
132 // If this is needed because profman advised, then keeping the data around
133 // until the next run is again not an issue.
134 //
135 // If the app attempts to acquire a lock while we've held one here,
136 // it will simply skip the current write cycle.
137 return false;
138 }
139
140 bool truncated = ftruncate(ufd.get(), 0) == 0;
141 if (!truncated) {
142 PLOG(WARNING) << "Could not truncate " << profile;
143 }
144 if (flock(ufd.get(), LOCK_UN) != 0) {
145 PLOG(WARNING) << "Error unlocking profile " << profile;
146 }
147 return truncated;
148}
149
Calin Juravle114f0812017-03-08 19:05:07 -0800150// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800151// The location is the profile name for primary apks or the dex path for secondary dex files.
152static bool clear_reference_profile(const std::string& package_name, const std::string& location,
153 bool is_secondary_dex) {
154 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700155}
156
Calin Juravle114f0812017-03-08 19:05:07 -0800157// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800158// The location is the profile name for primary apks or the dex path for secondary dex files.
159static bool clear_current_profile(const std::string& package_name, const std::string& location,
160 userid_t user, bool is_secondary_dex) {
161 return clear_profile(create_current_profile_path(user, package_name, location,
162 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700163}
164
Calin Juravle114f0812017-03-08 19:05:07 -0800165// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800166// The location is the profile name for primary apks or the dex path for secondary dex files.
167bool clear_primary_reference_profile(const std::string& package_name,
168 const std::string& location) {
169 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800170}
171
172// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800173// The location is the profile name for primary apks or the dex path for secondary dex files.
174bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700175 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800176 // 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 -0700177 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
178 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800179 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700180 }
181 return success;
182}
183
Calin Juravle114f0812017-03-08 19:05:07 -0800184// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800185bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
186 userid_t user) {
187 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800188}
189
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700190static std::vector<std::string> SplitBySpaces(const std::string& str) {
191 if (str.empty()) {
192 return {};
193 }
194 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700195}
196
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800197// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
198// need to be performed between the fork and exec.
199class ExecVHelper {
200 public:
201 // Store a placeholder for the binary name.
202 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800203
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800204 void PrepareArgs(const std::string& bin) {
205 CHECK(!args_.empty());
206 CHECK(args_[0].empty());
207 args_[0] = bin;
208 // Write char* into array.
209 for (const std::string& arg : args_) {
210 argv_.push_back(arg.c_str());
211 }
212 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800213 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800214
215 [[ noreturn ]]
216 void Exec(int exit_code) {
217 execv(argv_[0], (char * const *)&argv_[0]);
218 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
219 exit(exit_code);
220 }
221
222 // Add an arg if it's not empty.
223 void AddArg(const std::string& arg) {
224 if (!arg.empty()) {
225 args_.push_back(arg);
226 }
227 }
228
229 // Add a runtime arg if it's not empty.
230 void AddRuntimeArg(const std::string& arg) {
231 if (!arg.empty()) {
232 args_.push_back("--runtime-arg");
233 args_.push_back(arg);
234 }
235 }
236
237 protected:
238 // Holder arrays for backing arg storage.
239 std::vector<std::string> args_;
240
241 // Argument poiners.
242 std::vector<const char*> argv_;
243};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700244
245static std::string MapPropertyToArg(const std::string& property,
246 const std::string& format,
247 const std::string& default_value = "") {
248 std::string prop = GetProperty(property, default_value);
249 if (!prop.empty()) {
250 return StringPrintf(format.c_str(), prop.c_str());
251 }
252 return "";
253}
254
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700255static std::string MapPropertyToArgWithBackup(const std::string& property,
256 const std::string& backupProperty,
257 const std::string& format,
258 const std::string& default_value = "") {
259 std::string value = GetProperty(property, default_value);
260 if (!value.empty()) {
261 return StringPrintf(format.c_str(), value.c_str());
262 }
263 return MapPropertyToArg(backupProperty, format, default_value);
264}
265
Calin Juravlef74a7372019-02-28 20:29:41 -0800266// Determines which binary we should use for execution (the debug or non-debug version).
267// e.g. dex2oatd vs dex2oat
268static const char* select_execution_binary(const char* binary, const char* debug_binary,
269 bool background_job_compile) {
270 return select_execution_binary(
271 binary,
272 debug_binary,
273 background_job_compile,
274 is_debug_runtime(),
275 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
276 is_debuggable_build());
277}
278
279// Determines which binary we should use for execution (the debug or non-debug version).
280// e.g. dex2oatd vs dex2oat
281// This is convenient method which is much easier to test because it doesn't read
282// system properties.
283const char* select_execution_binary(
284 const char* binary,
285 const char* debug_binary,
286 bool background_job_compile,
287 bool is_debug_runtime,
288 bool is_release,
289 bool is_debuggable_build) {
290 // Do not use debug binaries for release candidates (to give more soak time).
291 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
292
293 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
294 // the file is present (it may not be on images with very little space available).
295 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
296
297 return useDebug ? debug_binary : binary;
298}
299
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000300// Namespace for Android Runtime flags applied during boot time.
301static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
302// Feature flag name for running the JIT in Zygote experiment, b/119800099.
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000303static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
304// Location of the JIT Zygote image.
305static const char* kJitZygoteImage =
306 "boot.art:/nonx/boot-framework.art!/system/etc/boot-image.prof";
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000307
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700308// Phenotype property name for enabling profiling the boot class path.
309static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
310
Calin Juravlef85ddb92020-05-01 14:05:40 -0700311static bool IsBootClassPathProfilingEnable() {
312 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
313 profile_boot_class_path =
314 server_configurable_flags::GetServerConfigurableFlag(
315 RUNTIME_NATIVE_BOOT_NAMESPACE,
316 PROFILE_BOOT_CLASS_PATH,
317 /*default_value=*/ profile_boot_class_path);
318 return profile_boot_class_path == "true";
319}
320
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800321class RunDex2Oat : public ExecVHelper {
322 public:
Victor Hsiehe98e6512020-08-10 15:39:22 -0700323 RunDex2Oat(const char* dex2oat_bin,
324 int zip_fd,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800325 int oat_fd,
326 int input_vdex_fd,
327 int output_vdex_fd,
328 int image_fd,
329 const char* input_file_name,
330 const char* output_file_name,
331 int swap_fd,
332 const char* instruction_set,
333 const char* compiler_filter,
334 bool debuggable,
335 bool post_bootcomplete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700336 bool for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800337 int profile_fd,
338 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000339 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800340 int target_sdk_version,
341 bool enable_hidden_api_checks,
342 bool generate_compact_dex,
343 int dex_metadata_fd,
Victor Hsieh8948a862020-08-07 11:30:55 -0700344 bool use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800345 const char* compilation_reason) {
346 // Get the relative path to the input file.
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700347 std::string input_basename = Basename(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
350 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700351
Patrick Baumann2271b3e2020-04-14 17:03:00 -0700352 std::string threads_format = "-j%s";
353 std::string dex2oat_threads_arg = post_bootcomplete
354 ? (for_restore
355 ? MapPropertyToArgWithBackup(
356 "dalvik.vm.restore-dex2oat-threads",
357 "dalvik.vm.dex2oat-threads",
358 threads_format)
359 : MapPropertyToArg("dalvik.vm.dex2oat-threads", threads_format))
360 : MapPropertyToArg("dalvik.vm.boot-dex2oat-threads", threads_format);
361 std::string cpu_set_format = "--cpu-set=%s";
362 std::string dex2oat_cpu_set_arg = post_bootcomplete
363 ? (for_restore
364 ? MapPropertyToArgWithBackup(
365 "dalvik.vm.restore-dex2oat-cpu-set",
366 "dalvik.vm.dex2oat-cpu-set",
367 cpu_set_format)
368 : MapPropertyToArg("dalvik.vm.dex2oat-cpu-set", cpu_set_format))
369 : MapPropertyToArg("dalvik.vm.boot-dex2oat-cpu-set", cpu_set_format);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700370
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000371 std::string bootclasspath;
372 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
373 if (dex2oat_bootclasspath != nullptr) {
374 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
375 }
376 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
377 // BOOTCLASSPATH.
378
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800379 const std::string dex2oat_isa_features_key =
380 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
381 std::string instruction_set_features_arg =
382 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700383
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800384 const std::string dex2oat_isa_variant_key =
385 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
386 std::string instruction_set_variant_arg =
387 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700388
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800389 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700390
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800391 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
392 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
393 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700394
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800395 // If we are booting without the real /data, don't spend time compiling.
396 std::string vold_decrypt = GetProperty("vold.decrypt", "");
397 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
398 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700399
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100400 std::string updatable_bcp_packages =
401 MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
402 "--updatable-bcp-packages-file=%s");
403 if (updatable_bcp_packages.empty()) {
404 // Make dex2oat fail by providing non-existent file name.
405 updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
406 }
407
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800408 std::string resolve_startup_string_arg =
409 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
410 "--resolve-startup-const-strings=%s");
411 if (resolve_startup_string_arg.empty()) {
412 // If empty, fall back to system property.
413 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800414 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
415 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800416 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800417
418 const std::string image_block_size_arg =
419 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
420 "--max-image-block-size=%s");
421
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800422 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700423
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800424 std::string image_format_arg;
425 if (image_fd >= 0) {
426 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000427 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000428
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800429 std::string dex2oat_large_app_threshold_arg =
430 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000431
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800432 bool generate_minidebug_info = kEnableMinidebugInfo &&
433 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000434
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000435 std::string boot_image;
Victor Hsieh8948a862020-08-07 11:30:55 -0700436 if (use_jitzygote_image) {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000437 boot_image = StringPrintf("--boot-image=%s", kJitZygoteImage);
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000438 } else {
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000439 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "--boot-image=%s");
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000440 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000441
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800442 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
443 // use arraysize instead.
444 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700445 std::string zip_location_arg = StringPrintf("--zip-location=%s", input_basename.c_str());
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800446 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
447 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
448 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
449 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
450 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
451 std::string dex2oat_compiler_filter_arg;
452 std::string dex2oat_swap_fd;
453 std::string dex2oat_image_fd;
454 std::string target_sdk_version_arg;
455 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000456 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800457 }
458 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000459 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800460 if (class_loader_context != nullptr) {
461 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
462 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000463 if (!class_loader_context_fds.empty()) {
464 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
465 class_loader_context_fds.c_str());
466 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800467 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000468
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800469 if (swap_fd >= 0) {
470 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
471 }
472 if (image_fd >= 0) {
473 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
474 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000475
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800476 // Compute compiler filter.
477 bool have_dex2oat_relocation_skip_flag = false;
478 if (skip_compilation) {
479 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
480 have_dex2oat_relocation_skip_flag = true;
481 } else if (compiler_filter != nullptr) {
482 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
483 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000484
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800485 if (dex2oat_compiler_filter_arg.empty()) {
486 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
487 "--compiler-filter=%s");
488 }
489
490 // Check whether all apps should be compiled debuggable.
491 if (!debuggable) {
492 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
493 }
494 std::string profile_arg;
495 if (profile_fd != -1) {
496 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
497 }
498
499 // Get the directory of the apk to pass as a base classpath directory.
500 std::string base_dir;
501 std::string apk_dir(input_file_name);
502 unsigned long dir_index = apk_dir.rfind('/');
503 bool has_base_dir = dir_index != std::string::npos;
504 if (has_base_dir) {
505 apk_dir = apk_dir.substr(0, dir_index);
506 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
507 }
508
509 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
510
511 std::string compilation_reason_arg = compilation_reason == nullptr
512 ? ""
513 : std::string("--compilation-reason=") + compilation_reason;
514
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700515 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, input_basename.c_str(), output_file_name);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800516
517 // Disable cdex if update input vdex is true since this combination of options is not
518 // supported.
519 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
520
521 AddArg(zip_fd_arg);
522 AddArg(zip_location_arg);
523 AddArg(input_vdex_fd_arg);
524 AddArg(output_vdex_fd_arg);
525 AddArg(oat_fd_arg);
526 AddArg(oat_location_arg);
527 AddArg(instruction_set_arg);
528
529 AddArg(instruction_set_variant_arg);
530 AddArg(instruction_set_features_arg);
531
Nicolas Geoffray5a4c4e92020-02-07 11:37:34 +0000532 AddArg(boot_image);
533
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000534 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800535 AddRuntimeArg(dex2oat_Xms_arg);
536 AddRuntimeArg(dex2oat_Xmx_arg);
537
Vladimir Marko79dc3c62020-04-06 10:38:58 +0100538 AddArg(updatable_bcp_packages);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800539 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800540 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800541 AddArg(dex2oat_compiler_filter_arg);
542 AddArg(dex2oat_threads_arg);
Orion Hodson45837462019-11-14 18:20:17 +0000543 AddArg(dex2oat_cpu_set_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800544 AddArg(dex2oat_swap_fd);
545 AddArg(dex2oat_image_fd);
546
547 if (generate_debug_info) {
548 AddArg("--generate-debug-info");
549 }
550 if (debuggable) {
551 AddArg("--debuggable");
552 }
553 AddArg(image_format_arg);
554 AddArg(dex2oat_large_app_threshold_arg);
555
556 if (have_dex2oat_relocation_skip_flag) {
557 AddRuntimeArg(dex2oat_norelocation);
558 }
559 AddArg(profile_arg);
560 AddArg(base_dir);
561 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000562 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800563 if (generate_minidebug_info) {
564 AddArg(kMinidebugDex2oatFlag);
565 }
566 if (disable_cdex) {
567 AddArg(kDisableCompactDexFlag);
568 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000569 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800570 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100571 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800572 }
573
574 if (dex_metadata_fd > -1) {
575 AddArg(dex_metadata_fd_arg);
576 }
577
578 AddArg(compilation_reason_arg);
579
580 // Do not add args after dex2oat_flags, they should override others for debugging.
581 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
582
583 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000584 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800585};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700586
587/*
588 * Whether dexopt should use a swap file when compiling an APK.
589 *
590 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
591 * itself, anyways).
592 *
593 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
594 *
595 * Otherwise, return true if this is a low-mem device.
596 *
597 * Otherwise, return default value.
598 */
599static bool kAlwaysProvideSwapFile = false;
600static bool kDefaultProvideSwapFile = true;
601
602static bool ShouldUseSwapFileForDexopt() {
603 if (kAlwaysProvideSwapFile) {
604 return true;
605 }
606
607 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700608 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
609 if (!dex2oat_prop_buf.empty()) {
610 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611 }
612
613 // Shortcut for default value. This is an implementation optimization for the process sketched
614 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
615 // as low-mem is never returning false. The compiler will optimize this away if it can.
616 if (kDefaultProvideSwapFile) {
617 return true;
618 }
619
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700620 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700621 return true;
622 }
623
624 // Default value must be false here.
625 return kDefaultProvideSwapFile;
626}
627
Richard Uhler76cc0272016-12-08 10:46:35 +0000628static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700629 if (set_to_bg) {
630 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800631 PLOG(ERROR) << "set_sched_policy failed";
632 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 }
634 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800635 PLOG(ERROR) << "setpriority failed";
636 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700637 }
638 }
639}
640
Calin Juravle29591732017-11-20 17:46:19 -0800641static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
642 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800643 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800644 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800645 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800646 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800647 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700648 }
Calin Juravle114f0812017-03-08 19:05:07 -0800649 // Profiles should belong to the app; make sure of that by giving ownership to
650 // the app uid. If we cannot do that, there's no point in returning the fd
651 // since dex2oat/profman will fail with SElinux denials.
652 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000653 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800654 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800655 }
Calin Juravle29591732017-11-20 17:46:19 -0800656 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800657}
658
Calin Juravle29591732017-11-20 17:46:19 -0800659static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800660 // Do not follow symlinks when opening a profile:
661 // - primary profiles should not contain symlinks in their paths
662 // - secondary dex paths should have been already resolved and validated
663 flags |= O_NOFOLLOW;
664
Calin Juravle29591732017-11-20 17:46:19 -0800665 // Check if we need to create the profile
666 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
667 unique_fd fd;
668 if ((flags & O_CREAT) != 0) {
669 fd = create_profile(uid, profile, flags);
670 } else {
671 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
672 }
673
Calin Juravle114f0812017-03-08 19:05:07 -0800674 if (fd.get() < 0) {
675 if (errno != ENOENT) {
676 // Profiles might be missing for various reasons. For example, in a
677 // multi-user environment, the profile directory for one user can be created
678 // after we start a merge. In this case the current profile for that user
679 // will not be found.
680 // Also, the secondary dex profiles might be deleted by the app at any time,
681 // so we can't we need to prepare if they are missing.
682 PLOG(ERROR) << "Failed to open profile " << profile;
683 }
684 return invalid_unique_fd();
685 }
686
Jeff Sharkey90aff262016-12-12 14:28:24 -0700687 return fd;
688}
689
Calin Juravle824a64d2018-01-18 20:23:17 -0800690static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
691 const std::string& location, bool is_secondary_dex) {
692 std::string profile = create_current_profile_path(user, package_name, location,
693 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800694 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800695}
696
Calin Juravle824a64d2018-01-18 20:23:17 -0800697static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
698 const std::string& location, bool read_write, bool is_secondary_dex) {
699 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800700 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
701}
702
703static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800704 const std::string& location) {
705 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800706 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800707}
708
Calin Juravle824a64d2018-01-18 20:23:17 -0800709static void open_profile_files(uid_t uid, const std::string& package_name,
710 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800711 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800713 *reference_profile_fd = open_reference_profile(uid, package_name, location,
714 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700715
Calin Juravle114f0812017-03-08 19:05:07 -0800716 // For secondary dex files, we don't really need the user but we use it for sanity checks.
717 // Note: the user owning the dex file should be the current user.
718 std::vector<userid_t> users;
719 if (is_secondary_dex){
720 users.push_back(multiuser_get_user_id(uid));
721 } else {
722 users = get_known_users(/*volume_uuid*/ nullptr);
723 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700724 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800725 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
726 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800728 if (profile_fd.get() >= 0) {
729 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700730 }
731 }
732}
733
Calin Juravle76561322019-11-14 09:08:52 -0800734static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
735static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
736static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 2;
737static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
738static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
739static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
740static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700741
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800742class RunProfman : public ExecVHelper {
743 public:
744 void SetupArgs(const std::vector<unique_fd>& profile_fds,
745 const unique_fd& reference_profile_fd,
746 const std::vector<unique_fd>& apk_fds,
747 const std::vector<std::string>& dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800748 bool copy_and_update,
749 bool for_snapshot,
750 bool for_boot_image) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800751
752 // TODO(calin): Assume for now we run in the bg compile job (which is in
753 // most of the invocation). With the current data flow, is not very easy or
754 // clean to discover this in RunProfman (it will require quite a messy refactoring).
755 const char* profman_bin = select_execution_binary(
756 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700757
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800758 if (copy_and_update) {
759 CHECK_EQ(1u, profile_fds.size());
760 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000761 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800762 if (reference_profile_fd != -1) {
763 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000764 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800765
766 for (const unique_fd& fd : profile_fds) {
767 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
768 }
769
770 for (const unique_fd& fd : apk_fds) {
771 AddArg("--apk-fd=" + std::to_string(fd.get()));
772 }
773
774 for (const std::string& dex_location : dex_locations) {
775 AddArg("--dex-location=" + dex_location);
776 }
777
778 if (copy_and_update) {
779 AddArg("--copy-and-update-profile-key");
780 }
781
Calin Juravle78728f32019-11-08 17:55:46 -0800782 if (for_snapshot) {
783 AddArg("--force-merge");
784 }
785
786 if (for_boot_image) {
787 AddArg("--boot-image-merge");
788 }
789
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800790 // Do not add after dex2oat_flags, they should override others for debugging.
791 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800792 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700793
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800794 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
795 const unique_fd& reference_profile_fd,
796 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravle78728f32019-11-08 17:55:46 -0800797 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
798 bool for_snapshot = false,
799 bool for_boot_image = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800800 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800801 reference_profile_fd,
802 apk_fds,
803 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800804 /*copy_and_update=*/ false,
805 for_snapshot,
806 for_boot_image);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800807 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800809 void SetupCopyAndUpdate(unique_fd&& profile_fd,
810 unique_fd&& reference_profile_fd,
811 unique_fd&& apk_fd,
812 const std::string& dex_location) {
813 // The fds need to stay open longer than the scope of the function, so put them into a local
814 // variable vector.
815 profiles_fd_.push_back(std::move(profile_fd));
816 apk_fds_.push_back(std::move(apk_fd));
817 reference_profile_fd_ = std::move(reference_profile_fd);
818 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800819 SetupArgs(profiles_fd_,
820 reference_profile_fd_,
821 apk_fds_,
822 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800823 /*copy_and_update=*/true,
824 /*for_snapshot*/false,
825 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800826 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000827
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800828 void SetupDump(const std::vector<unique_fd>& profiles_fd,
829 const unique_fd& reference_profile_fd,
830 const std::vector<std::string>& dex_locations,
831 const std::vector<unique_fd>& apk_fds,
832 const unique_fd& output_fd) {
833 AddArg("--dump-only");
834 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800835 SetupArgs(profiles_fd,
836 reference_profile_fd,
837 apk_fds,
838 dex_locations,
Calin Juravle78728f32019-11-08 17:55:46 -0800839 /*copy_and_update=*/false,
840 /*for_snapshot*/false,
841 /*for_boot_image*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800842 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000843
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800844 void Exec() {
845 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
846 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000847
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800848 private:
849 unique_fd reference_profile_fd_;
850 std::vector<unique_fd> profiles_fd_;
851 std::vector<unique_fd> apk_fds_;
852};
Mathieu Chartier31636522018-11-09 23:53:07 +0000853
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800854
Calin Juravlef63d4792018-01-30 17:43:34 +0000855
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800857// The location is the package name for primary apks or the dex path for secondary dex files.
858// Returns true if there is enough information in the current profiles that makes it
859// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700860// If the return value is true all the current profiles would have been merged into
861// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800862static bool analyze_profiles(uid_t uid, const std::string& package_name,
863 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800864 std::vector<unique_fd> profiles_fd;
865 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800866 open_profile_files(uid, package_name, location, is_secondary_dex,
867 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800868 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700869 // Skip profile guided compilation because no profiles were found.
870 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 return false;
872 }
873
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800874 RunProfman profman_merge;
Calin Juravlef85ddb92020-05-01 14:05:40 -0700875 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
876 const std::vector<std::string>& dex_locations = std::vector<std::string>();
877 profman_merge.SetupMerge(
878 profiles_fd,
879 reference_profile_fd,
880 apk_fds,
881 dex_locations,
882 /* for_snapshot= */ false,
883 IsBootClassPathProfilingEnable());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 pid_t pid = fork();
885 if (pid == 0) {
886 /* child -- drop privileges before continuing */
887 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800888 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700889 }
890 /* parent */
891 int return_code = wait_child(pid);
892 bool need_to_compile = false;
893 bool should_clear_current_profiles = false;
894 bool should_clear_reference_profile = false;
895 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800896 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700897 } else {
898 return_code = WEXITSTATUS(return_code);
899 switch (return_code) {
900 case PROFMAN_BIN_RETURN_CODE_COMPILE:
901 need_to_compile = true;
902 should_clear_current_profiles = true;
903 should_clear_reference_profile = false;
904 break;
905 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
906 need_to_compile = false;
907 should_clear_current_profiles = false;
908 should_clear_reference_profile = false;
909 break;
910 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800911 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700912 need_to_compile = false;
913 should_clear_current_profiles = true;
914 should_clear_reference_profile = true;
915 break;
916 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
917 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
918 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800919 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700920 need_to_compile = false;
921 should_clear_current_profiles = false;
922 should_clear_reference_profile = false;
923 break;
Calin Juravle76561322019-11-14 09:08:52 -0800924 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
925 need_to_compile = false;
926 should_clear_current_profiles = true;
927 should_clear_reference_profile = true;
928 break;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700929 default:
930 // Unknown return code or error. Unlink profiles.
Calin Juravle78728f32019-11-08 17:55:46 -0800931 LOG(WARNING) << "Unexpected error code while processing profiles for location "
Calin Juravle114f0812017-03-08 19:05:07 -0800932 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 need_to_compile = false;
934 should_clear_current_profiles = true;
935 should_clear_reference_profile = true;
936 break;
937 }
938 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800939
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800941 if (is_secondary_dex) {
942 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800943 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
944 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800945 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800946 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800947 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700948 }
949 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800950 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700951 }
952 return need_to_compile;
953}
954
Calin Juravle114f0812017-03-08 19:05:07 -0800955// Decides if profile guided compilation is needed or not based on existing profiles.
956// The analysis is done for the primary apks of the given package.
957// Returns true if there is enough information in the current profiles that makes it
958// worth to recompile the package.
959// If the return value is true all the current profiles would have been merged into
960// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800961bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
962 const std::string& profile_name) {
963 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800964}
965
Calin Juravle408cd4a2018-01-20 23:34:18 -0800966bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
967 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800968 std::vector<unique_fd> profile_fds;
969 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800970 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
971 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972
Calin Juravle408cd4a2018-01-20 23:34:18 -0800973 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800974 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700975
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800976 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700977 const bool has_profiles = !profile_fds.empty();
978
979 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800980 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700981 return false;
982 }
983
Calin Juravle114f0812017-03-08 19:05:07 -0800984 unique_fd output_fd(open(out_file_name.c_str(),
985 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700986 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800987 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988 return false;
989 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800990
Jeff Sharkey90aff262016-12-12 14:28:24 -0700991 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800992 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800993 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
994 if (apk_fd == -1) {
995 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
996 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700997 }
Victor Hsieh76f19ba2020-08-10 14:37:26 -0700998 dex_locations.push_back(Basename(code_path));
Calin Juravle408cd4a2018-01-20 23:34:18 -0800999 apk_fds.push_back(std::move(apk_fd));
1000
Jeff Sharkey90aff262016-12-12 14:28:24 -07001001
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001002 RunProfman profman_dump;
1003 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 pid_t pid = fork();
1005 if (pid == 0) {
1006 /* child -- drop privileges before continuing */
1007 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001008 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 }
1010 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001011 int return_code = wait_child(pid);
1012 if (!WIFEXITED(return_code)) {
1013 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1014 << return_code;
1015 return false;
1016 }
1017 return true;
1018}
1019
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001020bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001021 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001022 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1023 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001024 package_name,
1025 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001026 /*read_write*/ true,
1027 /*secondary*/ false));
1028 if (in_fd.get() < 0) {
1029 PLOG(WARNING) << "Could not open profile " << system_profile;
1030 return false;
1031 }
1032 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001033 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001034 return false;
1035 }
1036
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001037 // As a security measure we want to write the profile information with the reduced capabilities
1038 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001039 pid_t pid = fork();
1040 if (pid == 0) {
1041 /* child -- drop privileges before continuing */
1042 drop_capabilities(packageUid);
1043
1044 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1045 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001046 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001047 }
1048 // This implies that the app owning this profile is running
1049 // (and has acquired the lock).
1050 //
1051 // The app never acquires the lock for the reference profiles of primary apks.
1052 // Only dex2oat from installd will do that. Since installd is single threaded
1053 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001054 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001055 return false;
1056 }
1057
1058 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1059 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001060 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001061 }
1062
1063 // Copy over data.
1064 static constexpr size_t kBufferSize = 4 * 1024;
1065 char buffer[kBufferSize];
1066 while (true) {
1067 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1068 if (bytes == 0) {
1069 break;
1070 }
1071 write(out_fd.get(), buffer, bytes);
1072 }
1073 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001074 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001075 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001076 // Use _exit since we don't want to run the global destructors in the child.
1077 // b/62597429
1078 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001079 }
1080 /* parent */
1081 int return_code = wait_child(pid);
1082 return return_code == 0;
1083}
1084
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1086 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1087 if (EndsWith(oat_path, ".dex")) {
1088 std::string new_path = oat_path;
1089 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001090 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001091 return new_path;
1092 }
1093
1094 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1095 // case (where the base name will have an extension for the B artifact).
1096 size_t odex_pos = oat_path.rfind(".odex");
1097 if (odex_pos != std::string::npos) {
1098 std::string new_path = oat_path;
1099 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1100 CHECK_NE(new_path.find(new_ext), std::string::npos);
1101 return new_path;
1102 }
1103
1104 // Don't know how to handle this.
1105 return "";
1106}
1107
1108// Translate the given oat path to an art (app image) path. An empty string
1109// denotes an error.
1110static std::string create_image_filename(const std::string& oat_path) {
1111 return replace_file_extension(oat_path, ".art");
1112}
1113
1114// Translate the given oat path to a vdex path. An empty string denotes an error.
1115static std::string create_vdex_filename(const std::string& oat_path) {
1116 return replace_file_extension(oat_path, ".vdex");
1117}
1118
Jeff Sharkey90aff262016-12-12 14:28:24 -07001119static int open_output_file(const char* file_name, bool recreate, int permissions) {
1120 int flags = O_RDWR | O_CREAT;
1121 if (recreate) {
1122 if (unlink(file_name) < 0) {
1123 if (errno != ENOENT) {
1124 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1125 }
1126 }
1127 flags |= O_EXCL;
1128 }
1129 return open(file_name, flags, permissions);
1130}
1131
Calin Juravle2289c0a2017-02-15 12:44:14 -08001132static bool set_permissions_and_ownership(
1133 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1134 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1135 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001136 if (fchmod(fd,
1137 S_IRUSR|S_IWUSR|S_IRGRP |
1138 (is_public ? S_IROTH : 0)) < 0) {
1139 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1140 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001141 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001142 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1143 return false;
1144 }
1145 return true;
1146}
1147
1148static bool IsOutputDalvikCache(const char* oat_dir) {
1149 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1150 // into '!'. Play it safe by handling it both.
1151 // TODO: ensure we never get null.
1152 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1153 return oat_dir == nullptr || oat_dir[0] == '!';
1154}
1155
Calin Juravled23dee72017-07-06 16:29:11 -07001156// Best-effort check whether we can fit the the path into our buffers.
1157// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1158// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1159// extension to the cache path (5 bytes).
1160// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1161static bool validate_dex_path_size(const std::string& dex_path) {
1162 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1163 LOG(ERROR) << "dex_path too long: " << dex_path;
1164 return false;
1165 }
1166 return true;
1167}
1168
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001170 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001171 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001172 return false;
1173 }
1174
1175 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001176 // Oat dirs for secondary dex files are already validated.
1177 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001178 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1179 return false;
1180 }
1181 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1182 return false;
1183 }
1184 } else {
1185 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1186 return false;
1187 }
1188 }
1189 return true;
1190}
1191
1192// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1193// on destruction. It will also run the given cleanup (unless told not to) after closing.
1194//
1195// Usage example:
1196//
Calin Juravle7a570e82017-01-14 16:23:30 -08001197// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001198// [name]() {
1199// unlink(name.c_str());
1200// });
1201// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1202// wrapper if captured as a reference.
1203//
1204// if (file.get() == -1) {
1205// // Error opening...
1206// }
1207//
1208// ...
1209// if (error) {
1210// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1211// // and delete the file (after the fd is closed).
1212// return -1;
1213// }
1214//
1215// (Success case)
1216// file.SetCleanup(false);
1217// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1218// // (leaving the file around; after the fd is closed).
1219//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001220class Dex2oatFileWrapper {
1221 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001222 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001223 }
1224
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1226 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1227
1228 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1229 value_ = other.value_;
1230 cleanup_ = other.cleanup_;
1231 do_cleanup_ = other.do_cleanup_;
1232 auto_close_ = other.auto_close_;
1233 other.release();
1234 }
1235
1236 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1237 value_ = other.value_;
1238 cleanup_ = other.cleanup_;
1239 do_cleanup_ = other.do_cleanup_;
1240 auto_close_ = other.auto_close_;
1241 other.release();
1242 return *this;
1243 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001244
1245 ~Dex2oatFileWrapper() {
1246 reset(-1);
1247 }
1248
1249 int get() {
1250 return value_;
1251 }
1252
1253 void SetCleanup(bool cleanup) {
1254 do_cleanup_ = cleanup;
1255 }
1256
1257 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001258 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001259 close(value_);
1260 }
1261 if (do_cleanup_ && cleanup_ != nullptr) {
1262 cleanup_();
1263 }
1264
1265 value_ = new_value;
1266 }
1267
Calin Juravle7a570e82017-01-14 16:23:30 -08001268 void reset(int new_value, std::function<void ()> new_cleanup) {
1269 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001270 close(value_);
1271 }
1272 if (do_cleanup_ && cleanup_ != nullptr) {
1273 cleanup_();
1274 }
1275
1276 value_ = new_value;
1277 cleanup_ = new_cleanup;
1278 }
1279
Calin Juravle7a570e82017-01-14 16:23:30 -08001280 void DisableAutoClose() {
1281 auto_close_ = false;
1282 }
1283
Jeff Sharkey90aff262016-12-12 14:28:24 -07001284 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001285 void release() {
1286 value_ = -1;
1287 do_cleanup_ = false;
1288 cleanup_ = nullptr;
1289 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001290 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001294};
1295
Calin Juravle7a570e82017-01-14 16:23:30 -08001296// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001297Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1298 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001299
Calin Juravle7a570e82017-01-14 16:23:30 -08001300 const std::string image_path = create_image_filename(out_oat_path);
1301 if (image_path.empty()) {
1302 // Happens when the out_oat_path has an unknown extension.
1303 return Dex2oatFileWrapper();
1304 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001305
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001306 // In case there is a stale image, remove it now. Ignore any error.
1307 unlink(image_path.c_str());
1308
1309 // Not enabled, exit.
1310 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001311 return Dex2oatFileWrapper();
1312 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001313 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1314 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001315 return Dex2oatFileWrapper();
1316 }
1317 // Recreate is true since we do not want to modify a mapped image. If the app is
1318 // already running and we modify the image file, it can cause crashes (b/27493510).
1319 Dex2oatFileWrapper wrapper_fd(
1320 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1321 [image_path]() { unlink(image_path.c_str()); });
1322 if (wrapper_fd.get() < 0) {
1323 // Could not create application image file. Go on since we can compile without it.
1324 LOG(ERROR) << "installd could not create '" << image_path
1325 << "' for image file during dexopt";
1326 // If we have a valid image file path but no image fd, explicitly erase the image file.
1327 if (unlink(image_path.c_str()) < 0) {
1328 if (errno != ENOENT) {
1329 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1330 }
1331 }
1332 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001333 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001334 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1335 wrapper_fd.reset(-1);
1336 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001337
Calin Juravle7a570e82017-01-14 16:23:30 -08001338 return wrapper_fd;
1339}
1340
1341// Creates the dexopt swap file if necessary and return its fd.
1342// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001343unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001344 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001345 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001346 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001347 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001348 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001349 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001350 if (swap_fd.get() < 0) {
1351 // Could not create swap file. Optimistically go on and hope that we can compile
1352 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001353 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001354 } else {
1355 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001356 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001357 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1358 }
1359 }
1360 return swap_fd;
1361}
1362
1363// Opens the reference profiles if needed.
1364// 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 -08001365Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001366 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001367 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001368 // If we are not profile guided compilation, or we are compiling system server
1369 // do not bother to open the profiles; we won't be using them.
1370 if (!profile_guided || (pkgname[0] == '*')) {
1371 return Dex2oatFileWrapper();
1372 }
1373
1374 // If this is a secondary dex path which is public do not open the profile.
1375 // We cannot compile public secondary dex paths with profiles. That's because
1376 // it will expose how the dex files are used by their owner.
1377 //
1378 // Note that the PackageManager is responsible to set the is_public flag for
1379 // primary apks and we do not check it here. In some cases, e.g. when
1380 // compiling with a public profile from the .dm file the PackageManager will
1381 // set is_public toghether with the profile guided compilation.
1382 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001383 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001384 }
Calin Juravle114f0812017-03-08 19:05:07 -08001385
1386 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001387 std::string location;
1388 if (is_secondary_dex) {
1389 location = dex_path;
1390 } else {
1391 if (profile_name == nullptr) {
1392 // This path is taken for system server re-compilation lunched from ZygoteInit.
1393 return Dex2oatFileWrapper();
1394 } else {
1395 location = profile_name;
1396 }
1397 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001398 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1399 is_secondary_dex);
1400 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1401 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001402 };
1403 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001404}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001405
Calin Juravle7a570e82017-01-14 16:23:30 -08001406// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1407// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001408bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001409 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001410 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001411 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1412 CHECK(in_vdex_wrapper_fd != nullptr);
1413 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001414 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1415 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001416 char in_odex_path[PKG_PATH_MAX];
1417 int dexopt_action = abs(dexopt_needed);
1418 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001419 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001420
1421 // Infer the name of the output VDEX.
1422 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1423 if (out_vdex_path_str.empty()) {
1424 return false;
1425 }
1426
1427 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001428 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001429 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1430 const char* path = nullptr;
1431 if (is_odex_location) {
1432 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1433 path = in_odex_path;
1434 } else {
1435 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001436 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001437 }
1438 } else {
1439 path = out_oat_path;
1440 }
1441 in_vdex_path_str = create_vdex_filename(path);
1442 if (in_vdex_path_str.empty()) {
1443 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001444 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001445 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001446 // We can update in place when all these conditions are met:
1447 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1448 // on /system typically cannot be updated in place).
1449 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1450 // cannot be currently used by a running process.
1451 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1452 // different vdex files to operate.
1453 update_vdex_in_place =
1454 (in_vdex_path_str == out_vdex_path_str) &&
1455 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1456 !profile_guided;
1457 if (update_vdex_in_place) {
1458 // Open the file read-write to be able to update it.
1459 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1460 if (in_vdex_wrapper_fd->get() == -1) {
1461 // If we failed to open the file, we cannot update it in place.
1462 update_vdex_in_place = false;
1463 }
1464 } else {
1465 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1466 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001467 }
1468
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001469 // If we are updating the vdex in place, we do not need to recreate a vdex,
1470 // and can use the same existing one.
1471 if (update_vdex_in_place) {
1472 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1473 // have bogus stale vdex files.
1474 out_vdex_wrapper_fd->reset(
1475 in_vdex_wrapper_fd->get(),
1476 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1477 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1478 // wrapper).
1479 in_vdex_wrapper_fd->DisableAutoClose();
1480 } else {
1481 out_vdex_wrapper_fd->reset(
1482 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1483 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1484 if (out_vdex_wrapper_fd->get() < 0) {
1485 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1486 return false;
1487 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001488 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001489 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001490 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001491 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1492 return false;
1493 }
1494
1495 // If we got here we successfully opened the vdex files.
1496 return true;
1497}
1498
1499// Opens the output oat file for the given apk.
1500// If successful it stores the output path into out_oat_path and returns true.
1501Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001502 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1503 char* out_oat_path) {
1504 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001505 return Dex2oatFileWrapper();
1506 }
1507 const std::string out_oat_path_str(out_oat_path);
1508 Dex2oatFileWrapper wrapper_fd(
1509 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1510 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1511 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001512 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001513 } else if (!set_permissions_and_ownership(
1514 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001515 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1516 wrapper_fd.reset(-1);
1517 }
1518 return wrapper_fd;
1519}
1520
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001521// Creates RDONLY fds for oat and vdex files, if exist.
1522// Returns false if it fails to create oat out path for the given apk path.
1523// Note that the method returns true even if the files could not be opened.
1524bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1525 const std::string& oat_dir,
1526 const std::string& instruction_set,
1527 bool is_secondary_dex,
1528 unique_fd* oat_file_fd,
1529 unique_fd* vdex_file_fd) {
1530 char oat_path[PKG_PATH_MAX];
1531 if (!create_oat_out_path(apk_path.c_str(),
1532 instruction_set.c_str(),
1533 oat_dir.c_str(),
1534 is_secondary_dex,
1535 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001536 LOG(ERROR) << "Could not create oat out path for "
1537 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001538 return false;
1539 }
1540 oat_file_fd->reset(open(oat_path, O_RDONLY));
1541 if (oat_file_fd->get() < 0) {
1542 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1543 }
1544
1545 std::string vdex_filename = create_vdex_filename(oat_path);
1546 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1547 if (vdex_file_fd->get() < 0) {
1548 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1549 }
1550
1551 return true;
1552}
1553
Calin Juravle7a570e82017-01-14 16:23:30 -08001554// Updates the access times of out_oat_path based on those from apk_path.
1555void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1556 struct stat input_stat;
1557 memset(&input_stat, 0, sizeof(input_stat));
1558 if (stat(apk_path, &input_stat) != 0) {
1559 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1560 return;
1561 }
1562
1563 struct utimbuf ut;
1564 ut.actime = input_stat.st_atime;
1565 ut.modtime = input_stat.st_mtime;
1566 if (utime(out_oat_path, &ut) != 0) {
1567 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1568 }
1569}
1570
Calin Juravle80a21252017-01-17 14:43:25 -08001571// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001572// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1573// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1574// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001575class RunDexoptAnalyzer : public ExecVHelper {
1576 public:
1577 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001578 int vdex_fd,
1579 int oat_fd,
1580 int zip_fd,
1581 const std::string& instruction_set,
1582 const std::string& compiler_filter,
1583 bool profile_was_updated,
1584 bool downgrade,
1585 const char* class_loader_context,
1586 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001587 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001588
1589 // We always run the analyzer in the background job.
1590 const char* dexoptanalyzer_bin = select_execution_binary(
1591 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001592
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001593 std::string dex_file_arg = "--dex-file=" + dex_file;
1594 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1595 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1596 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1597 std::string isa_arg = "--isa=" + instruction_set;
1598 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1599 const char* assume_profile_changed = "--assume-profile-changed";
1600 const char* downgrade_flag = "--downgrade";
1601 std::string class_loader_context_arg = "--class-loader-context=";
1602 if (class_loader_context != nullptr) {
1603 class_loader_context_arg += class_loader_context;
1604 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001605 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1606 if (!class_loader_context_fds.empty()) {
1607 class_loader_context_fds_arg += class_loader_context_fds;
1608 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001609
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001610 // program name, dex file, isa, filter
1611 AddArg(dex_file_arg);
1612 AddArg(isa_arg);
1613 AddArg(compiler_filter_arg);
1614 if (oat_fd >= 0) {
1615 AddArg(oat_fd_arg);
1616 }
1617 if (vdex_fd >= 0) {
1618 AddArg(vdex_fd_arg);
1619 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001620 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001621 if (profile_was_updated) {
1622 AddArg(assume_profile_changed);
1623 }
1624 if (downgrade) {
1625 AddArg(downgrade_flag);
1626 }
1627 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001628 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001629 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001630 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001631 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001632 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001633
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001634 PrepareArgs(dexoptanalyzer_bin);
1635 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001636
1637 // Dexoptanalyzer mode which flattens the given class loader context and
1638 // prints a list of its dex files in that flattened order.
1639 RunDexoptAnalyzer(const char* class_loader_context) {
1640 CHECK(class_loader_context != nullptr);
1641
1642 // We always run the analyzer in the background job.
1643 const char* dexoptanalyzer_bin = select_execution_binary(
1644 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1645
1646 AddArg("--flatten-class-loader-context");
1647 AddArg(std::string("--class-loader-context=") + class_loader_context);
1648 PrepareArgs(dexoptanalyzer_bin);
1649 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001650};
Calin Juravle80a21252017-01-17 14:43:25 -08001651
1652// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001653static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001654 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001655 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001656 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001657 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001658 return false;
1659 }
Calin Juravle114f0812017-03-08 19:05:07 -08001660 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001661
Calin Juravle80a21252017-01-17 14:43:25 -08001662 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001663 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1664 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001665 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001666 return false;
1667 }
1668
1669 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001670 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001671
Calin Juravle7d765462017-09-04 15:57:10 -07001672 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001673 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001674 return false;
1675 }
1676
1677 return true;
1678}
1679
Calin Juravle7d765462017-09-04 15:57:10 -07001680// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1681// secondary dex files. This return codes are returned by the child process created for
1682// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001683
Andreas Gampe194fe422018-02-28 20:16:19 -08001684enum DexoptAnalyzerSkipCodes {
1685 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001686 // Specific errors are encoded in the name.
1687 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1688 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1689 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1690 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1691 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001692 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001693 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001694};
Calin Juravle7d765462017-09-04 15:57:10 -07001695
1696// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001697// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1698// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001699// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1700// of dexoptanalyzer.
1701static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001702 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001703 // The result values are defined in dexoptanalyzer.
1704 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001705 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001706 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001707 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001708 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001709 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001710 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001711 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001712 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001713 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1714 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001715 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1716 " Expected odex file status for secondary dex %s"
1717 " : dexoptanalyzer result=%d",
1718 dex_path.c_str(),
1719 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001720 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001721 }
1722
1723 // Use a second switch for enum switch-case analysis.
1724 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001725 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001726 // If the file does not exist there's no need for dexopt.
1727 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1728 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001729
1730 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1731 *error_msg = "Dexoptanalyzer path validation failed";
1732 return false;
1733 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1734 *error_msg = "Dexoptanalyzer open zip failed";
1735 return false;
1736 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1737 *error_msg = "Dexoptanalyzer dir preparation failed";
1738 return false;
1739 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1740 *error_msg = "Dexoptanalyzer open output failed";
1741 return false;
1742 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1743 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001744 return false;
1745 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001746
1747 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1748 dex_path.c_str(),
1749 result);
1750 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001751}
1752
Calin Juravle7d765462017-09-04 15:57:10 -07001753enum SecondaryDexAccess {
1754 kSecondaryDexAccessReadOk = 0,
1755 kSecondaryDexAccessDoesNotExist = 1,
1756 kSecondaryDexAccessPermissionError = 2,
1757 kSecondaryDexAccessIOError = 3
1758};
1759
1760static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1761 // Check if the path exists and can be read. If not, there's nothing to do.
1762 if (access(dex_path.c_str(), R_OK) == 0) {
1763 return kSecondaryDexAccessReadOk;
1764 } else {
1765 if (errno == ENOENT) {
1766 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1767 return kSecondaryDexAccessDoesNotExist;
1768 } else {
1769 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1770 return errno == EACCES
1771 ? kSecondaryDexAccessPermissionError
1772 : kSecondaryDexAccessIOError;
1773 }
1774 }
1775}
1776
1777static bool is_file_public(const std::string& filename) {
1778 struct stat file_stat;
1779 if (stat(filename.c_str(), &file_stat) == 0) {
1780 return (file_stat.st_mode & S_IROTH) != 0;
1781 }
1782 return false;
1783}
1784
1785// Create the oat file structure for the secondary dex 'dex_path' and assign
1786// the individual path component to the 'out_' parameters.
1787static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001788 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001789 size_t dirIndex = dex_path.rfind('/');
1790 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001791 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001792 return false;
1793 }
1794 // TODO(calin): we have similar computations in at lest 3 other places
1795 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1796 // using string append.
1797 std::string apk_dir = dex_path.substr(0, dirIndex);
1798 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1799 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1800
1801 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1802 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001803 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001804 return false;
1805 }
1806 return true;
1807}
1808
1809// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1810// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001811static bool validate_dexopt_storage_flags(int dexopt_flags,
1812 int* out_storage_flag,
1813 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001814 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1815 *out_storage_flag = FLAG_STORAGE_CE;
1816 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001817 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001818 return false;
1819 }
1820 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1821 *out_storage_flag = FLAG_STORAGE_DE;
1822 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001823 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001824 return false;
1825 }
1826 return true;
1827}
1828
David Brazdil4f6027a2019-03-19 11:44:21 +00001829static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1830 /* out */ std::vector<std::string>* context_dex_paths) {
1831 if (class_loader_context == nullptr) {
1832 return true;
1833 }
1834
1835 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1836
1837 // Pipe to get the hash result back from our child process.
1838 unique_fd pipe_read, pipe_write;
1839 if (!Pipe(&pipe_read, &pipe_write)) {
1840 PLOG(ERROR) << "Failed to create pipe";
1841 return false;
1842 }
1843
1844 pid_t pid = fork();
1845 if (pid == 0) {
1846 // child -- drop privileges before continuing.
1847 drop_capabilities(uid);
1848
1849 // Route stdout to `pipe_write`
1850 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1851 pipe_write.reset();
1852 pipe_read.reset();
1853
1854 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1855 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1856 }
1857
1858 /* parent */
1859 pipe_write.reset();
1860
1861 std::string str_dex_paths;
1862 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1863 PLOG(ERROR) << "Failed to read from pipe";
1864 return false;
1865 }
1866 pipe_read.reset();
1867
1868 int return_code = wait_child(pid);
1869 if (!WIFEXITED(return_code)) {
1870 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1871 return false;
1872 }
1873
1874 constexpr int kFlattenClassLoaderContextSuccess = 50;
1875 return_code = WEXITSTATUS(return_code);
1876 if (return_code != kFlattenClassLoaderContextSuccess) {
1877 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1878 return false;
1879 }
1880
1881 if (!str_dex_paths.empty()) {
1882 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1883 }
1884 return true;
1885}
1886
1887static int open_dex_paths(const std::vector<std::string>& dex_paths,
1888 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1889 for (const std::string& dex_path : dex_paths) {
1890 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1891 if (zip_fds->back().get() < 0) {
1892 *error_msg = StringPrintf(
1893 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1894 if (errno == ENOENT) {
1895 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1896 } else {
1897 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1898 }
1899 }
1900 }
1901 return 0;
1902}
1903
1904static std::string join_fds(const std::vector<unique_fd>& fds) {
1905 std::stringstream ss;
1906 bool is_first = true;
1907 for (const unique_fd& fd : fds) {
1908 if (is_first) {
1909 is_first = false;
1910 } else {
1911 ss << ":";
1912 }
1913 ss << fd.get();
1914 }
1915 return ss.str();
1916}
1917
Calin Juravlec9eab382017-01-25 01:17:17 -08001918// 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 -08001919// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1920// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001921// When returning true, the output parameters will be:
1922// - is_public_out: whether or not the oat file should not be made public
1923// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1924// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001925static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001926 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001927 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001928 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001929 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001930 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001931 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001932 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1933 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001934 return false;
1935 }
Calin Juravle7d765462017-09-04 15:57:10 -07001936 // Compute the oat dir as it's not easy to extract it from the child computation.
1937 char oat_path[PKG_PATH_MAX];
1938 char oat_dir[PKG_PATH_MAX];
1939 char oat_isa_dir[PKG_PATH_MAX];
1940 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001941 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1942 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001943 return false;
1944 }
Calin Juravle7d765462017-09-04 15:57:10 -07001945 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001946
Calin Juravle80a21252017-01-17 14:43:25 -08001947 pid_t pid = fork();
1948 if (pid == 0) {
1949 // child -- drop privileges before continuing.
1950 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001951
1952 // Validate the path structure.
1953 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1954 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001955 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001956 }
1957
1958 // Open the dex file.
1959 unique_fd zip_fd;
1960 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1961 if (zip_fd.get() < 0) {
1962 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001963 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001964 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001965 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001966 }
1967 }
1968
David Brazdil4f6027a2019-03-19 11:44:21 +00001969 // Open class loader context dex files.
1970 std::vector<unique_fd> context_zip_fds;
1971 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1972 if (open_dex_paths_rc != 0) {
1973 _exit(open_dex_paths_rc);
1974 }
1975
Calin Juravle7d765462017-09-04 15:57:10 -07001976 // Prepare the oat directories.
1977 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001978 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001979 }
1980
1981 // Open the vdex/oat files if any.
1982 unique_fd oat_file_fd;
1983 unique_fd vdex_file_fd;
1984 if (!maybe_open_oat_and_vdex_file(dex_path,
1985 *oat_dir_out,
1986 instruction_set,
1987 true /* is_secondary_dex */,
1988 &oat_file_fd,
1989 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001990 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001991 }
1992
1993 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001994 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1995 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001996
1997 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001998 // Note that we do not do it before the fork since opening the files is required to happen
1999 // after forking.
2000 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
2001 vdex_file_fd.get(),
2002 oat_file_fd.get(),
2003 zip_fd.get(),
2004 instruction_set,
2005 compiler_filter, profile_was_updated,
2006 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00002007 class_loader_context,
2008 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002009 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08002010 }
2011
2012 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08002013 int result = wait_child(pid);
2014 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002015 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
2016 dex_path.c_str(),
2017 result);
2018 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08002019 return false;
2020 }
2021 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07002022 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08002023 bool success = process_secondary_dexoptanalyzer_result(dex_path,
2024 result,
2025 dexopt_needed_out,
2026 error_msg);
2027 if (!success) {
2028 LOG(ERROR) << *error_msg;
2029 }
Calin Juravle7d765462017-09-04 15:57:10 -07002030
2031 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
2032
Calin Juravle80a21252017-01-17 14:43:25 -08002033 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07002034 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
2035 // makes the code simpler; force compilation is only needed during tests).
2036 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08002037 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07002038 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002039 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
2040 }
2041
Calin Juravle7d765462017-09-04 15:57:10 -07002042 // Check if we should make the oat file public.
2043 // Note that if the dex file is not public the compiled code cannot be made public.
2044 // It is ok to check this flag outside in the parent process.
2045 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2046
Calin Juravle80a21252017-01-17 14:43:25 -08002047 return success;
2048}
2049
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002050static std::string format_dexopt_error(int status, const char* dex_path) {
2051 if (WIFEXITED(status)) {
2052 int int_code = WEXITSTATUS(status);
2053 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2054 if (code_name != nullptr) {
2055 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2056 }
2057 }
2058 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002059}
2060
Calin Juravlec9eab382017-01-25 01:17:17 -08002061int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002062 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002063 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002064 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002065 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002066 CHECK(pkgname != nullptr);
2067 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002068 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002069 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2070 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002071
Calin Juravled23dee72017-07-06 16:29:11 -07002072 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002073 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002074 return -1;
2075 }
2076
2077 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002078 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2079 class_loader_context);
2080 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002081 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002082 }
2083
Calin Juravleebc8a792017-04-04 20:21:05 -07002084 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002085 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2086 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2087 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002088 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002089 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002090 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002091 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002092 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002093 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002094
2095 // Check if we're dealing with a secondary dex file and if we need to compile it.
2096 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002097 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002098 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002099 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2100 *error_msg = "Failed acquiring context dex paths";
2101 return -1; // We had an error, logged in the process method.
2102 }
2103
Calin Juravlec9eab382017-01-25 01:17:17 -08002104 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002105 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002106 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002107 oat_dir = oat_dir_str.c_str();
2108 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2109 return 0; // Nothing to do, report success.
2110 }
2111 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002112 if (error_msg->empty()) { // TODO: Make this a CHECK.
2113 *error_msg = "Failed processing secondary.";
2114 }
Calin Juravle80a21252017-01-17 14:43:25 -08002115 return -1; // We had an error, logged in the process method.
2116 }
2117 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002118 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002119 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002120 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2121 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2122 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002123
2124 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002125 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002126 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002127 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2128 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002129 return -1;
2130 }
2131
David Brazdil4f6027a2019-03-19 11:44:21 +00002132 // Open class loader context dex files.
2133 std::vector<unique_fd> context_input_fds;
2134 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2135 LOG(ERROR) << *error_msg;
2136 return -1;
2137 }
2138
Calin Juravle7a570e82017-01-14 16:23:30 -08002139 // Create the output OAT file.
2140 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002141 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002142 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002143 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002144 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002145 return -1;
2146 }
2147
2148 // Open vdex files.
2149 Dex2oatFileWrapper in_vdex_fd;
2150 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002151 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2152 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002153 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002154 return -1;
2155 }
2156
Calin Juravlecb556e32017-04-04 20:22:50 -07002157 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2158 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2159 // fully inherit their parent context).
2160 // Note that for primary apk the oat files are created before, in a separate installd
2161 // call which also does the restorecon. TODO(calin): unify the paths.
2162 if (is_secondary_dex) {
2163 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2164 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002165 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2166 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002167 return -1;
2168 }
2169 }
2170
Jeff Sharkey90aff262016-12-12 14:28:24 -07002171 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002172 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002173
Calin Juravle7a570e82017-01-14 16:23:30 -08002174 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002175 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002176 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002177
liulvping61907742018-08-21 09:36:52 +08002178 if (reference_profile_fd.get() == -1) {
2179 // We don't create an app image without reference profile since there is no speedup from
2180 // loading it in that case and instead will be a small overhead.
2181 generate_app_image = false;
2182 }
2183
2184 // Create the app image file if needed.
2185 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2186 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2187
Calin Juravle62c5a372018-02-01 17:03:23 +00002188 unique_fd dex_metadata_fd;
2189 if (dex_metadata_path != nullptr) {
2190 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2191 if (dex_metadata_fd.get() < 0) {
2192 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2193 }
2194 }
2195
Victor Hsieh8948a862020-08-07 11:30:55 -07002196 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
2197 RUNTIME_NATIVE_BOOT_NAMESPACE,
2198 ENABLE_JITZYGOTE_IMAGE,
2199 /*default_value=*/ "");
2200 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
2201
Victor Hsiehe98e6512020-08-10 15:39:22 -07002202 // Decide whether to use dex2oat64.
2203 bool use_dex2oat64 = false;
2204 // Check whether the device even supports 64-bit ABIs.
2205 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
2206 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
2207 }
2208 const char* dex2oat_bin = select_execution_binary(
2209 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
2210 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
2211 background_job_compile);
2212
Andreas Gampe023b2242018-02-28 16:03:25 -08002213 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002214
Victor Hsiehe98e6512020-08-10 15:39:22 -07002215 RunDex2Oat runner(dex2oat_bin,
2216 input_fd.get(),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002217 out_oat_fd.get(),
2218 in_vdex_fd.get(),
2219 out_vdex_fd.get(),
2220 image_fd.get(),
2221 dex_path,
2222 out_oat_path,
2223 swap_fd.get(),
2224 instruction_set,
2225 compiler_filter,
2226 debuggable,
2227 boot_complete,
Patrick Baumann2271b3e2020-04-14 17:03:00 -07002228 for_restore,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002229 reference_profile_fd.get(),
2230 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002231 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002232 target_sdk_version,
2233 enable_hidden_api_checks,
2234 generate_compact_dex,
2235 dex_metadata_fd.get(),
Victor Hsieh8948a862020-08-07 11:30:55 -07002236 use_jitzygote_image,
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002237 compilation_reason);
2238
Jeff Sharkey90aff262016-12-12 14:28:24 -07002239 pid_t pid = fork();
2240 if (pid == 0) {
2241 /* child -- drop privileges before continuing */
2242 drop_capabilities(uid);
2243
Richard Uhler76cc0272016-12-08 10:46:35 +00002244 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002245 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002246 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002247 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002248 }
2249
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002250 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002251 } else {
2252 int res = wait_child(pid);
2253 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002254 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002255 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002256 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2257 << std::hex << std::setw(4) << res << ", process failed";
2258 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002259 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002260 }
2261 }
2262
Calin Juravlec9eab382017-01-25 01:17:17 -08002263 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002264
2265 // We've been successful, don't delete output.
2266 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002267 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002268 image_fd.SetCleanup(false);
2269 reference_profile_fd.SetCleanup(false);
2270
2271 return 0;
2272}
2273
Calin Juravlec9eab382017-01-25 01:17:17 -08002274// Try to remove the given directory. Log an error if the directory exists
2275// and is empty but could not be removed.
2276static bool rmdir_if_empty(const char* dir) {
2277 if (rmdir(dir) == 0) {
2278 return true;
2279 }
2280 if (errno == ENOENT || errno == ENOTEMPTY) {
2281 return true;
2282 }
2283 PLOG(ERROR) << "Failed to remove dir: " << dir;
2284 return false;
2285}
2286
2287// Try to unlink the given file. Log an error if the file exists and could not
2288// be unlinked.
2289static bool unlink_if_exists(const std::string& file) {
2290 if (unlink(file.c_str()) == 0) {
2291 return true;
2292 }
2293 if (errno == ENOENT) {
2294 return true;
2295
2296 }
2297 PLOG(ERROR) << "Could not unlink: " << file;
2298 return false;
2299}
2300
Calin Juravle7d765462017-09-04 15:57:10 -07002301enum ReconcileSecondaryDexResult {
2302 kReconcileSecondaryDexExists = 0,
2303 kReconcileSecondaryDexCleanedUp = 1,
2304 kReconcileSecondaryDexValidationError = 2,
2305 kReconcileSecondaryDexCleanUpError = 3,
2306 kReconcileSecondaryDexAccessIOError = 4,
2307};
Calin Juravlec9eab382017-01-25 01:17:17 -08002308
2309// Reconcile the secondary dex 'dex_path' and its generated oat files.
2310// Return true if all the parameters are valid and the secondary dex file was
2311// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2312// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2313// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2314// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2315// Return false if there were errors during processing. In this case
2316// out_secondary_dex_exists will be set to false.
2317bool reconcile_secondary_dex_file(const std::string& dex_path,
2318 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002319 const std::optional<std::string>& volume_uuid, int storage_flag,
Calin Juravlec9eab382017-01-25 01:17:17 -08002320 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002321 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002322 if (isas.size() == 0) {
2323 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2324 return false;
2325 }
2326
Calin Juravle7d765462017-09-04 15:57:10 -07002327 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2328 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2329 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002330 return false;
2331 }
2332
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002333 // As a security measure we want to unlink art artifacts with the reduced capabilities
2334 // of the package user id. So we fork and drop capabilities in the child.
2335 pid_t pid = fork();
2336 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002337 /* child -- drop privileges before continuing */
2338 drop_capabilities(uid);
2339
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002340 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Greg Kaiser8042c372019-03-26 06:23:19 -07002341 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002342 uid, storage_flag)) {
2343 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2344 _exit(kReconcileSecondaryDexValidationError);
2345 }
2346
2347 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2348 switch (access_check) {
2349 case kSecondaryDexAccessDoesNotExist:
2350 // File does not exist. Proceed with cleaning.
2351 break;
2352 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2353 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2354 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2355 default:
2356 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2357 _exit(kReconcileSecondaryDexValidationError);
2358 }
2359
2360 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002361 char oat_path[PKG_PATH_MAX];
2362 char oat_dir[PKG_PATH_MAX];
2363 char oat_isa_dir[PKG_PATH_MAX];
2364 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002365 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002366 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002367 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002368 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2369 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002370 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002371 }
Calin Juravle51314092017-05-18 15:33:05 -07002372
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002373 // Delete oat/vdex/art files.
2374 result = unlink_if_exists(oat_path) && result;
2375 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2376 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002377
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002378 // Delete profiles.
2379 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002380 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002381 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002382 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002383 result = unlink_if_exists(current_profile) && result;
2384 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002385
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002386 // We upgraded once the location of current profile for secondary dex files.
2387 // Check for any previous left-overs and remove them as well.
2388 std::string old_current_profile = dex_path + ".prof";
2389 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002390
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002391 // Try removing the directories as well, they might be empty.
2392 result = rmdir_if_empty(oat_isa_dir) && result;
2393 result = rmdir_if_empty(oat_dir) && result;
2394 }
Calin Juravle7d765462017-09-04 15:57:10 -07002395 if (!result) {
2396 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2397 }
2398 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002399 }
2400
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002401 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002402 if (!WIFEXITED(return_code)) {
2403 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2404 } else {
2405 return_code = WEXITSTATUS(return_code);
2406 }
2407
2408 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2409
2410 switch (return_code) {
2411 case kReconcileSecondaryDexCleanedUp:
2412 case kReconcileSecondaryDexValidationError:
2413 // If we couldn't validate assume the dex file does not exist.
2414 // This will purge the entry from the PM records.
2415 *out_secondary_dex_exists = false;
2416 return true;
2417 case kReconcileSecondaryDexExists:
2418 *out_secondary_dex_exists = true;
2419 return true;
2420 case kReconcileSecondaryDexAccessIOError:
2421 // We had an access IO error.
2422 // Return false so that we can try again.
2423 // The value of out_secondary_dex_exists does not matter in this case and by convention
2424 // is set to false.
2425 *out_secondary_dex_exists = false;
2426 return false;
2427 default:
2428 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2429 *out_secondary_dex_exists = false;
2430 return false;
2431 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002432}
2433
Alan Stokesa25d90c2017-10-16 10:56:00 +01002434// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2435// Returns true if all parameters are valid and the hash successfully computed and stored in
2436// out_secondary_dex_hash.
2437// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2438// the app.
2439// For any other errors (e.g. if any of the parameters are invalid) returns false.
2440bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002441 const std::optional<std::string>& volume_uuid, int storage_flag,
Alan Stokesa25d90c2017-10-16 10:56:00 +01002442 std::vector<uint8_t>* out_secondary_dex_hash) {
2443 out_secondary_dex_hash->clear();
2444
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002445 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
Alan Stokesa25d90c2017-10-16 10:56:00 +01002446
2447 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2448 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2449 << storage_flag;
2450 return false;
2451 }
2452
2453 // Pipe to get the hash result back from our child process.
2454 unique_fd pipe_read, pipe_write;
2455 if (!Pipe(&pipe_read, &pipe_write)) {
2456 PLOG(ERROR) << "Failed to create pipe";
2457 return false;
2458 }
2459
2460 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2461 // access data the app itself can access.
2462 pid_t pid = fork();
2463 if (pid == 0) {
2464 // child -- drop privileges before continuing
2465 drop_capabilities(uid);
2466 pipe_read.reset();
2467
2468 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2469 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002470 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002471 }
2472
2473 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2474 if (fd == -1) {
2475 if (errno == EACCES || errno == ENOENT) {
2476 // Not treated as an error.
2477 _exit(0);
2478 }
2479 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002480 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002481 }
2482
2483 SHA256_CTX ctx;
2484 SHA256_Init(&ctx);
2485
2486 std::vector<uint8_t> buffer(65536);
2487 while (true) {
2488 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2489 if (bytes_read == 0) {
2490 break;
2491 } else if (bytes_read == -1) {
2492 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002493 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002494 }
2495
2496 SHA256_Update(&ctx, buffer.data(), bytes_read);
2497 }
2498
2499 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2500 SHA256_Final(hash.data(), &ctx);
2501 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002502 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002503 }
2504
2505 _exit(0);
2506 }
2507
2508 // parent
2509 pipe_write.reset();
2510
2511 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2512 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2513 out_secondary_dex_hash->clear();
2514 }
2515 return wait_child(pid) == 0;
2516}
2517
Jeff Sharkey90aff262016-12-12 14:28:24 -07002518// Helper for move_ab, so that we can have common failure-case cleanup.
2519static bool unlink_and_rename(const char* from, const char* to) {
2520 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2521 // return a failure.
2522 struct stat s;
2523 if (stat(to, &s) == 0) {
2524 if (!S_ISREG(s.st_mode)) {
2525 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2526 return false;
2527 }
2528 if (unlink(to) != 0) {
2529 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2530 return false;
2531 }
2532 } else {
2533 // This may be a permission problem. We could investigate the error code, but we'll just
2534 // let the rename failure do the work for us.
2535 }
2536
2537 // Try to rename "to" to "from."
2538 if (rename(from, to) != 0) {
2539 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2540 return false;
2541 }
2542 return true;
2543}
2544
2545// Move/rename a B artifact (from) to an A artifact (to).
2546static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2547 // Check whether B exists.
2548 {
2549 struct stat s;
2550 if (stat(b_path.c_str(), &s) != 0) {
2551 // Silently ignore for now. The service calling this isn't smart enough to understand
2552 // lack of artifacts at the moment.
2553 return false;
2554 }
2555 if (!S_ISREG(s.st_mode)) {
2556 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2557 // Try to unlink, but swallow errors.
2558 unlink(b_path.c_str());
2559 return false;
2560 }
2561 }
2562
2563 // Rename B to A.
2564 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2565 // Delete the b_path so we don't try again (or fail earlier).
2566 if (unlink(b_path.c_str()) != 0) {
2567 PLOG(ERROR) << "Could not unlink " << b_path;
2568 }
2569
2570 return false;
2571 }
2572
2573 return true;
2574}
2575
2576bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2577 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002578 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2579 if (slot_suffix.empty()) {
2580 return false;
2581 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002582
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002583 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2584 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2585 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002586 }
2587
2588 // Validate other inputs.
2589 if (validate_apk_path(apk_path) != 0) {
2590 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2591 return false;
2592 }
2593 if (validate_apk_path(oat_dir) != 0) {
2594 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2595 return false;
2596 }
2597
2598 char a_path[PKG_PATH_MAX];
2599 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2600 return false;
2601 }
2602 const std::string a_vdex_path = create_vdex_filename(a_path);
2603 const std::string a_image_path = create_image_filename(a_path);
2604
2605 // B path = A path + slot suffix.
2606 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2607 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2608 const std::string b_image_path = StringPrintf("%s.%s",
2609 a_image_path.c_str(),
2610 slot_suffix.c_str());
2611
2612 bool success = true;
2613 if (move_ab_path(b_path, a_path)) {
2614 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2615 // Note: we can live without an app image. As such, ignore failure to move the image file.
2616 // If we decide to require the app image, or the app image being moved correctly,
2617 // then change accordingly.
2618 constexpr bool kIgnoreAppImageFailure = true;
2619
2620 if (!a_image_path.empty()) {
2621 if (!move_ab_path(b_image_path, a_image_path)) {
2622 unlink(a_image_path.c_str());
2623 if (!kIgnoreAppImageFailure) {
2624 success = false;
2625 }
2626 }
2627 }
2628 } else {
2629 // Cleanup: delete B image, ignore errors.
2630 unlink(b_image_path.c_str());
2631 success = false;
2632 }
2633 } else {
2634 // Cleanup: delete B image, ignore errors.
2635 unlink(b_vdex_path.c_str());
2636 unlink(b_image_path.c_str());
2637 success = false;
2638 }
2639 return success;
2640}
2641
2642bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2643 // Delete the oat/odex file.
2644 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002645 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002646 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002647 return false;
2648 }
2649
2650 // In case of a permission failure report the issue. Otherwise just print a warning.
2651 auto unlink_and_check = [](const char* path) -> bool {
2652 int result = unlink(path);
2653 if (result != 0) {
2654 if (errno == EACCES || errno == EPERM) {
2655 PLOG(ERROR) << "Could not unlink " << path;
2656 return false;
2657 }
2658 PLOG(WARNING) << "Could not unlink " << path;
2659 }
2660 return true;
2661 };
2662
2663 // Delete the oat/odex file.
2664 bool return_value_oat = unlink_and_check(out_path);
2665
2666 // Derive and delete the app image.
2667 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2668
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002669 // Derive and delete the vdex file.
2670 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2671
Jeff Sharkey90aff262016-12-12 14:28:24 -07002672 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002673 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002674}
2675
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002676static bool is_absolute_path(const std::string& path) {
2677 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2678 LOG(ERROR) << "Invalid absolute path " << path;
2679 return false;
2680 } else {
2681 return true;
2682 }
2683}
2684
2685static bool is_valid_instruction_set(const std::string& instruction_set) {
2686 // TODO: add explicit whitelisting of instruction sets
2687 if (instruction_set.find('/') != std::string::npos) {
2688 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2689 return false;
2690 } else {
2691 return true;
2692 }
2693}
2694
2695bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2696 const char *apk_path, const char *instruction_set) {
2697 std::string oat_dir_ = oat_dir;
2698 std::string apk_path_ = apk_path;
2699 std::string instruction_set_ = instruction_set;
2700
2701 if (!is_absolute_path(oat_dir_)) return false;
2702 if (!is_absolute_path(apk_path_)) return false;
2703 if (!is_valid_instruction_set(instruction_set_)) return false;
2704
2705 std::string::size_type end = apk_path_.rfind('.');
2706 std::string::size_type start = apk_path_.rfind('/', end);
2707 if (end == std::string::npos || start == std::string::npos) {
2708 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2709 return false;
2710 }
2711
2712 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2713 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2714 const char* res = res_.c_str();
2715 if (strlen(res) >= PKG_PATH_MAX) {
2716 LOG(ERROR) << "Result too large";
2717 return false;
2718 } else {
2719 strlcpy(path, res, PKG_PATH_MAX);
2720 return true;
2721 }
2722}
2723
2724bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2725 const char *instruction_set) {
2726 std::string apk_path_ = apk_path;
2727 std::string instruction_set_ = instruction_set;
2728
2729 if (!is_absolute_path(apk_path_)) return false;
2730 if (!is_valid_instruction_set(instruction_set_)) return false;
2731
2732 std::string::size_type end = apk_path_.rfind('.');
2733 std::string::size_type start = apk_path_.rfind('/', end);
2734 if (end == std::string::npos || start == std::string::npos) {
2735 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2736 return false;
2737 }
2738
2739 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2740 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2741}
2742
2743bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2744 const char *instruction_set) {
2745 std::string src_ = src;
2746 std::string instruction_set_ = instruction_set;
2747
2748 if (!is_absolute_path(src_)) return false;
2749 if (!is_valid_instruction_set(instruction_set_)) return false;
2750
2751 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2752 if (*it == '/') {
2753 *it = '@';
2754 }
2755 }
2756
2757 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2758 + DALVIK_CACHE_POSTFIX;
2759 const char* res = res_.c_str();
2760 if (strlen(res) >= PKG_PATH_MAX) {
2761 LOG(ERROR) << "Result too large";
2762 return false;
2763 } else {
2764 strlcpy(path, res, PKG_PATH_MAX);
2765 return true;
2766 }
2767}
2768
Calin Juravle59f7ab82018-04-27 17:50:23 -07002769bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2770 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002771 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2772 for (const std::string& elem : classpaths_elems) {
2773 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2774 if (fd < 0) {
2775 PLOG(ERROR) << "Could not open classpath elem " << elem;
2776 return false;
2777 } else {
2778 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002779 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002780 }
2781 }
2782 return true;
2783}
2784
2785static bool create_app_profile_snapshot(int32_t app_id,
2786 const std::string& package_name,
2787 const std::string& profile_name,
2788 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002789 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2790
Calin Juravle824a64d2018-01-18 20:23:17 -08002791 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002792 if (snapshot_fd < 0) {
2793 return false;
2794 }
2795
2796 std::vector<unique_fd> profiles_fd;
2797 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002798 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2799 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002800 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2801 return false;
2802 }
2803
2804 profiles_fd.push_back(std::move(reference_profile_fd));
2805
Calin Juravle0d0a4922018-01-23 19:54:11 -08002806 // Open the class paths elements. These will be used to filter out profile data that does
2807 // not belong to the classpath during merge.
2808 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002809 std::vector<std::string> dex_locations;
2810 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002811 return false;
2812 }
2813
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002814 RunProfman args;
Calin Juravlef85ddb92020-05-01 14:05:40 -07002815 // This is specifically a snapshot for an app, so don't use boot image profiles.
2816 args.SetupMerge(profiles_fd,
2817 snapshot_fd,
2818 apk_fds,
2819 dex_locations,
2820 /* for_snapshot= */ true,
2821 /* for_boot_image= */ false);
Calin Juravle29591732017-11-20 17:46:19 -08002822 pid_t pid = fork();
2823 if (pid == 0) {
2824 /* child -- drop privileges before continuing */
2825 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002826 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002827 }
2828
2829 /* parent */
2830 int return_code = wait_child(pid);
2831 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002832 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002833 return false;
2834 }
2835
Calin Juravle78728f32019-11-08 17:55:46 -08002836 // Verify that profman finished successfully.
2837 int profman_code = WEXITSTATUS(return_code);
2838 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2839 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2840 << ":" << profman_code;
2841 return false;
2842 }
Calin Juravle29591732017-11-20 17:46:19 -08002843 return true;
2844}
2845
Calin Juravle0d0a4922018-01-23 19:54:11 -08002846static bool create_boot_image_profile_snapshot(const std::string& package_name,
2847 const std::string& profile_name,
2848 const std::string& classpath) {
2849 // The reference profile directory for the android package might not be prepared. Do it now.
2850 const std::string ref_profile_dir =
2851 create_primary_reference_profile_package_dir_path(package_name);
2852 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2853 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2854 return false;
2855 }
2856
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002857 // Return false for empty class path since it may otherwise return true below if profiles is
2858 // empty.
2859 if (classpath.empty()) {
2860 PLOG(ERROR) << "Class path is empty";
2861 return false;
2862 }
2863
Calin Juravle0d0a4922018-01-23 19:54:11 -08002864 // Open and create the snapshot profile.
2865 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2866
2867 // Collect all non empty profiles.
2868 // The collection will traverse all applications profiles and find the non empty files.
2869 // This has the potential of inspecting a large number of files and directories (depending
2870 // on the number of applications and users). So there is a slight increase in the chance
2871 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2872 // fail the snapshot and aggregate whatever profile we could open.
2873 //
2874 // The profile snapshot is a best effort based on available data it's ok if some data
2875 // from some apps is missing. It will be counter productive for the snapshot to fail
2876 // because we could not open or read some of the files.
2877 std::vector<std::string> profiles;
2878 if (!collect_profiles(&profiles)) {
2879 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2880 }
2881
2882 // If we have no profiles return early.
2883 if (profiles.empty()) {
2884 return true;
2885 }
2886
2887 // Open the classpath elements. These will be used to filter out profile data that does
2888 // not belong to the classpath during merge.
2889 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002890 std::vector<std::string> dex_locations;
2891 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002892 return false;
2893 }
2894
2895 // If we could not open any files from the classpath return an error.
2896 if (apk_fds.empty()) {
2897 LOG(ERROR) << "Could not open any of the classpath elements.";
2898 return false;
2899 }
2900
2901 // Aggregate the profiles in batches of kAggregationBatchSize.
2902 // We do this to avoid opening a huge a amount of files.
2903 static constexpr size_t kAggregationBatchSize = 10;
2904
Calin Juravle0d0a4922018-01-23 19:54:11 -08002905 for (size_t i = 0; i < profiles.size(); ) {
Calin Juravlea64fb512019-11-06 16:11:14 -08002906 std::vector<unique_fd> profiles_fd;
Calin Juravle0d0a4922018-01-23 19:54:11 -08002907 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2908 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2909 if (fd.get() >= 0) {
2910 profiles_fd.push_back(std::move(fd));
2911 }
2912 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002913
2914 // We aggregate (read & write) into the same fd multiple times in a row.
2915 // We need to reset the cursor every time to ensure we read the whole file every time.
2916 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2917 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2918 return false;
2919 }
2920
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002921 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002922 args.SetupMerge(profiles_fd,
2923 snapshot_fd,
2924 apk_fds,
Calin Juravle78728f32019-11-08 17:55:46 -08002925 dex_locations,
2926 /*for_snapshot=*/true,
2927 /*for_boot_image=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002928 pid_t pid = fork();
2929 if (pid == 0) {
2930 /* child -- drop privileges before continuing */
2931 drop_capabilities(AID_SYSTEM);
2932
Calin Juravle59f7ab82018-04-27 17:50:23 -07002933 // The introduction of new access flags into boot jars causes them to
2934 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002935 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002936 }
2937
2938 /* parent */
2939 int return_code = wait_child(pid);
Calin Juravlea64fb512019-11-06 16:11:14 -08002940
Calin Juravle0d0a4922018-01-23 19:54:11 -08002941 if (!WIFEXITED(return_code)) {
2942 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2943 return false;
2944 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002945
2946 // Verify that profman finished successfully.
2947 int profman_code = WEXITSTATUS(return_code);
Calin Juravle78728f32019-11-08 17:55:46 -08002948 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2949 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2950 << ":" << profman_code;
2951 return false;
Calin Juravlea64fb512019-11-06 16:11:14 -08002952 }
Calin Juravle0d0a4922018-01-23 19:54:11 -08002953 }
Calin Juravlea64fb512019-11-06 16:11:14 -08002954
Calin Juravle0d0a4922018-01-23 19:54:11 -08002955 return true;
2956}
2957
2958bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2959 const std::string& profile_name, const std::string& classpath) {
2960 if (app_id == -1) {
2961 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2962 } else {
2963 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2964 }
2965}
2966
Calin Juravlec3b049e2018-01-18 22:32:58 -08002967bool prepare_app_profile(const std::string& package_name,
2968 userid_t user_id,
2969 appid_t app_id,
2970 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002971 const std::string& code_path,
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002972 const std::optional<std::string>& dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002973 // Prepare the current profile.
2974 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2975 /*is_secondary_dex*/ false);
2976 uid_t uid = multiuser_get_uid(user_id, app_id);
2977 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2978 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2979 return false;
2980 }
2981
2982 // Check if we need to install the profile from the dex metadata.
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09002983 if (!dex_metadata) {
Calin Juravlec3b049e2018-01-18 22:32:58 -08002984 return true;
2985 }
2986
2987 // We have a dex metdata. Merge the profile into the reference profile.
2988 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2989 /*read_write*/ true, /*is_secondary_dex*/ false);
2990 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2991 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002992 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2993 if (apk_fd < 0) {
2994 PLOG(ERROR) << "Could not open code path " << code_path;
2995 return false;
2996 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002997
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002998 RunProfman args;
2999 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
3000 std::move(ref_profile_fd),
3001 std::move(apk_fd),
3002 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08003003 pid_t pid = fork();
3004 if (pid == 0) {
3005 /* child -- drop privileges before continuing */
3006 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
3007 drop_capabilities(app_shared_gid);
3008
Calin Juravlef63d4792018-01-30 17:43:34 +00003009 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08003010 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08003011 }
3012
3013 /* parent */
3014 int return_code = wait_child(pid);
3015 if (!WIFEXITED(return_code)) {
3016 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
3017 return false;
3018 }
3019 return true;
3020}
3021
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003022} // namespace installd
3023} // namespace android