blob: 19346c7c17635215056cddbc6bbc648c723b0b2f [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +000048#include <server_configurable_flags/get_flags.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080052#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060053#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070054#include "installd_deps.h"
55#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070056#include "utils.h"
57
Jeff Sharkey90aff262016-12-12 14:28:24 -070058using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070059using android::base::GetBoolProperty;
60using android::base::GetProperty;
David Brazdil4f6027a2019-03-19 11:44:21 +000061using android::base::ReadFdToString;
Alan Stokesa25d90c2017-10-16 10:56:00 +010062using android::base::ReadFully;
63using android::base::StringPrintf;
64using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080065using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066
67namespace android {
68namespace installd {
69
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070070// Should minidebug info be included in compiled artifacts? Even if this value is
71// "true," usage might still be conditional to other constraints, e.g., system
72// property overrides.
73static constexpr bool kEnableMinidebugInfo = true;
74
75static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
76static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
77static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080078static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070079
Andreas Gampefa2dadd2018-02-28 19:52:47 -080080
Calin Juravle114f0812017-03-08 19:05:07 -080081// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
82struct FreeDelete {
83 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
84 void operator()(const void* ptr) const {
85 free(const_cast<void*>(ptr));
86 }
87};
88
89// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
90template <typename T>
91using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
92
Calin Juravle1a0af3b2017-03-09 14:33:33 -080093static unique_fd invalid_unique_fd() {
94 return unique_fd(-1);
95}
96
Andreas Gampe6a9cf722017-07-24 16:49:10 -070097static bool is_debug_runtime() {
98 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
99}
100
David Sehra3b5ab62017-10-25 14:27:29 -0700101static bool is_debuggable_build() {
102 return android::base::GetBoolProperty("ro.debuggable", false);
103}
104
Jeff Sharkey90aff262016-12-12 14:28:24 -0700105static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800106 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700107 if (ufd.get() < 0) {
108 if (errno != ENOENT) {
109 PLOG(WARNING) << "Could not open profile " << profile;
110 return false;
111 } else {
112 // Nothing to clear. That's ok.
113 return true;
114 }
115 }
116
117 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
118 if (errno != EWOULDBLOCK) {
119 PLOG(WARNING) << "Error locking profile " << profile;
120 }
121 // This implies that the app owning this profile is running
122 // (and has acquired the lock).
123 //
124 // If we can't acquire the lock bail out since clearing is useless anyway
125 // (the app will write again to the profile).
126 //
127 // Note:
128 // This does not impact the this is not an issue for the profiling correctness.
129 // In case this is needed because of an app upgrade, profiles will still be
130 // eventually cleared by the app itself due to checksum mismatch.
131 // If this is needed because profman advised, then keeping the data around
132 // until the next run is again not an issue.
133 //
134 // If the app attempts to acquire a lock while we've held one here,
135 // it will simply skip the current write cycle.
136 return false;
137 }
138
139 bool truncated = ftruncate(ufd.get(), 0) == 0;
140 if (!truncated) {
141 PLOG(WARNING) << "Could not truncate " << profile;
142 }
143 if (flock(ufd.get(), LOCK_UN) != 0) {
144 PLOG(WARNING) << "Error unlocking profile " << profile;
145 }
146 return truncated;
147}
148
Calin Juravle114f0812017-03-08 19:05:07 -0800149// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800150// The location is the profile name for primary apks or the dex path for secondary dex files.
151static bool clear_reference_profile(const std::string& package_name, const std::string& location,
152 bool is_secondary_dex) {
153 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154}
155
Calin Juravle114f0812017-03-08 19:05:07 -0800156// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800157// The location is the profile name for primary apks or the dex path for secondary dex files.
158static bool clear_current_profile(const std::string& package_name, const std::string& location,
159 userid_t user, bool is_secondary_dex) {
160 return clear_profile(create_current_profile_path(user, package_name, location,
161 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700162}
163
Calin Juravle114f0812017-03-08 19:05:07 -0800164// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800165// The location is the profile name for primary apks or the dex path for secondary dex files.
166bool clear_primary_reference_profile(const std::string& package_name,
167 const std::string& location) {
168 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800169}
170
171// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800172// The location is the profile name for primary apks or the dex path for secondary dex files.
173bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800175 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700176 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
177 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800178 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700179 }
180 return success;
181}
182
Calin Juravle114f0812017-03-08 19:05:07 -0800183// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800184bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
185 userid_t user) {
186 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800187}
188
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700189static std::vector<std::string> SplitBySpaces(const std::string& str) {
190 if (str.empty()) {
191 return {};
192 }
193 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700194}
195
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700196static const char* get_location_from_path(const char* path) {
197 static constexpr char kLocationSeparator = '/';
198 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700199 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700200 return path;
201 } else {
202 // Skip the separator character.
203 return location + 1;
204 }
205}
206
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800207// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
208// need to be performed between the fork and exec.
209class ExecVHelper {
210 public:
211 // Store a placeholder for the binary name.
212 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800213
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800214 void PrepareArgs(const std::string& bin) {
215 CHECK(!args_.empty());
216 CHECK(args_[0].empty());
217 args_[0] = bin;
218 // Write char* into array.
219 for (const std::string& arg : args_) {
220 argv_.push_back(arg.c_str());
221 }
222 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800223 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800224
225 [[ noreturn ]]
226 void Exec(int exit_code) {
227 execv(argv_[0], (char * const *)&argv_[0]);
228 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
229 exit(exit_code);
230 }
231
232 // Add an arg if it's not empty.
233 void AddArg(const std::string& arg) {
234 if (!arg.empty()) {
235 args_.push_back(arg);
236 }
237 }
238
239 // Add a runtime arg if it's not empty.
240 void AddRuntimeArg(const std::string& arg) {
241 if (!arg.empty()) {
242 args_.push_back("--runtime-arg");
243 args_.push_back(arg);
244 }
245 }
246
247 protected:
248 // Holder arrays for backing arg storage.
249 std::vector<std::string> args_;
250
251 // Argument poiners.
252 std::vector<const char*> argv_;
253};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700254
255static std::string MapPropertyToArg(const std::string& property,
256 const std::string& format,
257 const std::string& default_value = "") {
258 std::string prop = GetProperty(property, default_value);
259 if (!prop.empty()) {
260 return StringPrintf(format.c_str(), prop.c_str());
261 }
262 return "";
263}
264
Calin Juravlef74a7372019-02-28 20:29:41 -0800265// Determines which binary we should use for execution (the debug or non-debug version).
266// e.g. dex2oatd vs dex2oat
267static const char* select_execution_binary(const char* binary, const char* debug_binary,
268 bool background_job_compile) {
269 return select_execution_binary(
270 binary,
271 debug_binary,
272 background_job_compile,
273 is_debug_runtime(),
274 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
275 is_debuggable_build());
276}
277
278// Determines which binary we should use for execution (the debug or non-debug version).
279// e.g. dex2oatd vs dex2oat
280// This is convenient method which is much easier to test because it doesn't read
281// system properties.
282const char* select_execution_binary(
283 const char* binary,
284 const char* debug_binary,
285 bool background_job_compile,
286 bool is_debug_runtime,
287 bool is_release,
288 bool is_debuggable_build) {
289 // Do not use debug binaries for release candidates (to give more soak time).
290 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
291
292 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
293 // the file is present (it may not be on images with very little space available).
294 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
295
296 return useDebug ? debug_binary : binary;
297}
298
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000299// Namespace for Android Runtime flags applied during boot time.
300static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
301// Feature flag name for running the JIT in Zygote experiment, b/119800099.
302static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
303// Location of the apex image.
304static const char* kApexImage = "/system/framework/apex.art";
305
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700306// Phenotype property name for enabling profiling the boot class path.
307static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
308
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800309class RunDex2Oat : public ExecVHelper {
310 public:
311 RunDex2Oat(int zip_fd,
312 int oat_fd,
313 int input_vdex_fd,
314 int output_vdex_fd,
315 int image_fd,
316 const char* input_file_name,
317 const char* output_file_name,
318 int swap_fd,
319 const char* instruction_set,
320 const char* compiler_filter,
321 bool debuggable,
322 bool post_bootcomplete,
323 bool background_job_compile,
324 int profile_fd,
325 const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +0000326 const std::string& class_loader_context_fds,
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800327 int target_sdk_version,
328 bool enable_hidden_api_checks,
329 bool generate_compact_dex,
330 int dex_metadata_fd,
331 const char* compilation_reason) {
332 // Get the relative path to the input file.
333 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700334
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800335 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
336 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700337
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800338 const char* threads_property = post_bootcomplete
339 ? "dalvik.vm.dex2oat-threads"
340 : "dalvik.vm.boot-dex2oat-threads";
341 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000343 std::string bootclasspath;
344 char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
345 if (dex2oat_bootclasspath != nullptr) {
346 bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
347 }
348 // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
349 // BOOTCLASSPATH.
350
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800351 const std::string dex2oat_isa_features_key =
352 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
353 std::string instruction_set_features_arg =
354 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700355
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800356 const std::string dex2oat_isa_variant_key =
357 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
358 std::string instruction_set_variant_arg =
359 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700360
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800361 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700362
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800363 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
364 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
365 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700366
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800367 // If we are booting without the real /data, don't spend time compiling.
368 std::string vold_decrypt = GetProperty("vold.decrypt", "");
369 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
370 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700371
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800372 std::string resolve_startup_string_arg =
373 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
374 "--resolve-startup-const-strings=%s");
375 if (resolve_startup_string_arg.empty()) {
376 // If empty, fall back to system property.
377 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800378 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
379 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800380 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800381
382 const std::string image_block_size_arg =
383 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
384 "--max-image-block-size=%s");
385
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800386 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388 std::string image_format_arg;
389 if (image_fd >= 0) {
390 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000391 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000392
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800393 std::string dex2oat_large_app_threshold_arg =
394 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000395
Calin Juravlef74a7372019-02-28 20:29:41 -0800396
397 const char* dex2oat_bin = select_execution_binary(
398 kDex2oatPath, kDex2oatDebugPath, background_job_compile);
Mathieu Chartier31636522018-11-09 23:53:07 +0000399
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800400 bool generate_minidebug_info = kEnableMinidebugInfo &&
401 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000402
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000403 std::string boot_image;
404 std::string use_apex_image =
405 server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
406 ENABLE_APEX_IMAGE,
407 /*default_value=*/ "");
Mathieu Chartiere97261e2019-10-01 15:36:01 -0700408
409 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
410 profile_boot_class_path =
411 server_configurable_flags::GetServerConfigurableFlag(
412 RUNTIME_NATIVE_BOOT_NAMESPACE,
413 PROFILE_BOOT_CLASS_PATH,
414 /*default_value=*/ profile_boot_class_path);
415
416 if (use_apex_image == "true" || profile_boot_class_path == "true") {
Nicolas Geoffrayaaad21e2019-02-25 13:31:10 +0000417 boot_image = StringPrintf("-Ximage:%s", kApexImage);
418 } else {
419 boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
420 }
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000421
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800422 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
423 // use arraysize instead.
424 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
425 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
426 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
427 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
428 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
429 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
430 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
431 std::string dex2oat_compiler_filter_arg;
432 std::string dex2oat_swap_fd;
433 std::string dex2oat_image_fd;
434 std::string target_sdk_version_arg;
435 if (target_sdk_version != 0) {
David Brazdilccfb3cf2019-02-20 10:39:34 +0000436 target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800437 }
438 std::string class_loader_context_arg;
David Brazdil4f6027a2019-03-19 11:44:21 +0000439 std::string class_loader_context_fds_arg;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800440 if (class_loader_context != nullptr) {
441 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
442 class_loader_context);
David Brazdil4f6027a2019-03-19 11:44:21 +0000443 if (!class_loader_context_fds.empty()) {
444 class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
445 class_loader_context_fds.c_str());
446 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800447 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000448
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800449 if (swap_fd >= 0) {
450 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
451 }
452 if (image_fd >= 0) {
453 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
454 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000455
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800456 // Compute compiler filter.
457 bool have_dex2oat_relocation_skip_flag = false;
458 if (skip_compilation) {
459 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
460 have_dex2oat_relocation_skip_flag = true;
461 } else if (compiler_filter != nullptr) {
462 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
463 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000464
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800465 if (dex2oat_compiler_filter_arg.empty()) {
466 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
467 "--compiler-filter=%s");
468 }
469
470 // Check whether all apps should be compiled debuggable.
471 if (!debuggable) {
472 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
473 }
474 std::string profile_arg;
475 if (profile_fd != -1) {
476 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
477 }
478
479 // Get the directory of the apk to pass as a base classpath directory.
480 std::string base_dir;
481 std::string apk_dir(input_file_name);
482 unsigned long dir_index = apk_dir.rfind('/');
483 bool has_base_dir = dir_index != std::string::npos;
484 if (has_base_dir) {
485 apk_dir = apk_dir.substr(0, dir_index);
486 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
487 }
488
489 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
490
491 std::string compilation_reason_arg = compilation_reason == nullptr
492 ? ""
493 : std::string("--compilation-reason=") + compilation_reason;
494
495 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
496
497 // Disable cdex if update input vdex is true since this combination of options is not
498 // supported.
499 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
500
501 AddArg(zip_fd_arg);
502 AddArg(zip_location_arg);
503 AddArg(input_vdex_fd_arg);
504 AddArg(output_vdex_fd_arg);
505 AddArg(oat_fd_arg);
506 AddArg(oat_location_arg);
507 AddArg(instruction_set_arg);
508
509 AddArg(instruction_set_variant_arg);
510 AddArg(instruction_set_features_arg);
511
Nicolas Geoffray8b3fa972019-02-14 15:57:47 +0000512 AddRuntimeArg(boot_image);
Nicolas Geoffrayab0a1902019-02-22 21:42:45 +0000513 AddRuntimeArg(bootclasspath);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800514 AddRuntimeArg(dex2oat_Xms_arg);
515 AddRuntimeArg(dex2oat_Xmx_arg);
516
517 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800518 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800519 AddArg(dex2oat_compiler_filter_arg);
520 AddArg(dex2oat_threads_arg);
521 AddArg(dex2oat_swap_fd);
522 AddArg(dex2oat_image_fd);
523
524 if (generate_debug_info) {
525 AddArg("--generate-debug-info");
526 }
527 if (debuggable) {
528 AddArg("--debuggable");
529 }
530 AddArg(image_format_arg);
531 AddArg(dex2oat_large_app_threshold_arg);
532
533 if (have_dex2oat_relocation_skip_flag) {
534 AddRuntimeArg(dex2oat_norelocation);
535 }
536 AddArg(profile_arg);
537 AddArg(base_dir);
538 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +0000539 AddArg(class_loader_context_fds_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800540 if (generate_minidebug_info) {
541 AddArg(kMinidebugDex2oatFlag);
542 }
543 if (disable_cdex) {
544 AddArg(kDisableCompactDexFlag);
545 }
David Brazdilccfb3cf2019-02-20 10:39:34 +0000546 AddRuntimeArg(target_sdk_version_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800547 if (enable_hidden_api_checks) {
David Brazdil36133d12019-04-12 11:08:44 +0100548 AddRuntimeArg("-Xhidden-api-policy:enabled");
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800549 }
550
551 if (dex_metadata_fd > -1) {
552 AddArg(dex_metadata_fd_arg);
553 }
554
555 AddArg(compilation_reason_arg);
556
557 // Do not add args after dex2oat_flags, they should override others for debugging.
558 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
559
560 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000561 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800562};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700563
564/*
565 * Whether dexopt should use a swap file when compiling an APK.
566 *
567 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
568 * itself, anyways).
569 *
570 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
571 *
572 * Otherwise, return true if this is a low-mem device.
573 *
574 * Otherwise, return default value.
575 */
576static bool kAlwaysProvideSwapFile = false;
577static bool kDefaultProvideSwapFile = true;
578
579static bool ShouldUseSwapFileForDexopt() {
580 if (kAlwaysProvideSwapFile) {
581 return true;
582 }
583
584 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700585 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
586 if (!dex2oat_prop_buf.empty()) {
587 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700588 }
589
590 // Shortcut for default value. This is an implementation optimization for the process sketched
591 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
592 // as low-mem is never returning false. The compiler will optimize this away if it can.
593 if (kDefaultProvideSwapFile) {
594 return true;
595 }
596
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700597 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700598 return true;
599 }
600
601 // Default value must be false here.
602 return kDefaultProvideSwapFile;
603}
604
Richard Uhler76cc0272016-12-08 10:46:35 +0000605static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700606 if (set_to_bg) {
607 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800608 PLOG(ERROR) << "set_sched_policy failed";
609 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700610 }
611 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800612 PLOG(ERROR) << "setpriority failed";
613 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 }
615 }
616}
617
Calin Juravle29591732017-11-20 17:46:19 -0800618static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
619 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800620 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800621 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800622 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800623 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800624 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700625 }
Calin Juravle114f0812017-03-08 19:05:07 -0800626 // Profiles should belong to the app; make sure of that by giving ownership to
627 // the app uid. If we cannot do that, there's no point in returning the fd
628 // since dex2oat/profman will fail with SElinux denials.
629 if (fchown(fd.get(), uid, uid) < 0) {
Roland Levillain019db5b2019-03-14 14:31:59 +0000630 PLOG(ERROR) << "Could not chown profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800631 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800632 }
Calin Juravle29591732017-11-20 17:46:19 -0800633 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800634}
635
Calin Juravle29591732017-11-20 17:46:19 -0800636static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800637 // Do not follow symlinks when opening a profile:
638 // - primary profiles should not contain symlinks in their paths
639 // - secondary dex paths should have been already resolved and validated
640 flags |= O_NOFOLLOW;
641
Calin Juravle29591732017-11-20 17:46:19 -0800642 // Check if we need to create the profile
643 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
644 unique_fd fd;
645 if ((flags & O_CREAT) != 0) {
646 fd = create_profile(uid, profile, flags);
647 } else {
648 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
649 }
650
Calin Juravle114f0812017-03-08 19:05:07 -0800651 if (fd.get() < 0) {
652 if (errno != ENOENT) {
653 // Profiles might be missing for various reasons. For example, in a
654 // multi-user environment, the profile directory for one user can be created
655 // after we start a merge. In this case the current profile for that user
656 // will not be found.
657 // Also, the secondary dex profiles might be deleted by the app at any time,
658 // so we can't we need to prepare if they are missing.
659 PLOG(ERROR) << "Failed to open profile " << profile;
660 }
661 return invalid_unique_fd();
662 }
663
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664 return fd;
665}
666
Calin Juravle824a64d2018-01-18 20:23:17 -0800667static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
668 const std::string& location, bool is_secondary_dex) {
669 std::string profile = create_current_profile_path(user, package_name, location,
670 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800671 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800672}
673
Calin Juravle824a64d2018-01-18 20:23:17 -0800674static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
675 const std::string& location, bool read_write, bool is_secondary_dex) {
676 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800677 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
678}
679
680static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800681 const std::string& location) {
682 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800683 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800684}
685
Calin Juravle824a64d2018-01-18 20:23:17 -0800686static void open_profile_files(uid_t uid, const std::string& package_name,
687 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800688 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800690 *reference_profile_fd = open_reference_profile(uid, package_name, location,
691 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692
Calin Juravle114f0812017-03-08 19:05:07 -0800693 // For secondary dex files, we don't really need the user but we use it for sanity checks.
694 // Note: the user owning the dex file should be the current user.
695 std::vector<userid_t> users;
696 if (is_secondary_dex){
697 users.push_back(multiuser_get_user_id(uid));
698 } else {
699 users = get_known_users(/*volume_uuid*/ nullptr);
700 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800702 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
703 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700704 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800705 if (profile_fd.get() >= 0) {
706 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 }
708 }
709}
710
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
712static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
713static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
714static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
715static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
716
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800717class RunProfman : public ExecVHelper {
718 public:
719 void SetupArgs(const std::vector<unique_fd>& profile_fds,
720 const unique_fd& reference_profile_fd,
721 const std::vector<unique_fd>& apk_fds,
722 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800723 bool copy_and_update,
724 bool store_aggregation_counters) {
Calin Juravlef74a7372019-02-28 20:29:41 -0800725
726 // TODO(calin): Assume for now we run in the bg compile job (which is in
727 // most of the invocation). With the current data flow, is not very easy or
728 // clean to discover this in RunProfman (it will require quite a messy refactoring).
729 const char* profman_bin = select_execution_binary(
730 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700731
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800732 if (copy_and_update) {
733 CHECK_EQ(1u, profile_fds.size());
734 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000735 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800736 if (reference_profile_fd != -1) {
737 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000738 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800739
740 for (const unique_fd& fd : profile_fds) {
741 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
742 }
743
744 for (const unique_fd& fd : apk_fds) {
745 AddArg("--apk-fd=" + std::to_string(fd.get()));
746 }
747
748 for (const std::string& dex_location : dex_locations) {
749 AddArg("--dex-location=" + dex_location);
750 }
751
752 if (copy_and_update) {
753 AddArg("--copy-and-update-profile-key");
754 }
755
Calin Juravleb3a929d2018-12-11 14:40:00 -0800756 if (store_aggregation_counters) {
757 AddArg("--store-aggregation-counters");
758 }
759
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800760 // Do not add after dex2oat_flags, they should override others for debugging.
761 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800762 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800764 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
765 const unique_fd& reference_profile_fd,
766 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800767 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
768 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800769 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800770 reference_profile_fd,
771 apk_fds,
772 dex_locations,
773 /*copy_and_update=*/false,
774 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800775 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700776
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800777 void SetupCopyAndUpdate(unique_fd&& profile_fd,
778 unique_fd&& reference_profile_fd,
779 unique_fd&& apk_fd,
780 const std::string& dex_location) {
781 // The fds need to stay open longer than the scope of the function, so put them into a local
782 // variable vector.
783 profiles_fd_.push_back(std::move(profile_fd));
784 apk_fds_.push_back(std::move(apk_fd));
785 reference_profile_fd_ = std::move(reference_profile_fd);
786 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800787 SetupArgs(profiles_fd_,
788 reference_profile_fd_,
789 apk_fds_,
790 dex_locations,
791 /*copy_and_update=*/true,
792 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800793 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000794
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800795 void SetupDump(const std::vector<unique_fd>& profiles_fd,
796 const unique_fd& reference_profile_fd,
797 const std::vector<std::string>& dex_locations,
798 const std::vector<unique_fd>& apk_fds,
799 const unique_fd& output_fd) {
800 AddArg("--dump-only");
801 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800802 SetupArgs(profiles_fd,
803 reference_profile_fd,
804 apk_fds,
805 dex_locations,
806 /*copy_and_update=*/false,
807 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800808 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000809
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800810 void Exec() {
811 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
812 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000813
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800814 private:
815 unique_fd reference_profile_fd_;
816 std::vector<unique_fd> profiles_fd_;
817 std::vector<unique_fd> apk_fds_;
818};
Mathieu Chartier31636522018-11-09 23:53:07 +0000819
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800820
Calin Juravlef63d4792018-01-30 17:43:34 +0000821
Jeff Sharkey90aff262016-12-12 14:28:24 -0700822// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800823// The location is the package name for primary apks or the dex path for secondary dex files.
824// Returns true if there is enough information in the current profiles that makes it
825// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700826// If the return value is true all the current profiles would have been merged into
827// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800828static bool analyze_profiles(uid_t uid, const std::string& package_name,
829 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800830 std::vector<unique_fd> profiles_fd;
831 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800832 open_profile_files(uid, package_name, location, is_secondary_dex,
833 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800834 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700835 // Skip profile guided compilation because no profiles were found.
836 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700837 return false;
838 }
839
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800840 RunProfman profman_merge;
841 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842 pid_t pid = fork();
843 if (pid == 0) {
844 /* child -- drop privileges before continuing */
845 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800846 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 }
848 /* parent */
849 int return_code = wait_child(pid);
850 bool need_to_compile = false;
851 bool should_clear_current_profiles = false;
852 bool should_clear_reference_profile = false;
853 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800854 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700855 } else {
856 return_code = WEXITSTATUS(return_code);
857 switch (return_code) {
858 case PROFMAN_BIN_RETURN_CODE_COMPILE:
859 need_to_compile = true;
860 should_clear_current_profiles = true;
861 should_clear_reference_profile = false;
862 break;
863 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
864 need_to_compile = false;
865 should_clear_current_profiles = false;
866 should_clear_reference_profile = false;
867 break;
868 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800869 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 need_to_compile = false;
871 should_clear_current_profiles = true;
872 should_clear_reference_profile = true;
873 break;
874 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
875 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
876 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800877 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700878 need_to_compile = false;
879 should_clear_current_profiles = false;
880 should_clear_reference_profile = false;
881 break;
882 default:
883 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800884 LOG(WARNING) << "Unknown error code while processing profiles for location "
885 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700886 need_to_compile = false;
887 should_clear_current_profiles = true;
888 should_clear_reference_profile = true;
889 break;
890 }
891 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800892
Jeff Sharkey90aff262016-12-12 14:28:24 -0700893 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800894 if (is_secondary_dex) {
895 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800896 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
897 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800898 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800899 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800900 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700901 }
902 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800903 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700904 }
905 return need_to_compile;
906}
907
Calin Juravle114f0812017-03-08 19:05:07 -0800908// Decides if profile guided compilation is needed or not based on existing profiles.
909// The analysis is done for the primary apks of the given package.
910// Returns true if there is enough information in the current profiles that makes it
911// worth to recompile the package.
912// If the return value is true all the current profiles would have been merged into
913// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800914bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
915 const std::string& profile_name) {
916 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800917}
918
Calin Juravle408cd4a2018-01-20 23:34:18 -0800919bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
920 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800921 std::vector<unique_fd> profile_fds;
922 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800923 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
924 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700925
Calin Juravle408cd4a2018-01-20 23:34:18 -0800926 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800927 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700928
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800929 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700930 const bool has_profiles = !profile_fds.empty();
931
932 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800933 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934 return false;
935 }
936
Calin Juravle114f0812017-03-08 19:05:07 -0800937 unique_fd output_fd(open(out_file_name.c_str(),
938 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700939 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800940 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700941 return false;
942 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800943
Jeff Sharkey90aff262016-12-12 14:28:24 -0700944 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800945 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800946 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
947 if (apk_fd == -1) {
948 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
949 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700950 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800951 dex_locations.push_back(get_location_from_path(code_path.c_str()));
952 apk_fds.push_back(std::move(apk_fd));
953
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800955 RunProfman profman_dump;
956 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700957 pid_t pid = fork();
958 if (pid == 0) {
959 /* child -- drop privileges before continuing */
960 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800961 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700962 }
963 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964 int return_code = wait_child(pid);
965 if (!WIFEXITED(return_code)) {
966 LOG(WARNING) << "profman failed for package " << pkgname << ": "
967 << return_code;
968 return false;
969 }
970 return true;
971}
972
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700973bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800974 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700975 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
976 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800977 package_name,
978 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700979 /*read_write*/ true,
980 /*secondary*/ false));
981 if (in_fd.get() < 0) {
982 PLOG(WARNING) << "Could not open profile " << system_profile;
983 return false;
984 }
985 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800986 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700987 return false;
988 }
989
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700990 // As a security measure we want to write the profile information with the reduced capabilities
991 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700992 pid_t pid = fork();
993 if (pid == 0) {
994 /* child -- drop privileges before continuing */
995 drop_capabilities(packageUid);
996
997 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
998 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800999 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001000 }
1001 // This implies that the app owning this profile is running
1002 // (and has acquired the lock).
1003 //
1004 // The app never acquires the lock for the reference profiles of primary apks.
1005 // Only dex2oat from installd will do that. Since installd is single threaded
1006 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001007 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001008 return false;
1009 }
1010
1011 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1012 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001013 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001014 }
1015
1016 // Copy over data.
1017 static constexpr size_t kBufferSize = 4 * 1024;
1018 char buffer[kBufferSize];
1019 while (true) {
1020 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1021 if (bytes == 0) {
1022 break;
1023 }
1024 write(out_fd.get(), buffer, bytes);
1025 }
1026 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001027 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001028 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001029 // Use _exit since we don't want to run the global destructors in the child.
1030 // b/62597429
1031 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001032 }
1033 /* parent */
1034 int return_code = wait_child(pid);
1035 return return_code == 0;
1036}
1037
Jeff Sharkey90aff262016-12-12 14:28:24 -07001038static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1039 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1040 if (EndsWith(oat_path, ".dex")) {
1041 std::string new_path = oat_path;
1042 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001043 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001044 return new_path;
1045 }
1046
1047 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1048 // case (where the base name will have an extension for the B artifact).
1049 size_t odex_pos = oat_path.rfind(".odex");
1050 if (odex_pos != std::string::npos) {
1051 std::string new_path = oat_path;
1052 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1053 CHECK_NE(new_path.find(new_ext), std::string::npos);
1054 return new_path;
1055 }
1056
1057 // Don't know how to handle this.
1058 return "";
1059}
1060
1061// Translate the given oat path to an art (app image) path. An empty string
1062// denotes an error.
1063static std::string create_image_filename(const std::string& oat_path) {
1064 return replace_file_extension(oat_path, ".art");
1065}
1066
1067// Translate the given oat path to a vdex path. An empty string denotes an error.
1068static std::string create_vdex_filename(const std::string& oat_path) {
1069 return replace_file_extension(oat_path, ".vdex");
1070}
1071
Jeff Sharkey90aff262016-12-12 14:28:24 -07001072static int open_output_file(const char* file_name, bool recreate, int permissions) {
1073 int flags = O_RDWR | O_CREAT;
1074 if (recreate) {
1075 if (unlink(file_name) < 0) {
1076 if (errno != ENOENT) {
1077 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1078 }
1079 }
1080 flags |= O_EXCL;
1081 }
1082 return open(file_name, flags, permissions);
1083}
1084
Calin Juravle2289c0a2017-02-15 12:44:14 -08001085static bool set_permissions_and_ownership(
1086 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1087 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1088 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 if (fchmod(fd,
1090 S_IRUSR|S_IWUSR|S_IRGRP |
1091 (is_public ? S_IROTH : 0)) < 0) {
1092 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1093 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001094 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001095 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1096 return false;
1097 }
1098 return true;
1099}
1100
1101static bool IsOutputDalvikCache(const char* oat_dir) {
1102 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1103 // into '!'. Play it safe by handling it both.
1104 // TODO: ensure we never get null.
1105 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1106 return oat_dir == nullptr || oat_dir[0] == '!';
1107}
1108
Calin Juravled23dee72017-07-06 16:29:11 -07001109// Best-effort check whether we can fit the the path into our buffers.
1110// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1111// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1112// extension to the cache path (5 bytes).
1113// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1114static bool validate_dex_path_size(const std::string& dex_path) {
1115 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1116 LOG(ERROR) << "dex_path too long: " << dex_path;
1117 return false;
1118 }
1119 return true;
1120}
1121
Jeff Sharkey90aff262016-12-12 14:28:24 -07001122static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001123 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001124 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 return false;
1126 }
1127
1128 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001129 // Oat dirs for secondary dex files are already validated.
1130 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1132 return false;
1133 }
1134 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1135 return false;
1136 }
1137 } else {
1138 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1139 return false;
1140 }
1141 }
1142 return true;
1143}
1144
1145// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1146// on destruction. It will also run the given cleanup (unless told not to) after closing.
1147//
1148// Usage example:
1149//
Calin Juravle7a570e82017-01-14 16:23:30 -08001150// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001151// [name]() {
1152// unlink(name.c_str());
1153// });
1154// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1155// wrapper if captured as a reference.
1156//
1157// if (file.get() == -1) {
1158// // Error opening...
1159// }
1160//
1161// ...
1162// if (error) {
1163// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1164// // and delete the file (after the fd is closed).
1165// return -1;
1166// }
1167//
1168// (Success case)
1169// file.SetCleanup(false);
1170// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1171// // (leaving the file around; after the fd is closed).
1172//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001173class Dex2oatFileWrapper {
1174 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001175 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001176 }
1177
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1179 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1180
1181 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1182 value_ = other.value_;
1183 cleanup_ = other.cleanup_;
1184 do_cleanup_ = other.do_cleanup_;
1185 auto_close_ = other.auto_close_;
1186 other.release();
1187 }
1188
1189 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1190 value_ = other.value_;
1191 cleanup_ = other.cleanup_;
1192 do_cleanup_ = other.do_cleanup_;
1193 auto_close_ = other.auto_close_;
1194 other.release();
1195 return *this;
1196 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001197
1198 ~Dex2oatFileWrapper() {
1199 reset(-1);
1200 }
1201
1202 int get() {
1203 return value_;
1204 }
1205
1206 void SetCleanup(bool cleanup) {
1207 do_cleanup_ = cleanup;
1208 }
1209
1210 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001211 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001212 close(value_);
1213 }
1214 if (do_cleanup_ && cleanup_ != nullptr) {
1215 cleanup_();
1216 }
1217
1218 value_ = new_value;
1219 }
1220
Calin Juravle7a570e82017-01-14 16:23:30 -08001221 void reset(int new_value, std::function<void ()> new_cleanup) {
1222 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001223 close(value_);
1224 }
1225 if (do_cleanup_ && cleanup_ != nullptr) {
1226 cleanup_();
1227 }
1228
1229 value_ = new_value;
1230 cleanup_ = new_cleanup;
1231 }
1232
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 void DisableAutoClose() {
1234 auto_close_ = false;
1235 }
1236
Jeff Sharkey90aff262016-12-12 14:28:24 -07001237 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001238 void release() {
1239 value_ = -1;
1240 do_cleanup_ = false;
1241 cleanup_ = nullptr;
1242 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001243 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001244 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001245 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001246 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001247};
1248
Calin Juravle7a570e82017-01-14 16:23:30 -08001249// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001250Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1251 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001252
1253 // We don't create an image for secondary dex files.
1254 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001255 return Dex2oatFileWrapper();
1256 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001257
Calin Juravle7a570e82017-01-14 16:23:30 -08001258 const std::string image_path = create_image_filename(out_oat_path);
1259 if (image_path.empty()) {
1260 // Happens when the out_oat_path has an unknown extension.
1261 return Dex2oatFileWrapper();
1262 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001263
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001264 // In case there is a stale image, remove it now. Ignore any error.
1265 unlink(image_path.c_str());
1266
1267 // Not enabled, exit.
1268 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001269 return Dex2oatFileWrapper();
1270 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001271 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1272 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001273 return Dex2oatFileWrapper();
1274 }
1275 // Recreate is true since we do not want to modify a mapped image. If the app is
1276 // already running and we modify the image file, it can cause crashes (b/27493510).
1277 Dex2oatFileWrapper wrapper_fd(
1278 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1279 [image_path]() { unlink(image_path.c_str()); });
1280 if (wrapper_fd.get() < 0) {
1281 // Could not create application image file. Go on since we can compile without it.
1282 LOG(ERROR) << "installd could not create '" << image_path
1283 << "' for image file during dexopt";
1284 // If we have a valid image file path but no image fd, explicitly erase the image file.
1285 if (unlink(image_path.c_str()) < 0) {
1286 if (errno != ENOENT) {
1287 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1288 }
1289 }
1290 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001291 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001292 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1293 wrapper_fd.reset(-1);
1294 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001295
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 return wrapper_fd;
1297}
1298
1299// Creates the dexopt swap file if necessary and return its fd.
1300// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001301unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001302 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001303 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001304 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001305 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001306 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001307 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001308 if (swap_fd.get() < 0) {
1309 // Could not create swap file. Optimistically go on and hope that we can compile
1310 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001311 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001312 } else {
1313 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001314 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001315 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1316 }
1317 }
1318 return swap_fd;
1319}
1320
1321// Opens the reference profiles if needed.
1322// 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 -08001323Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001324 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001325 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001326 // If we are not profile guided compilation, or we are compiling system server
1327 // do not bother to open the profiles; we won't be using them.
1328 if (!profile_guided || (pkgname[0] == '*')) {
1329 return Dex2oatFileWrapper();
1330 }
1331
1332 // If this is a secondary dex path which is public do not open the profile.
1333 // We cannot compile public secondary dex paths with profiles. That's because
1334 // it will expose how the dex files are used by their owner.
1335 //
1336 // Note that the PackageManager is responsible to set the is_public flag for
1337 // primary apks and we do not check it here. In some cases, e.g. when
1338 // compiling with a public profile from the .dm file the PackageManager will
1339 // set is_public toghether with the profile guided compilation.
1340 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001341 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001342 }
Calin Juravle114f0812017-03-08 19:05:07 -08001343
1344 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001345 std::string location;
1346 if (is_secondary_dex) {
1347 location = dex_path;
1348 } else {
1349 if (profile_name == nullptr) {
1350 // This path is taken for system server re-compilation lunched from ZygoteInit.
1351 return Dex2oatFileWrapper();
1352 } else {
1353 location = profile_name;
1354 }
1355 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001356 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1357 is_secondary_dex);
1358 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1359 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001360 };
1361 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001362}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001363
Calin Juravle7a570e82017-01-14 16:23:30 -08001364// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1365// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001366bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001367 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001368 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001369 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1370 CHECK(in_vdex_wrapper_fd != nullptr);
1371 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001372 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1373 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001374 char in_odex_path[PKG_PATH_MAX];
1375 int dexopt_action = abs(dexopt_needed);
1376 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001377 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001378
1379 // Infer the name of the output VDEX.
1380 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1381 if (out_vdex_path_str.empty()) {
1382 return false;
1383 }
1384
1385 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001386 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001387 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1388 const char* path = nullptr;
1389 if (is_odex_location) {
1390 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1391 path = in_odex_path;
1392 } else {
1393 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001394 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001395 }
1396 } else {
1397 path = out_oat_path;
1398 }
1399 in_vdex_path_str = create_vdex_filename(path);
1400 if (in_vdex_path_str.empty()) {
1401 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001402 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001403 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001404 // We can update in place when all these conditions are met:
1405 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1406 // on /system typically cannot be updated in place).
1407 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1408 // cannot be currently used by a running process.
1409 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1410 // different vdex files to operate.
1411 update_vdex_in_place =
1412 (in_vdex_path_str == out_vdex_path_str) &&
1413 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1414 !profile_guided;
1415 if (update_vdex_in_place) {
1416 // Open the file read-write to be able to update it.
1417 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1418 if (in_vdex_wrapper_fd->get() == -1) {
1419 // If we failed to open the file, we cannot update it in place.
1420 update_vdex_in_place = false;
1421 }
1422 } else {
1423 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1424 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001425 }
1426
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001427 // If we are updating the vdex in place, we do not need to recreate a vdex,
1428 // and can use the same existing one.
1429 if (update_vdex_in_place) {
1430 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1431 // have bogus stale vdex files.
1432 out_vdex_wrapper_fd->reset(
1433 in_vdex_wrapper_fd->get(),
1434 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1435 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1436 // wrapper).
1437 in_vdex_wrapper_fd->DisableAutoClose();
1438 } else {
1439 out_vdex_wrapper_fd->reset(
1440 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1441 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1442 if (out_vdex_wrapper_fd->get() < 0) {
1443 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1444 return false;
1445 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001446 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001447 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001448 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001449 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1450 return false;
1451 }
1452
1453 // If we got here we successfully opened the vdex files.
1454 return true;
1455}
1456
1457// Opens the output oat file for the given apk.
1458// If successful it stores the output path into out_oat_path and returns true.
1459Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001460 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1461 char* out_oat_path) {
1462 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001463 return Dex2oatFileWrapper();
1464 }
1465 const std::string out_oat_path_str(out_oat_path);
1466 Dex2oatFileWrapper wrapper_fd(
1467 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1468 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1469 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001470 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001471 } else if (!set_permissions_and_ownership(
1472 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001473 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1474 wrapper_fd.reset(-1);
1475 }
1476 return wrapper_fd;
1477}
1478
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001479// Creates RDONLY fds for oat and vdex files, if exist.
1480// Returns false if it fails to create oat out path for the given apk path.
1481// Note that the method returns true even if the files could not be opened.
1482bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1483 const std::string& oat_dir,
1484 const std::string& instruction_set,
1485 bool is_secondary_dex,
1486 unique_fd* oat_file_fd,
1487 unique_fd* vdex_file_fd) {
1488 char oat_path[PKG_PATH_MAX];
1489 if (!create_oat_out_path(apk_path.c_str(),
1490 instruction_set.c_str(),
1491 oat_dir.c_str(),
1492 is_secondary_dex,
1493 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001494 LOG(ERROR) << "Could not create oat out path for "
1495 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001496 return false;
1497 }
1498 oat_file_fd->reset(open(oat_path, O_RDONLY));
1499 if (oat_file_fd->get() < 0) {
1500 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1501 }
1502
1503 std::string vdex_filename = create_vdex_filename(oat_path);
1504 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1505 if (vdex_file_fd->get() < 0) {
1506 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1507 }
1508
1509 return true;
1510}
1511
Calin Juravle7a570e82017-01-14 16:23:30 -08001512// Updates the access times of out_oat_path based on those from apk_path.
1513void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1514 struct stat input_stat;
1515 memset(&input_stat, 0, sizeof(input_stat));
1516 if (stat(apk_path, &input_stat) != 0) {
1517 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1518 return;
1519 }
1520
1521 struct utimbuf ut;
1522 ut.actime = input_stat.st_atime;
1523 ut.modtime = input_stat.st_mtime;
1524 if (utime(out_oat_path, &ut) != 0) {
1525 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1526 }
1527}
1528
Calin Juravle80a21252017-01-17 14:43:25 -08001529// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001530// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1531// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1532// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001533class RunDexoptAnalyzer : public ExecVHelper {
1534 public:
1535 RunDexoptAnalyzer(const std::string& dex_file,
David Brazdil4f6027a2019-03-19 11:44:21 +00001536 int vdex_fd,
1537 int oat_fd,
1538 int zip_fd,
1539 const std::string& instruction_set,
1540 const std::string& compiler_filter,
1541 bool profile_was_updated,
1542 bool downgrade,
1543 const char* class_loader_context,
1544 const std::string& class_loader_context_fds) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001545 CHECK_GE(zip_fd, 0);
Calin Juravlef74a7372019-02-28 20:29:41 -08001546
1547 // We always run the analyzer in the background job.
1548 const char* dexoptanalyzer_bin = select_execution_binary(
1549 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
Calin Juravle80a21252017-01-17 14:43:25 -08001550
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001551 std::string dex_file_arg = "--dex-file=" + dex_file;
1552 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1553 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1554 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1555 std::string isa_arg = "--isa=" + instruction_set;
1556 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1557 const char* assume_profile_changed = "--assume-profile-changed";
1558 const char* downgrade_flag = "--downgrade";
1559 std::string class_loader_context_arg = "--class-loader-context=";
1560 if (class_loader_context != nullptr) {
1561 class_loader_context_arg += class_loader_context;
1562 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001563 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1564 if (!class_loader_context_fds.empty()) {
1565 class_loader_context_fds_arg += class_loader_context_fds;
1566 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001567
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001568 // program name, dex file, isa, filter
1569 AddArg(dex_file_arg);
1570 AddArg(isa_arg);
1571 AddArg(compiler_filter_arg);
1572 if (oat_fd >= 0) {
1573 AddArg(oat_fd_arg);
1574 }
1575 if (vdex_fd >= 0) {
1576 AddArg(vdex_fd_arg);
1577 }
Greg Kaiser8042c372019-03-26 06:23:19 -07001578 AddArg(zip_fd_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001579 if (profile_was_updated) {
1580 AddArg(assume_profile_changed);
1581 }
1582 if (downgrade) {
1583 AddArg(downgrade_flag);
1584 }
1585 if (class_loader_context != nullptr) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001586 AddArg(class_loader_context_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001587 if (!class_loader_context_fds.empty()) {
Greg Kaiser8042c372019-03-26 06:23:19 -07001588 AddArg(class_loader_context_fds_arg);
David Brazdil4f6027a2019-03-19 11:44:21 +00001589 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001590 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001591
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001592 PrepareArgs(dexoptanalyzer_bin);
1593 }
David Brazdil4f6027a2019-03-19 11:44:21 +00001594
1595 // Dexoptanalyzer mode which flattens the given class loader context and
1596 // prints a list of its dex files in that flattened order.
1597 RunDexoptAnalyzer(const char* class_loader_context) {
1598 CHECK(class_loader_context != nullptr);
1599
1600 // We always run the analyzer in the background job.
1601 const char* dexoptanalyzer_bin = select_execution_binary(
1602 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1603
1604 AddArg("--flatten-class-loader-context");
1605 AddArg(std::string("--class-loader-context=") + class_loader_context);
1606 PrepareArgs(dexoptanalyzer_bin);
1607 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001608};
Calin Juravle80a21252017-01-17 14:43:25 -08001609
1610// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001611static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001612 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001613 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001614 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001615 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001616 return false;
1617 }
Calin Juravle114f0812017-03-08 19:05:07 -08001618 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001619
Calin Juravle80a21252017-01-17 14:43:25 -08001620 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001621 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1622 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001623 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001624 return false;
1625 }
1626
1627 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001628 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001629
Calin Juravle7d765462017-09-04 15:57:10 -07001630 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001631 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001632 return false;
1633 }
1634
1635 return true;
1636}
1637
Calin Juravle7d765462017-09-04 15:57:10 -07001638// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1639// secondary dex files. This return codes are returned by the child process created for
1640// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001641
Andreas Gampe194fe422018-02-28 20:16:19 -08001642enum DexoptAnalyzerSkipCodes {
1643 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001644 // Specific errors are encoded in the name.
1645 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1646 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1647 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1648 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1649 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001650 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001651 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001652};
Calin Juravle7d765462017-09-04 15:57:10 -07001653
1654// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001655// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1656// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001657// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1658// of dexoptanalyzer.
1659static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001660 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001661 // The result values are defined in dexoptanalyzer.
1662 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001663 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001664 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001665 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001666 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001667 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001668 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001669 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001670 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001671 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1672 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001673 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1674 " Expected odex file status for secondary dex %s"
1675 " : dexoptanalyzer result=%d",
1676 dex_path.c_str(),
1677 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001678 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001679 }
1680
1681 // Use a second switch for enum switch-case analysis.
1682 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001683 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001684 // If the file does not exist there's no need for dexopt.
1685 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1686 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001687
1688 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1689 *error_msg = "Dexoptanalyzer path validation failed";
1690 return false;
1691 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1692 *error_msg = "Dexoptanalyzer open zip failed";
1693 return false;
1694 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1695 *error_msg = "Dexoptanalyzer dir preparation failed";
1696 return false;
1697 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1698 *error_msg = "Dexoptanalyzer open output failed";
1699 return false;
1700 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1701 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001702 return false;
1703 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001704
1705 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1706 dex_path.c_str(),
1707 result);
1708 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001709}
1710
Calin Juravle7d765462017-09-04 15:57:10 -07001711enum SecondaryDexAccess {
1712 kSecondaryDexAccessReadOk = 0,
1713 kSecondaryDexAccessDoesNotExist = 1,
1714 kSecondaryDexAccessPermissionError = 2,
1715 kSecondaryDexAccessIOError = 3
1716};
1717
1718static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1719 // Check if the path exists and can be read. If not, there's nothing to do.
1720 if (access(dex_path.c_str(), R_OK) == 0) {
1721 return kSecondaryDexAccessReadOk;
1722 } else {
1723 if (errno == ENOENT) {
1724 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1725 return kSecondaryDexAccessDoesNotExist;
1726 } else {
1727 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1728 return errno == EACCES
1729 ? kSecondaryDexAccessPermissionError
1730 : kSecondaryDexAccessIOError;
1731 }
1732 }
1733}
1734
1735static bool is_file_public(const std::string& filename) {
1736 struct stat file_stat;
1737 if (stat(filename.c_str(), &file_stat) == 0) {
1738 return (file_stat.st_mode & S_IROTH) != 0;
1739 }
1740 return false;
1741}
1742
1743// Create the oat file structure for the secondary dex 'dex_path' and assign
1744// the individual path component to the 'out_' parameters.
1745static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001746 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001747 size_t dirIndex = dex_path.rfind('/');
1748 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001749 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001750 return false;
1751 }
1752 // TODO(calin): we have similar computations in at lest 3 other places
1753 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1754 // using string append.
1755 std::string apk_dir = dex_path.substr(0, dirIndex);
1756 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1757 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1758
1759 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1760 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001761 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001762 return false;
1763 }
1764 return true;
1765}
1766
1767// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1768// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001769static bool validate_dexopt_storage_flags(int dexopt_flags,
1770 int* out_storage_flag,
1771 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001772 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1773 *out_storage_flag = FLAG_STORAGE_CE;
1774 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001775 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001776 return false;
1777 }
1778 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1779 *out_storage_flag = FLAG_STORAGE_DE;
1780 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001781 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001782 return false;
1783 }
1784 return true;
1785}
1786
David Brazdil4f6027a2019-03-19 11:44:21 +00001787static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1788 /* out */ std::vector<std::string>* context_dex_paths) {
1789 if (class_loader_context == nullptr) {
1790 return true;
1791 }
1792
1793 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1794
1795 // Pipe to get the hash result back from our child process.
1796 unique_fd pipe_read, pipe_write;
1797 if (!Pipe(&pipe_read, &pipe_write)) {
1798 PLOG(ERROR) << "Failed to create pipe";
1799 return false;
1800 }
1801
1802 pid_t pid = fork();
1803 if (pid == 0) {
1804 // child -- drop privileges before continuing.
1805 drop_capabilities(uid);
1806
1807 // Route stdout to `pipe_write`
1808 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1809 pipe_write.reset();
1810 pipe_read.reset();
1811
1812 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1813 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1814 }
1815
1816 /* parent */
1817 pipe_write.reset();
1818
1819 std::string str_dex_paths;
1820 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1821 PLOG(ERROR) << "Failed to read from pipe";
1822 return false;
1823 }
1824 pipe_read.reset();
1825
1826 int return_code = wait_child(pid);
1827 if (!WIFEXITED(return_code)) {
1828 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1829 return false;
1830 }
1831
1832 constexpr int kFlattenClassLoaderContextSuccess = 50;
1833 return_code = WEXITSTATUS(return_code);
1834 if (return_code != kFlattenClassLoaderContextSuccess) {
1835 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1836 return false;
1837 }
1838
1839 if (!str_dex_paths.empty()) {
1840 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1841 }
1842 return true;
1843}
1844
1845static int open_dex_paths(const std::vector<std::string>& dex_paths,
1846 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1847 for (const std::string& dex_path : dex_paths) {
1848 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1849 if (zip_fds->back().get() < 0) {
1850 *error_msg = StringPrintf(
1851 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1852 if (errno == ENOENT) {
1853 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1854 } else {
1855 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1856 }
1857 }
1858 }
1859 return 0;
1860}
1861
1862static std::string join_fds(const std::vector<unique_fd>& fds) {
1863 std::stringstream ss;
1864 bool is_first = true;
1865 for (const unique_fd& fd : fds) {
1866 if (is_first) {
1867 is_first = false;
1868 } else {
1869 ss << ":";
1870 }
1871 ss << fd.get();
1872 }
1873 return ss.str();
1874}
1875
Calin Juravlec9eab382017-01-25 01:17:17 -08001876// 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 -08001877// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1878// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001879// When returning true, the output parameters will be:
1880// - is_public_out: whether or not the oat file should not be made public
1881// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1882// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001883static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001884 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001885 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001886 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00001887 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001888 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001889 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001890 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1891 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001892 return false;
1893 }
Calin Juravle7d765462017-09-04 15:57:10 -07001894 // Compute the oat dir as it's not easy to extract it from the child computation.
1895 char oat_path[PKG_PATH_MAX];
1896 char oat_dir[PKG_PATH_MAX];
1897 char oat_isa_dir[PKG_PATH_MAX];
1898 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001899 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1900 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001901 return false;
1902 }
Calin Juravle7d765462017-09-04 15:57:10 -07001903 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001904
Calin Juravle80a21252017-01-17 14:43:25 -08001905 pid_t pid = fork();
1906 if (pid == 0) {
1907 // child -- drop privileges before continuing.
1908 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001909
1910 // Validate the path structure.
1911 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1912 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001913 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001914 }
1915
1916 // Open the dex file.
1917 unique_fd zip_fd;
1918 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1919 if (zip_fd.get() < 0) {
1920 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001921 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001922 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001923 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001924 }
1925 }
1926
David Brazdil4f6027a2019-03-19 11:44:21 +00001927 // Open class loader context dex files.
1928 std::vector<unique_fd> context_zip_fds;
1929 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1930 if (open_dex_paths_rc != 0) {
1931 _exit(open_dex_paths_rc);
1932 }
1933
Calin Juravle7d765462017-09-04 15:57:10 -07001934 // Prepare the oat directories.
1935 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001936 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001937 }
1938
1939 // Open the vdex/oat files if any.
1940 unique_fd oat_file_fd;
1941 unique_fd vdex_file_fd;
1942 if (!maybe_open_oat_and_vdex_file(dex_path,
1943 *oat_dir_out,
1944 instruction_set,
1945 true /* is_secondary_dex */,
1946 &oat_file_fd,
1947 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001948 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001949 }
1950
1951 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001952 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1953 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001954
1955 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001956 // Note that we do not do it before the fork since opening the files is required to happen
1957 // after forking.
1958 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1959 vdex_file_fd.get(),
1960 oat_file_fd.get(),
1961 zip_fd.get(),
1962 instruction_set,
1963 compiler_filter, profile_was_updated,
1964 downgrade,
David Brazdil4f6027a2019-03-19 11:44:21 +00001965 class_loader_context,
1966 join_fds(context_zip_fds));
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001967 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001968 }
1969
1970 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001971 int result = wait_child(pid);
1972 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001973 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1974 dex_path.c_str(),
1975 result);
1976 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001977 return false;
1978 }
1979 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001980 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001981 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1982 result,
1983 dexopt_needed_out,
1984 error_msg);
1985 if (!success) {
1986 LOG(ERROR) << *error_msg;
1987 }
Calin Juravle7d765462017-09-04 15:57:10 -07001988
1989 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1990
Calin Juravle80a21252017-01-17 14:43:25 -08001991 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001992 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1993 // makes the code simpler; force compilation is only needed during tests).
1994 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001995 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001996 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001997 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1998 }
1999
Calin Juravle7d765462017-09-04 15:57:10 -07002000 // Check if we should make the oat file public.
2001 // Note that if the dex file is not public the compiled code cannot be made public.
2002 // It is ok to check this flag outside in the parent process.
2003 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
2004
Calin Juravle80a21252017-01-17 14:43:25 -08002005 return success;
2006}
2007
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002008static std::string format_dexopt_error(int status, const char* dex_path) {
2009 if (WIFEXITED(status)) {
2010 int int_code = WEXITSTATUS(status);
2011 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
2012 if (code_name != nullptr) {
2013 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
2014 }
2015 }
2016 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08002017}
2018
Calin Juravlec9eab382017-01-25 01:17:17 -08002019int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08002020 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07002021 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00002022 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08002023 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08002024 CHECK(pkgname != nullptr);
2025 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08002026 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08002027 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
2028 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08002029
Calin Juravled23dee72017-07-06 16:29:11 -07002030 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002031 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07002032 return -1;
2033 }
2034
2035 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002036 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
2037 class_loader_context);
2038 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07002039 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07002040 }
2041
Calin Juravleebc8a792017-04-04 20:21:05 -07002042 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08002043 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
2044 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
2045 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002046 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002047 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08002048 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002049 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002050 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08002051
2052 // Check if we're dealing with a secondary dex file and if we need to compile it.
2053 std::string oat_dir_str;
David Brazdil4f6027a2019-03-19 11:44:21 +00002054 std::vector<std::string> context_dex_paths;
Calin Juravle80a21252017-01-17 14:43:25 -08002055 if (is_secondary_dex) {
David Brazdil4f6027a2019-03-19 11:44:21 +00002056 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
2057 *error_msg = "Failed acquiring context dex paths";
2058 return -1; // We had an error, logged in the process method.
2059 }
2060
Calin Juravlec9eab382017-01-25 01:17:17 -08002061 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07002062 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
David Brazdil4f6027a2019-03-19 11:44:21 +00002063 downgrade, class_loader_context, context_dex_paths, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08002064 oat_dir = oat_dir_str.c_str();
2065 if (dexopt_needed == NO_DEXOPT_NEEDED) {
2066 return 0; // Nothing to do, report success.
2067 }
2068 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08002069 if (error_msg->empty()) { // TODO: Make this a CHECK.
2070 *error_msg = "Failed processing secondary.";
2071 }
Calin Juravle80a21252017-01-17 14:43:25 -08002072 return -1; // We had an error, logged in the process method.
2073 }
2074 } else {
David Brazdil4f6027a2019-03-19 11:44:21 +00002075 // Currently these flags are only used for secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08002076 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002077 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2078 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2079 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002080
2081 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002082 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002083 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002084 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2085 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002086 return -1;
2087 }
2088
David Brazdil4f6027a2019-03-19 11:44:21 +00002089 // Open class loader context dex files.
2090 std::vector<unique_fd> context_input_fds;
2091 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
2092 LOG(ERROR) << *error_msg;
2093 return -1;
2094 }
2095
Calin Juravle7a570e82017-01-14 16:23:30 -08002096 // Create the output OAT file.
2097 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002098 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002099 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002100 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002101 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002102 return -1;
2103 }
2104
2105 // Open vdex files.
2106 Dex2oatFileWrapper in_vdex_fd;
2107 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002108 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2109 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002110 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002111 return -1;
2112 }
2113
Calin Juravlecb556e32017-04-04 20:22:50 -07002114 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2115 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2116 // fully inherit their parent context).
2117 // Note that for primary apk the oat files are created before, in a separate installd
2118 // call which also does the restorecon. TODO(calin): unify the paths.
2119 if (is_secondary_dex) {
2120 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2121 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002122 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2123 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002124 return -1;
2125 }
2126 }
2127
Jeff Sharkey90aff262016-12-12 14:28:24 -07002128 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002129 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002130
Calin Juravle7a570e82017-01-14 16:23:30 -08002131 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002132 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002133 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002134
liulvping61907742018-08-21 09:36:52 +08002135 if (reference_profile_fd.get() == -1) {
2136 // We don't create an app image without reference profile since there is no speedup from
2137 // loading it in that case and instead will be a small overhead.
2138 generate_app_image = false;
2139 }
2140
2141 // Create the app image file if needed.
2142 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2143 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
2144
Calin Juravle62c5a372018-02-01 17:03:23 +00002145 unique_fd dex_metadata_fd;
2146 if (dex_metadata_path != nullptr) {
2147 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2148 if (dex_metadata_fd.get() < 0) {
2149 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2150 }
2151 }
2152
Andreas Gampe023b2242018-02-28 16:03:25 -08002153 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002154
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002155 RunDex2Oat runner(input_fd.get(),
2156 out_oat_fd.get(),
2157 in_vdex_fd.get(),
2158 out_vdex_fd.get(),
2159 image_fd.get(),
2160 dex_path,
2161 out_oat_path,
2162 swap_fd.get(),
2163 instruction_set,
2164 compiler_filter,
2165 debuggable,
2166 boot_complete,
2167 background_job_compile,
2168 reference_profile_fd.get(),
2169 class_loader_context,
David Brazdil4f6027a2019-03-19 11:44:21 +00002170 join_fds(context_input_fds),
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002171 target_sdk_version,
2172 enable_hidden_api_checks,
2173 generate_compact_dex,
2174 dex_metadata_fd.get(),
2175 compilation_reason);
2176
Jeff Sharkey90aff262016-12-12 14:28:24 -07002177 pid_t pid = fork();
2178 if (pid == 0) {
2179 /* child -- drop privileges before continuing */
2180 drop_capabilities(uid);
2181
Richard Uhler76cc0272016-12-08 10:46:35 +00002182 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002183 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002184 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002185 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002186 }
2187
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002188 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002189 } else {
2190 int res = wait_child(pid);
2191 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002192 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002193 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002194 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2195 << std::hex << std::setw(4) << res << ", process failed";
2196 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002197 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002198 }
2199 }
2200
Calin Juravlec9eab382017-01-25 01:17:17 -08002201 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002202
2203 // We've been successful, don't delete output.
2204 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002205 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002206 image_fd.SetCleanup(false);
2207 reference_profile_fd.SetCleanup(false);
2208
2209 return 0;
2210}
2211
Calin Juravlec9eab382017-01-25 01:17:17 -08002212// Try to remove the given directory. Log an error if the directory exists
2213// and is empty but could not be removed.
2214static bool rmdir_if_empty(const char* dir) {
2215 if (rmdir(dir) == 0) {
2216 return true;
2217 }
2218 if (errno == ENOENT || errno == ENOTEMPTY) {
2219 return true;
2220 }
2221 PLOG(ERROR) << "Failed to remove dir: " << dir;
2222 return false;
2223}
2224
2225// Try to unlink the given file. Log an error if the file exists and could not
2226// be unlinked.
2227static bool unlink_if_exists(const std::string& file) {
2228 if (unlink(file.c_str()) == 0) {
2229 return true;
2230 }
2231 if (errno == ENOENT) {
2232 return true;
2233
2234 }
2235 PLOG(ERROR) << "Could not unlink: " << file;
2236 return false;
2237}
2238
Calin Juravle7d765462017-09-04 15:57:10 -07002239enum ReconcileSecondaryDexResult {
2240 kReconcileSecondaryDexExists = 0,
2241 kReconcileSecondaryDexCleanedUp = 1,
2242 kReconcileSecondaryDexValidationError = 2,
2243 kReconcileSecondaryDexCleanUpError = 3,
2244 kReconcileSecondaryDexAccessIOError = 4,
2245};
Calin Juravlec9eab382017-01-25 01:17:17 -08002246
2247// Reconcile the secondary dex 'dex_path' and its generated oat files.
2248// Return true if all the parameters are valid and the secondary dex file was
2249// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2250// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2251// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2252// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2253// Return false if there were errors during processing. In this case
2254// out_secondary_dex_exists will be set to false.
2255bool reconcile_secondary_dex_file(const std::string& dex_path,
2256 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2257 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2258 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002259 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002260 if (isas.size() == 0) {
2261 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2262 return false;
2263 }
2264
Calin Juravle7d765462017-09-04 15:57:10 -07002265 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2266 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2267 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002268 return false;
2269 }
2270
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002271 // As a security measure we want to unlink art artifacts with the reduced capabilities
2272 // of the package user id. So we fork and drop capabilities in the child.
2273 pid_t pid = fork();
2274 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002275 /* child -- drop privileges before continuing */
2276 drop_capabilities(uid);
2277
2278 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Greg Kaiser8042c372019-03-26 06:23:19 -07002279 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
Calin Juravle7d765462017-09-04 15:57:10 -07002280 uid, storage_flag)) {
2281 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2282 _exit(kReconcileSecondaryDexValidationError);
2283 }
2284
2285 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2286 switch (access_check) {
2287 case kSecondaryDexAccessDoesNotExist:
2288 // File does not exist. Proceed with cleaning.
2289 break;
2290 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2291 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2292 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2293 default:
2294 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2295 _exit(kReconcileSecondaryDexValidationError);
2296 }
2297
2298 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002299 char oat_path[PKG_PATH_MAX];
2300 char oat_dir[PKG_PATH_MAX];
2301 char oat_isa_dir[PKG_PATH_MAX];
2302 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002303 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002304 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002305 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002306 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2307 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002308 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002309 }
Calin Juravle51314092017-05-18 15:33:05 -07002310
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002311 // Delete oat/vdex/art files.
2312 result = unlink_if_exists(oat_path) && result;
2313 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2314 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002315
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002316 // Delete profiles.
2317 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002318 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002319 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002320 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002321 result = unlink_if_exists(current_profile) && result;
2322 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002323
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002324 // We upgraded once the location of current profile for secondary dex files.
2325 // Check for any previous left-overs and remove them as well.
2326 std::string old_current_profile = dex_path + ".prof";
2327 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002328
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002329 // Try removing the directories as well, they might be empty.
2330 result = rmdir_if_empty(oat_isa_dir) && result;
2331 result = rmdir_if_empty(oat_dir) && result;
2332 }
Calin Juravle7d765462017-09-04 15:57:10 -07002333 if (!result) {
2334 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2335 }
2336 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002337 }
2338
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002339 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002340 if (!WIFEXITED(return_code)) {
2341 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2342 } else {
2343 return_code = WEXITSTATUS(return_code);
2344 }
2345
2346 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2347
2348 switch (return_code) {
2349 case kReconcileSecondaryDexCleanedUp:
2350 case kReconcileSecondaryDexValidationError:
2351 // If we couldn't validate assume the dex file does not exist.
2352 // This will purge the entry from the PM records.
2353 *out_secondary_dex_exists = false;
2354 return true;
2355 case kReconcileSecondaryDexExists:
2356 *out_secondary_dex_exists = true;
2357 return true;
2358 case kReconcileSecondaryDexAccessIOError:
2359 // We had an access IO error.
2360 // Return false so that we can try again.
2361 // The value of out_secondary_dex_exists does not matter in this case and by convention
2362 // is set to false.
2363 *out_secondary_dex_exists = false;
2364 return false;
2365 default:
2366 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2367 *out_secondary_dex_exists = false;
2368 return false;
2369 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002370}
2371
Alan Stokesa25d90c2017-10-16 10:56:00 +01002372// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2373// Returns true if all parameters are valid and the hash successfully computed and stored in
2374// out_secondary_dex_hash.
2375// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2376// the app.
2377// For any other errors (e.g. if any of the parameters are invalid) returns false.
2378bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2379 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2380 std::vector<uint8_t>* out_secondary_dex_hash) {
2381 out_secondary_dex_hash->clear();
2382
2383 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2384
2385 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2386 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2387 << storage_flag;
2388 return false;
2389 }
2390
2391 // Pipe to get the hash result back from our child process.
2392 unique_fd pipe_read, pipe_write;
2393 if (!Pipe(&pipe_read, &pipe_write)) {
2394 PLOG(ERROR) << "Failed to create pipe";
2395 return false;
2396 }
2397
2398 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2399 // access data the app itself can access.
2400 pid_t pid = fork();
2401 if (pid == 0) {
2402 // child -- drop privileges before continuing
2403 drop_capabilities(uid);
2404 pipe_read.reset();
2405
2406 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2407 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002408 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002409 }
2410
2411 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2412 if (fd == -1) {
2413 if (errno == EACCES || errno == ENOENT) {
2414 // Not treated as an error.
2415 _exit(0);
2416 }
2417 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002418 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002419 }
2420
2421 SHA256_CTX ctx;
2422 SHA256_Init(&ctx);
2423
2424 std::vector<uint8_t> buffer(65536);
2425 while (true) {
2426 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2427 if (bytes_read == 0) {
2428 break;
2429 } else if (bytes_read == -1) {
2430 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002431 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002432 }
2433
2434 SHA256_Update(&ctx, buffer.data(), bytes_read);
2435 }
2436
2437 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2438 SHA256_Final(hash.data(), &ctx);
2439 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002440 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002441 }
2442
2443 _exit(0);
2444 }
2445
2446 // parent
2447 pipe_write.reset();
2448
2449 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2450 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2451 out_secondary_dex_hash->clear();
2452 }
2453 return wait_child(pid) == 0;
2454}
2455
Jeff Sharkey90aff262016-12-12 14:28:24 -07002456// Helper for move_ab, so that we can have common failure-case cleanup.
2457static bool unlink_and_rename(const char* from, const char* to) {
2458 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2459 // return a failure.
2460 struct stat s;
2461 if (stat(to, &s) == 0) {
2462 if (!S_ISREG(s.st_mode)) {
2463 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2464 return false;
2465 }
2466 if (unlink(to) != 0) {
2467 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2468 return false;
2469 }
2470 } else {
2471 // This may be a permission problem. We could investigate the error code, but we'll just
2472 // let the rename failure do the work for us.
2473 }
2474
2475 // Try to rename "to" to "from."
2476 if (rename(from, to) != 0) {
2477 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2478 return false;
2479 }
2480 return true;
2481}
2482
2483// Move/rename a B artifact (from) to an A artifact (to).
2484static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2485 // Check whether B exists.
2486 {
2487 struct stat s;
2488 if (stat(b_path.c_str(), &s) != 0) {
2489 // Silently ignore for now. The service calling this isn't smart enough to understand
2490 // lack of artifacts at the moment.
2491 return false;
2492 }
2493 if (!S_ISREG(s.st_mode)) {
2494 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2495 // Try to unlink, but swallow errors.
2496 unlink(b_path.c_str());
2497 return false;
2498 }
2499 }
2500
2501 // Rename B to A.
2502 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2503 // Delete the b_path so we don't try again (or fail earlier).
2504 if (unlink(b_path.c_str()) != 0) {
2505 PLOG(ERROR) << "Could not unlink " << b_path;
2506 }
2507
2508 return false;
2509 }
2510
2511 return true;
2512}
2513
2514bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2515 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002516 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2517 if (slot_suffix.empty()) {
2518 return false;
2519 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002520
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002521 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2522 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2523 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002524 }
2525
2526 // Validate other inputs.
2527 if (validate_apk_path(apk_path) != 0) {
2528 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2529 return false;
2530 }
2531 if (validate_apk_path(oat_dir) != 0) {
2532 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2533 return false;
2534 }
2535
2536 char a_path[PKG_PATH_MAX];
2537 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2538 return false;
2539 }
2540 const std::string a_vdex_path = create_vdex_filename(a_path);
2541 const std::string a_image_path = create_image_filename(a_path);
2542
2543 // B path = A path + slot suffix.
2544 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2545 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2546 const std::string b_image_path = StringPrintf("%s.%s",
2547 a_image_path.c_str(),
2548 slot_suffix.c_str());
2549
2550 bool success = true;
2551 if (move_ab_path(b_path, a_path)) {
2552 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2553 // Note: we can live without an app image. As such, ignore failure to move the image file.
2554 // If we decide to require the app image, or the app image being moved correctly,
2555 // then change accordingly.
2556 constexpr bool kIgnoreAppImageFailure = true;
2557
2558 if (!a_image_path.empty()) {
2559 if (!move_ab_path(b_image_path, a_image_path)) {
2560 unlink(a_image_path.c_str());
2561 if (!kIgnoreAppImageFailure) {
2562 success = false;
2563 }
2564 }
2565 }
2566 } else {
2567 // Cleanup: delete B image, ignore errors.
2568 unlink(b_image_path.c_str());
2569 success = false;
2570 }
2571 } else {
2572 // Cleanup: delete B image, ignore errors.
2573 unlink(b_vdex_path.c_str());
2574 unlink(b_image_path.c_str());
2575 success = false;
2576 }
2577 return success;
2578}
2579
2580bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2581 // Delete the oat/odex file.
2582 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002583 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002584 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002585 return false;
2586 }
2587
2588 // In case of a permission failure report the issue. Otherwise just print a warning.
2589 auto unlink_and_check = [](const char* path) -> bool {
2590 int result = unlink(path);
2591 if (result != 0) {
2592 if (errno == EACCES || errno == EPERM) {
2593 PLOG(ERROR) << "Could not unlink " << path;
2594 return false;
2595 }
2596 PLOG(WARNING) << "Could not unlink " << path;
2597 }
2598 return true;
2599 };
2600
2601 // Delete the oat/odex file.
2602 bool return_value_oat = unlink_and_check(out_path);
2603
2604 // Derive and delete the app image.
2605 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2606
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002607 // Derive and delete the vdex file.
2608 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2609
Jeff Sharkey90aff262016-12-12 14:28:24 -07002610 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002611 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002612}
2613
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002614static bool is_absolute_path(const std::string& path) {
2615 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2616 LOG(ERROR) << "Invalid absolute path " << path;
2617 return false;
2618 } else {
2619 return true;
2620 }
2621}
2622
2623static bool is_valid_instruction_set(const std::string& instruction_set) {
2624 // TODO: add explicit whitelisting of instruction sets
2625 if (instruction_set.find('/') != std::string::npos) {
2626 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2627 return false;
2628 } else {
2629 return true;
2630 }
2631}
2632
2633bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2634 const char *apk_path, const char *instruction_set) {
2635 std::string oat_dir_ = oat_dir;
2636 std::string apk_path_ = apk_path;
2637 std::string instruction_set_ = instruction_set;
2638
2639 if (!is_absolute_path(oat_dir_)) return false;
2640 if (!is_absolute_path(apk_path_)) return false;
2641 if (!is_valid_instruction_set(instruction_set_)) return false;
2642
2643 std::string::size_type end = apk_path_.rfind('.');
2644 std::string::size_type start = apk_path_.rfind('/', end);
2645 if (end == std::string::npos || start == std::string::npos) {
2646 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2647 return false;
2648 }
2649
2650 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2651 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2652 const char* res = res_.c_str();
2653 if (strlen(res) >= PKG_PATH_MAX) {
2654 LOG(ERROR) << "Result too large";
2655 return false;
2656 } else {
2657 strlcpy(path, res, PKG_PATH_MAX);
2658 return true;
2659 }
2660}
2661
2662bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2663 const char *instruction_set) {
2664 std::string apk_path_ = apk_path;
2665 std::string instruction_set_ = instruction_set;
2666
2667 if (!is_absolute_path(apk_path_)) return false;
2668 if (!is_valid_instruction_set(instruction_set_)) return false;
2669
2670 std::string::size_type end = apk_path_.rfind('.');
2671 std::string::size_type start = apk_path_.rfind('/', end);
2672 if (end == std::string::npos || start == std::string::npos) {
2673 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2674 return false;
2675 }
2676
2677 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2678 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2679}
2680
2681bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2682 const char *instruction_set) {
2683 std::string src_ = src;
2684 std::string instruction_set_ = instruction_set;
2685
2686 if (!is_absolute_path(src_)) return false;
2687 if (!is_valid_instruction_set(instruction_set_)) return false;
2688
2689 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2690 if (*it == '/') {
2691 *it = '@';
2692 }
2693 }
2694
2695 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2696 + DALVIK_CACHE_POSTFIX;
2697 const char* res = res_.c_str();
2698 if (strlen(res) >= PKG_PATH_MAX) {
2699 LOG(ERROR) << "Result too large";
2700 return false;
2701 } else {
2702 strlcpy(path, res, PKG_PATH_MAX);
2703 return true;
2704 }
2705}
2706
Calin Juravle59f7ab82018-04-27 17:50:23 -07002707bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2708 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002709 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2710 for (const std::string& elem : classpaths_elems) {
2711 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2712 if (fd < 0) {
2713 PLOG(ERROR) << "Could not open classpath elem " << elem;
2714 return false;
2715 } else {
2716 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002717 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002718 }
2719 }
2720 return true;
2721}
2722
2723static bool create_app_profile_snapshot(int32_t app_id,
2724 const std::string& package_name,
2725 const std::string& profile_name,
2726 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002727 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2728
Calin Juravle824a64d2018-01-18 20:23:17 -08002729 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002730 if (snapshot_fd < 0) {
2731 return false;
2732 }
2733
2734 std::vector<unique_fd> profiles_fd;
2735 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002736 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2737 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002738 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2739 return false;
2740 }
2741
2742 profiles_fd.push_back(std::move(reference_profile_fd));
2743
Calin Juravle0d0a4922018-01-23 19:54:11 -08002744 // Open the class paths elements. These will be used to filter out profile data that does
2745 // not belong to the classpath during merge.
2746 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002747 std::vector<std::string> dex_locations;
2748 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002749 return false;
2750 }
2751
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002752 RunProfman args;
2753 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002754 pid_t pid = fork();
2755 if (pid == 0) {
2756 /* child -- drop privileges before continuing */
2757 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002758 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002759 }
2760
2761 /* parent */
2762 int return_code = wait_child(pid);
2763 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002764 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002765 return false;
2766 }
2767
2768 return true;
2769}
2770
Calin Juravle0d0a4922018-01-23 19:54:11 -08002771static bool create_boot_image_profile_snapshot(const std::string& package_name,
2772 const std::string& profile_name,
2773 const std::string& classpath) {
2774 // The reference profile directory for the android package might not be prepared. Do it now.
2775 const std::string ref_profile_dir =
2776 create_primary_reference_profile_package_dir_path(package_name);
2777 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2778 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2779 return false;
2780 }
2781
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002782 // Return false for empty class path since it may otherwise return true below if profiles is
2783 // empty.
2784 if (classpath.empty()) {
2785 PLOG(ERROR) << "Class path is empty";
2786 return false;
2787 }
2788
Calin Juravle0d0a4922018-01-23 19:54:11 -08002789 // Open and create the snapshot profile.
2790 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2791
2792 // Collect all non empty profiles.
2793 // The collection will traverse all applications profiles and find the non empty files.
2794 // This has the potential of inspecting a large number of files and directories (depending
2795 // on the number of applications and users). So there is a slight increase in the chance
2796 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2797 // fail the snapshot and aggregate whatever profile we could open.
2798 //
2799 // The profile snapshot is a best effort based on available data it's ok if some data
2800 // from some apps is missing. It will be counter productive for the snapshot to fail
2801 // because we could not open or read some of the files.
2802 std::vector<std::string> profiles;
2803 if (!collect_profiles(&profiles)) {
2804 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2805 }
2806
2807 // If we have no profiles return early.
2808 if (profiles.empty()) {
2809 return true;
2810 }
2811
2812 // Open the classpath elements. These will be used to filter out profile data that does
2813 // not belong to the classpath during merge.
2814 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002815 std::vector<std::string> dex_locations;
2816 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002817 return false;
2818 }
2819
2820 // If we could not open any files from the classpath return an error.
2821 if (apk_fds.empty()) {
2822 LOG(ERROR) << "Could not open any of the classpath elements.";
2823 return false;
2824 }
2825
2826 // Aggregate the profiles in batches of kAggregationBatchSize.
2827 // We do this to avoid opening a huge a amount of files.
2828 static constexpr size_t kAggregationBatchSize = 10;
2829
2830 std::vector<unique_fd> profiles_fd;
2831 for (size_t i = 0; i < profiles.size(); ) {
2832 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2833 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2834 if (fd.get() >= 0) {
2835 profiles_fd.push_back(std::move(fd));
2836 }
2837 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002838 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002839 args.SetupMerge(profiles_fd,
2840 snapshot_fd,
2841 apk_fds,
2842 dex_locations,
2843 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002844 pid_t pid = fork();
2845 if (pid == 0) {
2846 /* child -- drop privileges before continuing */
2847 drop_capabilities(AID_SYSTEM);
2848
Calin Juravle59f7ab82018-04-27 17:50:23 -07002849 // The introduction of new access flags into boot jars causes them to
2850 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002851 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002852 }
2853
2854 /* parent */
2855 int return_code = wait_child(pid);
2856 if (!WIFEXITED(return_code)) {
2857 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2858 return false;
2859 }
2860 return true;
2861 }
2862 return true;
2863}
2864
2865bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2866 const std::string& profile_name, const std::string& classpath) {
2867 if (app_id == -1) {
2868 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2869 } else {
2870 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2871 }
2872}
2873
Calin Juravlec3b049e2018-01-18 22:32:58 -08002874bool prepare_app_profile(const std::string& package_name,
2875 userid_t user_id,
2876 appid_t app_id,
2877 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002878 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002879 const std::unique_ptr<std::string>& dex_metadata) {
2880 // Prepare the current profile.
2881 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2882 /*is_secondary_dex*/ false);
2883 uid_t uid = multiuser_get_uid(user_id, app_id);
2884 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2885 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2886 return false;
2887 }
2888
2889 // Check if we need to install the profile from the dex metadata.
2890 if (dex_metadata == nullptr) {
2891 return true;
2892 }
2893
2894 // We have a dex metdata. Merge the profile into the reference profile.
2895 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2896 /*read_write*/ true, /*is_secondary_dex*/ false);
2897 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2898 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002899 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2900 if (apk_fd < 0) {
2901 PLOG(ERROR) << "Could not open code path " << code_path;
2902 return false;
2903 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002904
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002905 RunProfman args;
2906 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2907 std::move(ref_profile_fd),
2908 std::move(apk_fd),
2909 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002910 pid_t pid = fork();
2911 if (pid == 0) {
2912 /* child -- drop privileges before continuing */
2913 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2914 drop_capabilities(app_shared_gid);
2915
Calin Juravlef63d4792018-01-30 17:43:34 +00002916 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002917 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002918 }
2919
2920 /* parent */
2921 int return_code = wait_child(pid);
2922 if (!WIFEXITED(return_code)) {
2923 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2924 return false;
2925 }
2926 return true;
2927}
2928
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002929} // namespace installd
2930} // namespace android