blob: 25e5247c68bca37a213c9a80a0b77776b5bbf4b6 [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>
Calin Juravlecb556e32017-04-04 20:22:50 -070046#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070047#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070048
49#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080050#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060051#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070052#include "installd_deps.h"
53#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070054#include "utils.h"
55
Jeff Sharkey90aff262016-12-12 14:28:24 -070056using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070057using android::base::GetBoolProperty;
58using android::base::GetProperty;
Alan Stokesa25d90c2017-10-16 10:56:00 +010059using android::base::ReadFully;
60using android::base::StringPrintf;
61using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080062using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070063
64namespace android {
65namespace installd {
66
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070067// Should minidebug info be included in compiled artifacts? Even if this value is
68// "true," usage might still be conditional to other constraints, e.g., system
69// property overrides.
70static constexpr bool kEnableMinidebugInfo = true;
71
72static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
73static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
74static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080075static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070076
Andreas Gampefa2dadd2018-02-28 19:52:47 -080077
Calin Juravle114f0812017-03-08 19:05:07 -080078// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
79struct FreeDelete {
80 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
81 void operator()(const void* ptr) const {
82 free(const_cast<void*>(ptr));
83 }
84};
85
86// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
87template <typename T>
88using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
89
Calin Juravle1a0af3b2017-03-09 14:33:33 -080090static unique_fd invalid_unique_fd() {
91 return unique_fd(-1);
92}
93
Andreas Gampe6a9cf722017-07-24 16:49:10 -070094static bool is_debug_runtime() {
95 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
96}
97
David Sehra3b5ab62017-10-25 14:27:29 -070098static bool is_debuggable_build() {
99 return android::base::GetBoolProperty("ro.debuggable", false);
100}
101
Jeff Sharkey90aff262016-12-12 14:28:24 -0700102static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800103 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700104 if (ufd.get() < 0) {
105 if (errno != ENOENT) {
106 PLOG(WARNING) << "Could not open profile " << profile;
107 return false;
108 } else {
109 // Nothing to clear. That's ok.
110 return true;
111 }
112 }
113
114 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
115 if (errno != EWOULDBLOCK) {
116 PLOG(WARNING) << "Error locking profile " << profile;
117 }
118 // This implies that the app owning this profile is running
119 // (and has acquired the lock).
120 //
121 // If we can't acquire the lock bail out since clearing is useless anyway
122 // (the app will write again to the profile).
123 //
124 // Note:
125 // This does not impact the this is not an issue for the profiling correctness.
126 // In case this is needed because of an app upgrade, profiles will still be
127 // eventually cleared by the app itself due to checksum mismatch.
128 // If this is needed because profman advised, then keeping the data around
129 // until the next run is again not an issue.
130 //
131 // If the app attempts to acquire a lock while we've held one here,
132 // it will simply skip the current write cycle.
133 return false;
134 }
135
136 bool truncated = ftruncate(ufd.get(), 0) == 0;
137 if (!truncated) {
138 PLOG(WARNING) << "Could not truncate " << profile;
139 }
140 if (flock(ufd.get(), LOCK_UN) != 0) {
141 PLOG(WARNING) << "Error unlocking profile " << profile;
142 }
143 return truncated;
144}
145
Calin Juravle114f0812017-03-08 19:05:07 -0800146// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800147// The location is the profile name for primary apks or the dex path for secondary dex files.
148static bool clear_reference_profile(const std::string& package_name, const std::string& location,
149 bool is_secondary_dex) {
150 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700151}
152
Calin Juravle114f0812017-03-08 19:05:07 -0800153// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800154// The location is the profile name for primary apks or the dex path for secondary dex files.
155static bool clear_current_profile(const std::string& package_name, const std::string& location,
156 userid_t user, bool is_secondary_dex) {
157 return clear_profile(create_current_profile_path(user, package_name, location,
158 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700159}
160
Calin Juravle114f0812017-03-08 19:05:07 -0800161// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800162// The location is the profile name for primary apks or the dex path for secondary dex files.
163bool clear_primary_reference_profile(const std::string& package_name,
164 const std::string& location) {
165 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800166}
167
168// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800169// The location is the profile name for primary apks or the dex path for secondary dex files.
170bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700171 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800172 // 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 -0700173 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
174 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800175 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700176 }
177 return success;
178}
179
Calin Juravle114f0812017-03-08 19:05:07 -0800180// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800181bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
182 userid_t user) {
183 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800184}
185
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700186static std::vector<std::string> SplitBySpaces(const std::string& str) {
187 if (str.empty()) {
188 return {};
189 }
190 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700191}
192
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700193static const char* get_location_from_path(const char* path) {
194 static constexpr char kLocationSeparator = '/';
195 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700196 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700197 return path;
198 } else {
199 // Skip the separator character.
200 return location + 1;
201 }
202}
203
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800204// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
205// need to be performed between the fork and exec.
206class ExecVHelper {
207 public:
208 // Store a placeholder for the binary name.
209 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800210
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800211 void PrepareArgs(const std::string& bin) {
212 CHECK(!args_.empty());
213 CHECK(args_[0].empty());
214 args_[0] = bin;
215 // Write char* into array.
216 for (const std::string& arg : args_) {
217 argv_.push_back(arg.c_str());
218 }
219 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800220 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800221
222 [[ noreturn ]]
223 void Exec(int exit_code) {
224 execv(argv_[0], (char * const *)&argv_[0]);
225 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
226 exit(exit_code);
227 }
228
229 // Add an arg if it's not empty.
230 void AddArg(const std::string& arg) {
231 if (!arg.empty()) {
232 args_.push_back(arg);
233 }
234 }
235
236 // Add a runtime arg if it's not empty.
237 void AddRuntimeArg(const std::string& arg) {
238 if (!arg.empty()) {
239 args_.push_back("--runtime-arg");
240 args_.push_back(arg);
241 }
242 }
243
244 protected:
245 // Holder arrays for backing arg storage.
246 std::vector<std::string> args_;
247
248 // Argument poiners.
249 std::vector<const char*> argv_;
250};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700251
252static std::string MapPropertyToArg(const std::string& property,
253 const std::string& format,
254 const std::string& default_value = "") {
255 std::string prop = GetProperty(property, default_value);
256 if (!prop.empty()) {
257 return StringPrintf(format.c_str(), prop.c_str());
258 }
259 return "";
260}
261
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800262class RunDex2Oat : public ExecVHelper {
263 public:
264 RunDex2Oat(int zip_fd,
265 int oat_fd,
266 int input_vdex_fd,
267 int output_vdex_fd,
268 int image_fd,
269 const char* input_file_name,
270 const char* output_file_name,
271 int swap_fd,
272 const char* instruction_set,
273 const char* compiler_filter,
274 bool debuggable,
275 bool post_bootcomplete,
276 bool background_job_compile,
277 int profile_fd,
278 const char* class_loader_context,
279 int target_sdk_version,
280 bool enable_hidden_api_checks,
281 bool generate_compact_dex,
282 int dex_metadata_fd,
283 const char* compilation_reason) {
284 // Get the relative path to the input file.
285 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700286
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800287 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
288 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700289
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800290 const char* threads_property = post_bootcomplete
291 ? "dalvik.vm.dex2oat-threads"
292 : "dalvik.vm.boot-dex2oat-threads";
293 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700294
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800295 const std::string dex2oat_isa_features_key =
296 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
297 std::string instruction_set_features_arg =
298 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700299
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800300 const std::string dex2oat_isa_variant_key =
301 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
302 std::string instruction_set_variant_arg =
303 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700304
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800305 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700306
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800307 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
308 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
309 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700310
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800311 // If we are booting without the real /data, don't spend time compiling.
312 std::string vold_decrypt = GetProperty("vold.decrypt", "");
313 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
314 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700315
Mathieu Chartier5880c032018-11-28 19:15:41 -0800316 const std::string resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800317 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
318 "--resolve-startup-const-strings=%s");
Mathieu Chartier5880c032018-11-28 19:15:41 -0800319
320 const std::string image_block_size_arg =
321 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
322 "--max-image-block-size=%s");
323
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800324 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700325
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800326 std::string image_format_arg;
327 if (image_fd >= 0) {
328 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000329 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000330
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800331 std::string dex2oat_large_app_threshold_arg =
332 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000333
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800334 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
335 const char* dex2oat_bin = "/system/bin/dex2oat";
336 constexpr const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
337 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
338 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
339 if (is_debug_runtime() ||
340 (background_job_compile && is_debuggable_build() && !is_release)) {
341 if (access(kDex2oatDebugPath, X_OK) == 0) {
342 dex2oat_bin = kDex2oatDebugPath;
343 }
344 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000345
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800346 bool generate_minidebug_info = kEnableMinidebugInfo &&
347 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
350 // use arraysize instead.
351 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
352 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
353 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
354 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
355 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
356 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
357 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
358 std::string dex2oat_compiler_filter_arg;
359 std::string dex2oat_swap_fd;
360 std::string dex2oat_image_fd;
361 std::string target_sdk_version_arg;
362 if (target_sdk_version != 0) {
363 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
364 }
365 std::string class_loader_context_arg;
366 if (class_loader_context != nullptr) {
367 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
368 class_loader_context);
369 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000370
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800371 if (swap_fd >= 0) {
372 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
373 }
374 if (image_fd >= 0) {
375 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
376 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000377
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800378 // Compute compiler filter.
379 bool have_dex2oat_relocation_skip_flag = false;
380 if (skip_compilation) {
381 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
382 have_dex2oat_relocation_skip_flag = true;
383 } else if (compiler_filter != nullptr) {
384 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
385 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000386
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800387 if (dex2oat_compiler_filter_arg.empty()) {
388 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
389 "--compiler-filter=%s");
390 }
391
392 // Check whether all apps should be compiled debuggable.
393 if (!debuggable) {
394 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
395 }
396 std::string profile_arg;
397 if (profile_fd != -1) {
398 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
399 }
400
401 // Get the directory of the apk to pass as a base classpath directory.
402 std::string base_dir;
403 std::string apk_dir(input_file_name);
404 unsigned long dir_index = apk_dir.rfind('/');
405 bool has_base_dir = dir_index != std::string::npos;
406 if (has_base_dir) {
407 apk_dir = apk_dir.substr(0, dir_index);
408 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
409 }
410
411 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
412
413 std::string compilation_reason_arg = compilation_reason == nullptr
414 ? ""
415 : std::string("--compilation-reason=") + compilation_reason;
416
417 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
418
419 // Disable cdex if update input vdex is true since this combination of options is not
420 // supported.
421 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
422
423 AddArg(zip_fd_arg);
424 AddArg(zip_location_arg);
425 AddArg(input_vdex_fd_arg);
426 AddArg(output_vdex_fd_arg);
427 AddArg(oat_fd_arg);
428 AddArg(oat_location_arg);
429 AddArg(instruction_set_arg);
430
431 AddArg(instruction_set_variant_arg);
432 AddArg(instruction_set_features_arg);
433
434 AddRuntimeArg(dex2oat_Xms_arg);
435 AddRuntimeArg(dex2oat_Xmx_arg);
436
437 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800438 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800439 AddArg(dex2oat_compiler_filter_arg);
440 AddArg(dex2oat_threads_arg);
441 AddArg(dex2oat_swap_fd);
442 AddArg(dex2oat_image_fd);
443
444 if (generate_debug_info) {
445 AddArg("--generate-debug-info");
446 }
447 if (debuggable) {
448 AddArg("--debuggable");
449 }
450 AddArg(image_format_arg);
451 AddArg(dex2oat_large_app_threshold_arg);
452
453 if (have_dex2oat_relocation_skip_flag) {
454 AddRuntimeArg(dex2oat_norelocation);
455 }
456 AddArg(profile_arg);
457 AddArg(base_dir);
458 AddArg(class_loader_context_arg);
459 if (generate_minidebug_info) {
460 AddArg(kMinidebugDex2oatFlag);
461 }
462 if (disable_cdex) {
463 AddArg(kDisableCompactDexFlag);
464 }
465 AddArg(target_sdk_version_arg);
466 if (enable_hidden_api_checks) {
467 AddRuntimeArg("-Xhidden-api-checks");
468 }
469
470 if (dex_metadata_fd > -1) {
471 AddArg(dex_metadata_fd_arg);
472 }
473
474 AddArg(compilation_reason_arg);
475
476 // Do not add args after dex2oat_flags, they should override others for debugging.
477 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
478
479 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000480 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800481};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700482
483/*
484 * Whether dexopt should use a swap file when compiling an APK.
485 *
486 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
487 * itself, anyways).
488 *
489 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
490 *
491 * Otherwise, return true if this is a low-mem device.
492 *
493 * Otherwise, return default value.
494 */
495static bool kAlwaysProvideSwapFile = false;
496static bool kDefaultProvideSwapFile = true;
497
498static bool ShouldUseSwapFileForDexopt() {
499 if (kAlwaysProvideSwapFile) {
500 return true;
501 }
502
503 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700504 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
505 if (!dex2oat_prop_buf.empty()) {
506 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700507 }
508
509 // Shortcut for default value. This is an implementation optimization for the process sketched
510 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
511 // as low-mem is never returning false. The compiler will optimize this away if it can.
512 if (kDefaultProvideSwapFile) {
513 return true;
514 }
515
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700516 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700517 return true;
518 }
519
520 // Default value must be false here.
521 return kDefaultProvideSwapFile;
522}
523
Richard Uhler76cc0272016-12-08 10:46:35 +0000524static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525 if (set_to_bg) {
526 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800527 PLOG(ERROR) << "set_sched_policy failed";
528 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700529 }
530 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800531 PLOG(ERROR) << "setpriority failed";
532 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700533 }
534 }
535}
536
Calin Juravle29591732017-11-20 17:46:19 -0800537static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
538 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800539 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800540 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800541 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800542 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800543 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700544 }
Calin Juravle114f0812017-03-08 19:05:07 -0800545 // Profiles should belong to the app; make sure of that by giving ownership to
546 // the app uid. If we cannot do that, there's no point in returning the fd
547 // since dex2oat/profman will fail with SElinux denials.
548 if (fchown(fd.get(), uid, uid) < 0) {
549 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800550 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800551 }
Calin Juravle29591732017-11-20 17:46:19 -0800552 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800553}
554
Calin Juravle29591732017-11-20 17:46:19 -0800555static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800556 // Do not follow symlinks when opening a profile:
557 // - primary profiles should not contain symlinks in their paths
558 // - secondary dex paths should have been already resolved and validated
559 flags |= O_NOFOLLOW;
560
Calin Juravle29591732017-11-20 17:46:19 -0800561 // Check if we need to create the profile
562 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
563 unique_fd fd;
564 if ((flags & O_CREAT) != 0) {
565 fd = create_profile(uid, profile, flags);
566 } else {
567 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
568 }
569
Calin Juravle114f0812017-03-08 19:05:07 -0800570 if (fd.get() < 0) {
571 if (errno != ENOENT) {
572 // Profiles might be missing for various reasons. For example, in a
573 // multi-user environment, the profile directory for one user can be created
574 // after we start a merge. In this case the current profile for that user
575 // will not be found.
576 // Also, the secondary dex profiles might be deleted by the app at any time,
577 // so we can't we need to prepare if they are missing.
578 PLOG(ERROR) << "Failed to open profile " << profile;
579 }
580 return invalid_unique_fd();
581 }
582
Jeff Sharkey90aff262016-12-12 14:28:24 -0700583 return fd;
584}
585
Calin Juravle824a64d2018-01-18 20:23:17 -0800586static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
587 const std::string& location, bool is_secondary_dex) {
588 std::string profile = create_current_profile_path(user, package_name, location,
589 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800590 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800591}
592
Calin Juravle824a64d2018-01-18 20:23:17 -0800593static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
594 const std::string& location, bool read_write, bool is_secondary_dex) {
595 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800596 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
597}
598
599static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800600 const std::string& location) {
601 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800602 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800603}
604
Calin Juravle824a64d2018-01-18 20:23:17 -0800605static void open_profile_files(uid_t uid, const std::string& package_name,
606 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800607 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700608 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800609 *reference_profile_fd = open_reference_profile(uid, package_name, location,
610 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611
Calin Juravle114f0812017-03-08 19:05:07 -0800612 // For secondary dex files, we don't really need the user but we use it for sanity checks.
613 // Note: the user owning the dex file should be the current user.
614 std::vector<userid_t> users;
615 if (is_secondary_dex){
616 users.push_back(multiuser_get_user_id(uid));
617 } else {
618 users = get_known_users(/*volume_uuid*/ nullptr);
619 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700620 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800621 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
622 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700623 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800624 if (profile_fd.get() >= 0) {
625 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 }
627 }
628}
629
630static void drop_capabilities(uid_t uid) {
631 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800632 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
633 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700634 }
635 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800636 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
637 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700638 }
639 // drop capabilities
640 struct __user_cap_header_struct capheader;
641 struct __user_cap_data_struct capdata[2];
642 memset(&capheader, 0, sizeof(capheader));
643 memset(&capdata, 0, sizeof(capdata));
644 capheader.version = _LINUX_CAPABILITY_VERSION_3;
645 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800646 PLOG(ERROR) << "capset failed";
647 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700648 }
649}
650
651static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
652static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
653static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
654static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
655static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
656
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800657class RunProfman : public ExecVHelper {
658 public:
659 void SetupArgs(const std::vector<unique_fd>& profile_fds,
660 const unique_fd& reference_profile_fd,
661 const std::vector<unique_fd>& apk_fds,
662 const std::vector<std::string>& dex_locations,
663 bool copy_and_update) {
664 const char* profman_bin =
665 is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700666
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800667 if (copy_and_update) {
668 CHECK_EQ(1u, profile_fds.size());
669 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000670 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800671 if (reference_profile_fd != -1) {
672 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000673 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800674
675 for (const unique_fd& fd : profile_fds) {
676 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
677 }
678
679 for (const unique_fd& fd : apk_fds) {
680 AddArg("--apk-fd=" + std::to_string(fd.get()));
681 }
682
683 for (const std::string& dex_location : dex_locations) {
684 AddArg("--dex-location=" + dex_location);
685 }
686
687 if (copy_and_update) {
688 AddArg("--copy-and-update-profile-key");
689 }
690
691 // Do not add after dex2oat_flags, they should override others for debugging.
692 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800693 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800695 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
696 const unique_fd& reference_profile_fd,
697 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
698 const std::vector<std::string>& dex_locations = std::vector<std::string>()) {
699 SetupArgs(profiles_fd,
700 reference_profile_fd,
701 apk_fds,
702 dex_locations,
703 /*copy_and_update=*/false);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800704 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800706 void SetupCopyAndUpdate(unique_fd&& profile_fd,
707 unique_fd&& reference_profile_fd,
708 unique_fd&& apk_fd,
709 const std::string& dex_location) {
710 // The fds need to stay open longer than the scope of the function, so put them into a local
711 // variable vector.
712 profiles_fd_.push_back(std::move(profile_fd));
713 apk_fds_.push_back(std::move(apk_fd));
714 reference_profile_fd_ = std::move(reference_profile_fd);
715 std::vector<std::string> dex_locations = {dex_location};
716 SetupArgs(profiles_fd_, reference_profile_fd_, apk_fds_, dex_locations,
717 /*copy_and_update=*/true);
718 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000719
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800720 void SetupDump(const std::vector<unique_fd>& profiles_fd,
721 const unique_fd& reference_profile_fd,
722 const std::vector<std::string>& dex_locations,
723 const std::vector<unique_fd>& apk_fds,
724 const unique_fd& output_fd) {
725 AddArg("--dump-only");
726 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
727 SetupArgs(profiles_fd, reference_profile_fd, apk_fds, dex_locations,
728 /*copy_and_update=*/false);
729 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000730
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800731 void Exec() {
732 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
733 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000734
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800735 private:
736 unique_fd reference_profile_fd_;
737 std::vector<unique_fd> profiles_fd_;
738 std::vector<unique_fd> apk_fds_;
739};
Mathieu Chartier31636522018-11-09 23:53:07 +0000740
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800741
Calin Juravlef63d4792018-01-30 17:43:34 +0000742
Jeff Sharkey90aff262016-12-12 14:28:24 -0700743// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800744// The location is the package name for primary apks or the dex path for secondary dex files.
745// Returns true if there is enough information in the current profiles that makes it
746// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747// If the return value is true all the current profiles would have been merged into
748// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800749static bool analyze_profiles(uid_t uid, const std::string& package_name,
750 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800751 std::vector<unique_fd> profiles_fd;
752 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800753 open_profile_files(uid, package_name, location, is_secondary_dex,
754 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800755 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 // Skip profile guided compilation because no profiles were found.
757 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700758 return false;
759 }
760
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800761 RunProfman profman_merge;
762 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763 pid_t pid = fork();
764 if (pid == 0) {
765 /* child -- drop privileges before continuing */
766 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800767 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700768 }
769 /* parent */
770 int return_code = wait_child(pid);
771 bool need_to_compile = false;
772 bool should_clear_current_profiles = false;
773 bool should_clear_reference_profile = false;
774 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800775 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700776 } else {
777 return_code = WEXITSTATUS(return_code);
778 switch (return_code) {
779 case PROFMAN_BIN_RETURN_CODE_COMPILE:
780 need_to_compile = true;
781 should_clear_current_profiles = true;
782 should_clear_reference_profile = false;
783 break;
784 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
785 need_to_compile = false;
786 should_clear_current_profiles = false;
787 should_clear_reference_profile = false;
788 break;
789 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800790 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700791 need_to_compile = false;
792 should_clear_current_profiles = true;
793 should_clear_reference_profile = true;
794 break;
795 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
796 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
797 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800798 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700799 need_to_compile = false;
800 should_clear_current_profiles = false;
801 should_clear_reference_profile = false;
802 break;
803 default:
804 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800805 LOG(WARNING) << "Unknown error code while processing profiles for location "
806 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807 need_to_compile = false;
808 should_clear_current_profiles = true;
809 should_clear_reference_profile = true;
810 break;
811 }
812 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800813
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800815 if (is_secondary_dex) {
816 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800817 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
818 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800819 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800820 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800821 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700822 }
823 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800824 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825 }
826 return need_to_compile;
827}
828
Calin Juravle114f0812017-03-08 19:05:07 -0800829// Decides if profile guided compilation is needed or not based on existing profiles.
830// The analysis is done for the primary apks of the given package.
831// Returns true if there is enough information in the current profiles that makes it
832// worth to recompile the package.
833// If the return value is true all the current profiles would have been merged into
834// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800835bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
836 const std::string& profile_name) {
837 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800838}
839
Calin Juravle408cd4a2018-01-20 23:34:18 -0800840bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
841 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800842 std::vector<unique_fd> profile_fds;
843 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800844 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
845 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700846
Calin Juravle408cd4a2018-01-20 23:34:18 -0800847 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800848 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700849
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800850 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700851 const bool has_profiles = !profile_fds.empty();
852
853 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800854 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700855 return false;
856 }
857
Calin Juravle114f0812017-03-08 19:05:07 -0800858 unique_fd output_fd(open(out_file_name.c_str(),
859 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700860 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800861 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862 return false;
863 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800864
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800866 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800867 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
868 if (apk_fd == -1) {
869 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
870 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800872 dex_locations.push_back(get_location_from_path(code_path.c_str()));
873 apk_fds.push_back(std::move(apk_fd));
874
Jeff Sharkey90aff262016-12-12 14:28:24 -0700875
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800876 RunProfman profman_dump;
877 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700878 pid_t pid = fork();
879 if (pid == 0) {
880 /* child -- drop privileges before continuing */
881 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800882 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883 }
884 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700885 int return_code = wait_child(pid);
886 if (!WIFEXITED(return_code)) {
887 LOG(WARNING) << "profman failed for package " << pkgname << ": "
888 << return_code;
889 return false;
890 }
891 return true;
892}
893
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700894bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800895 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700896 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
897 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800898 package_name,
899 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700900 /*read_write*/ true,
901 /*secondary*/ false));
902 if (in_fd.get() < 0) {
903 PLOG(WARNING) << "Could not open profile " << system_profile;
904 return false;
905 }
906 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800907 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700908 return false;
909 }
910
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700911 // As a security measure we want to write the profile information with the reduced capabilities
912 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700913 pid_t pid = fork();
914 if (pid == 0) {
915 /* child -- drop privileges before continuing */
916 drop_capabilities(packageUid);
917
918 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
919 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800920 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700921 }
922 // This implies that the app owning this profile is running
923 // (and has acquired the lock).
924 //
925 // The app never acquires the lock for the reference profiles of primary apks.
926 // Only dex2oat from installd will do that. Since installd is single threaded
927 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800928 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700929 return false;
930 }
931
932 bool truncated = ftruncate(out_fd.get(), 0) == 0;
933 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800934 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700935 }
936
937 // Copy over data.
938 static constexpr size_t kBufferSize = 4 * 1024;
939 char buffer[kBufferSize];
940 while (true) {
941 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
942 if (bytes == 0) {
943 break;
944 }
945 write(out_fd.get(), buffer, bytes);
946 }
947 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800948 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700949 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700950 // Use _exit since we don't want to run the global destructors in the child.
951 // b/62597429
952 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700953 }
954 /* parent */
955 int return_code = wait_child(pid);
956 return return_code == 0;
957}
958
Jeff Sharkey90aff262016-12-12 14:28:24 -0700959static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
960 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
961 if (EndsWith(oat_path, ".dex")) {
962 std::string new_path = oat_path;
963 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800964 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700965 return new_path;
966 }
967
968 // An odex entry. Not that this may not be an extension, e.g., in the OTA
969 // case (where the base name will have an extension for the B artifact).
970 size_t odex_pos = oat_path.rfind(".odex");
971 if (odex_pos != std::string::npos) {
972 std::string new_path = oat_path;
973 new_path.replace(odex_pos, strlen(".odex"), new_ext);
974 CHECK_NE(new_path.find(new_ext), std::string::npos);
975 return new_path;
976 }
977
978 // Don't know how to handle this.
979 return "";
980}
981
982// Translate the given oat path to an art (app image) path. An empty string
983// denotes an error.
984static std::string create_image_filename(const std::string& oat_path) {
985 return replace_file_extension(oat_path, ".art");
986}
987
988// Translate the given oat path to a vdex path. An empty string denotes an error.
989static std::string create_vdex_filename(const std::string& oat_path) {
990 return replace_file_extension(oat_path, ".vdex");
991}
992
Jeff Sharkey90aff262016-12-12 14:28:24 -0700993static int open_output_file(const char* file_name, bool recreate, int permissions) {
994 int flags = O_RDWR | O_CREAT;
995 if (recreate) {
996 if (unlink(file_name) < 0) {
997 if (errno != ENOENT) {
998 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
999 }
1000 }
1001 flags |= O_EXCL;
1002 }
1003 return open(file_name, flags, permissions);
1004}
1005
Calin Juravle2289c0a2017-02-15 12:44:14 -08001006static bool set_permissions_and_ownership(
1007 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1008 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1009 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001010 if (fchmod(fd,
1011 S_IRUSR|S_IWUSR|S_IRGRP |
1012 (is_public ? S_IROTH : 0)) < 0) {
1013 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1014 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001015 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001016 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1017 return false;
1018 }
1019 return true;
1020}
1021
1022static bool IsOutputDalvikCache(const char* oat_dir) {
1023 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1024 // into '!'. Play it safe by handling it both.
1025 // TODO: ensure we never get null.
1026 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1027 return oat_dir == nullptr || oat_dir[0] == '!';
1028}
1029
Calin Juravled23dee72017-07-06 16:29:11 -07001030// Best-effort check whether we can fit the the path into our buffers.
1031// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1032// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1033// extension to the cache path (5 bytes).
1034// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1035static bool validate_dex_path_size(const std::string& dex_path) {
1036 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1037 LOG(ERROR) << "dex_path too long: " << dex_path;
1038 return false;
1039 }
1040 return true;
1041}
1042
Jeff Sharkey90aff262016-12-12 14:28:24 -07001043static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001044 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001045 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001046 return false;
1047 }
1048
1049 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001050 // Oat dirs for secondary dex files are already validated.
1051 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001052 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1053 return false;
1054 }
1055 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1056 return false;
1057 }
1058 } else {
1059 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1060 return false;
1061 }
1062 }
1063 return true;
1064}
1065
1066// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1067// on destruction. It will also run the given cleanup (unless told not to) after closing.
1068//
1069// Usage example:
1070//
Calin Juravle7a570e82017-01-14 16:23:30 -08001071// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001072// [name]() {
1073// unlink(name.c_str());
1074// });
1075// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1076// wrapper if captured as a reference.
1077//
1078// if (file.get() == -1) {
1079// // Error opening...
1080// }
1081//
1082// ...
1083// if (error) {
1084// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1085// // and delete the file (after the fd is closed).
1086// return -1;
1087// }
1088//
1089// (Success case)
1090// file.SetCleanup(false);
1091// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1092// // (leaving the file around; after the fd is closed).
1093//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001094class Dex2oatFileWrapper {
1095 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001096 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001097 }
1098
Calin Juravle7a570e82017-01-14 16:23:30 -08001099 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1100 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1101
1102 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1103 value_ = other.value_;
1104 cleanup_ = other.cleanup_;
1105 do_cleanup_ = other.do_cleanup_;
1106 auto_close_ = other.auto_close_;
1107 other.release();
1108 }
1109
1110 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1111 value_ = other.value_;
1112 cleanup_ = other.cleanup_;
1113 do_cleanup_ = other.do_cleanup_;
1114 auto_close_ = other.auto_close_;
1115 other.release();
1116 return *this;
1117 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118
1119 ~Dex2oatFileWrapper() {
1120 reset(-1);
1121 }
1122
1123 int get() {
1124 return value_;
1125 }
1126
1127 void SetCleanup(bool cleanup) {
1128 do_cleanup_ = cleanup;
1129 }
1130
1131 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001132 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001133 close(value_);
1134 }
1135 if (do_cleanup_ && cleanup_ != nullptr) {
1136 cleanup_();
1137 }
1138
1139 value_ = new_value;
1140 }
1141
Calin Juravle7a570e82017-01-14 16:23:30 -08001142 void reset(int new_value, std::function<void ()> new_cleanup) {
1143 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001144 close(value_);
1145 }
1146 if (do_cleanup_ && cleanup_ != nullptr) {
1147 cleanup_();
1148 }
1149
1150 value_ = new_value;
1151 cleanup_ = new_cleanup;
1152 }
1153
Calin Juravle7a570e82017-01-14 16:23:30 -08001154 void DisableAutoClose() {
1155 auto_close_ = false;
1156 }
1157
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001159 void release() {
1160 value_ = -1;
1161 do_cleanup_ = false;
1162 cleanup_ = nullptr;
1163 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001164 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001165 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001166 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001168};
1169
Calin Juravle7a570e82017-01-14 16:23:30 -08001170// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001171Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1172 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001173
1174 // We don't create an image for secondary dex files.
1175 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001176 return Dex2oatFileWrapper();
1177 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001178
Calin Juravle7a570e82017-01-14 16:23:30 -08001179 const std::string image_path = create_image_filename(out_oat_path);
1180 if (image_path.empty()) {
1181 // Happens when the out_oat_path has an unknown extension.
1182 return Dex2oatFileWrapper();
1183 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001184
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001185 // In case there is a stale image, remove it now. Ignore any error.
1186 unlink(image_path.c_str());
1187
1188 // Not enabled, exit.
1189 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001190 return Dex2oatFileWrapper();
1191 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001192 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1193 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001194 return Dex2oatFileWrapper();
1195 }
1196 // Recreate is true since we do not want to modify a mapped image. If the app is
1197 // already running and we modify the image file, it can cause crashes (b/27493510).
1198 Dex2oatFileWrapper wrapper_fd(
1199 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1200 [image_path]() { unlink(image_path.c_str()); });
1201 if (wrapper_fd.get() < 0) {
1202 // Could not create application image file. Go on since we can compile without it.
1203 LOG(ERROR) << "installd could not create '" << image_path
1204 << "' for image file during dexopt";
1205 // If we have a valid image file path but no image fd, explicitly erase the image file.
1206 if (unlink(image_path.c_str()) < 0) {
1207 if (errno != ENOENT) {
1208 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1209 }
1210 }
1211 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001212 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1214 wrapper_fd.reset(-1);
1215 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001216
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 return wrapper_fd;
1218}
1219
1220// Creates the dexopt swap file if necessary and return its fd.
1221// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001222unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001223 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001224 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001226 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001227 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001228 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001229 if (swap_fd.get() < 0) {
1230 // Could not create swap file. Optimistically go on and hope that we can compile
1231 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001232 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 } else {
1234 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001235 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1237 }
1238 }
1239 return swap_fd;
1240}
1241
1242// Opens the reference profiles if needed.
1243// 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 -08001244Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001245 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001246 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001247 // If we are not profile guided compilation, or we are compiling system server
1248 // do not bother to open the profiles; we won't be using them.
1249 if (!profile_guided || (pkgname[0] == '*')) {
1250 return Dex2oatFileWrapper();
1251 }
1252
1253 // If this is a secondary dex path which is public do not open the profile.
1254 // We cannot compile public secondary dex paths with profiles. That's because
1255 // it will expose how the dex files are used by their owner.
1256 //
1257 // Note that the PackageManager is responsible to set the is_public flag for
1258 // primary apks and we do not check it here. In some cases, e.g. when
1259 // compiling with a public profile from the .dm file the PackageManager will
1260 // set is_public toghether with the profile guided compilation.
1261 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001262 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001263 }
Calin Juravle114f0812017-03-08 19:05:07 -08001264
1265 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001266 std::string location;
1267 if (is_secondary_dex) {
1268 location = dex_path;
1269 } else {
1270 if (profile_name == nullptr) {
1271 // This path is taken for system server re-compilation lunched from ZygoteInit.
1272 return Dex2oatFileWrapper();
1273 } else {
1274 location = profile_name;
1275 }
1276 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001277 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1278 is_secondary_dex);
1279 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1280 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001281 };
1282 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001283}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001284
Calin Juravle7a570e82017-01-14 16:23:30 -08001285// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1286// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001287bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001288 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001289 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001290 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1291 CHECK(in_vdex_wrapper_fd != nullptr);
1292 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001293 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1294 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001295 char in_odex_path[PKG_PATH_MAX];
1296 int dexopt_action = abs(dexopt_needed);
1297 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001298 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001299
1300 // Infer the name of the output VDEX.
1301 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1302 if (out_vdex_path_str.empty()) {
1303 return false;
1304 }
1305
1306 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001307 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001308 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1309 const char* path = nullptr;
1310 if (is_odex_location) {
1311 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1312 path = in_odex_path;
1313 } else {
1314 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001315 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001316 }
1317 } else {
1318 path = out_oat_path;
1319 }
1320 in_vdex_path_str = create_vdex_filename(path);
1321 if (in_vdex_path_str.empty()) {
1322 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001323 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001324 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001325 // We can update in place when all these conditions are met:
1326 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1327 // on /system typically cannot be updated in place).
1328 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1329 // cannot be currently used by a running process.
1330 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1331 // different vdex files to operate.
1332 update_vdex_in_place =
1333 (in_vdex_path_str == out_vdex_path_str) &&
1334 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1335 !profile_guided;
1336 if (update_vdex_in_place) {
1337 // Open the file read-write to be able to update it.
1338 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1339 if (in_vdex_wrapper_fd->get() == -1) {
1340 // If we failed to open the file, we cannot update it in place.
1341 update_vdex_in_place = false;
1342 }
1343 } else {
1344 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1345 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001346 }
1347
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001348 // If we are updating the vdex in place, we do not need to recreate a vdex,
1349 // and can use the same existing one.
1350 if (update_vdex_in_place) {
1351 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1352 // have bogus stale vdex files.
1353 out_vdex_wrapper_fd->reset(
1354 in_vdex_wrapper_fd->get(),
1355 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1356 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1357 // wrapper).
1358 in_vdex_wrapper_fd->DisableAutoClose();
1359 } else {
1360 out_vdex_wrapper_fd->reset(
1361 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1362 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1363 if (out_vdex_wrapper_fd->get() < 0) {
1364 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1365 return false;
1366 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001367 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001368 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001369 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001370 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1371 return false;
1372 }
1373
1374 // If we got here we successfully opened the vdex files.
1375 return true;
1376}
1377
1378// Opens the output oat file for the given apk.
1379// If successful it stores the output path into out_oat_path and returns true.
1380Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001381 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1382 char* out_oat_path) {
1383 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001384 return Dex2oatFileWrapper();
1385 }
1386 const std::string out_oat_path_str(out_oat_path);
1387 Dex2oatFileWrapper wrapper_fd(
1388 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1389 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1390 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001391 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001392 } else if (!set_permissions_and_ownership(
1393 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001394 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1395 wrapper_fd.reset(-1);
1396 }
1397 return wrapper_fd;
1398}
1399
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001400// Creates RDONLY fds for oat and vdex files, if exist.
1401// Returns false if it fails to create oat out path for the given apk path.
1402// Note that the method returns true even if the files could not be opened.
1403bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1404 const std::string& oat_dir,
1405 const std::string& instruction_set,
1406 bool is_secondary_dex,
1407 unique_fd* oat_file_fd,
1408 unique_fd* vdex_file_fd) {
1409 char oat_path[PKG_PATH_MAX];
1410 if (!create_oat_out_path(apk_path.c_str(),
1411 instruction_set.c_str(),
1412 oat_dir.c_str(),
1413 is_secondary_dex,
1414 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001415 LOG(ERROR) << "Could not create oat out path for "
1416 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001417 return false;
1418 }
1419 oat_file_fd->reset(open(oat_path, O_RDONLY));
1420 if (oat_file_fd->get() < 0) {
1421 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1422 }
1423
1424 std::string vdex_filename = create_vdex_filename(oat_path);
1425 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1426 if (vdex_file_fd->get() < 0) {
1427 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1428 }
1429
1430 return true;
1431}
1432
Calin Juravle7a570e82017-01-14 16:23:30 -08001433// Updates the access times of out_oat_path based on those from apk_path.
1434void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1435 struct stat input_stat;
1436 memset(&input_stat, 0, sizeof(input_stat));
1437 if (stat(apk_path, &input_stat) != 0) {
1438 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1439 return;
1440 }
1441
1442 struct utimbuf ut;
1443 ut.actime = input_stat.st_atime;
1444 ut.modtime = input_stat.st_mtime;
1445 if (utime(out_oat_path, &ut) != 0) {
1446 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1447 }
1448}
1449
Calin Juravle80a21252017-01-17 14:43:25 -08001450// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001451// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1452// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1453// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001454class RunDexoptAnalyzer : public ExecVHelper {
1455 public:
1456 RunDexoptAnalyzer(const std::string& dex_file,
1457 int vdex_fd,
1458 int oat_fd,
1459 int zip_fd,
1460 const std::string& instruction_set,
1461 const std::string& compiler_filter,
1462 bool profile_was_updated,
1463 bool downgrade,
1464 const char* class_loader_context) {
1465 CHECK_GE(zip_fd, 0);
1466 const char* dexoptanalyzer_bin =
1467 is_debug_runtime()
1468 ? "/system/bin/dexoptanalyzerd"
1469 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001470
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001471 std::string dex_file_arg = "--dex-file=" + dex_file;
1472 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1473 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1474 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1475 std::string isa_arg = "--isa=" + instruction_set;
1476 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1477 const char* assume_profile_changed = "--assume-profile-changed";
1478 const char* downgrade_flag = "--downgrade";
1479 std::string class_loader_context_arg = "--class-loader-context=";
1480 if (class_loader_context != nullptr) {
1481 class_loader_context_arg += class_loader_context;
1482 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001483
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001484 // program name, dex file, isa, filter
1485 AddArg(dex_file_arg);
1486 AddArg(isa_arg);
1487 AddArg(compiler_filter_arg);
1488 if (oat_fd >= 0) {
1489 AddArg(oat_fd_arg);
1490 }
1491 if (vdex_fd >= 0) {
1492 AddArg(vdex_fd_arg);
1493 }
1494 AddArg(zip_fd_arg.c_str());
1495 if (profile_was_updated) {
1496 AddArg(assume_profile_changed);
1497 }
1498 if (downgrade) {
1499 AddArg(downgrade_flag);
1500 }
1501 if (class_loader_context != nullptr) {
1502 AddArg(class_loader_context_arg.c_str());
1503 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001504
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001505 PrepareArgs(dexoptanalyzer_bin);
1506 }
1507};
Calin Juravle80a21252017-01-17 14:43:25 -08001508
1509// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001510static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001511 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001512 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001513 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001514 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001515 return false;
1516 }
Calin Juravle114f0812017-03-08 19:05:07 -08001517 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001518
Calin Juravle80a21252017-01-17 14:43:25 -08001519 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001520 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1521 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001522 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001523 return false;
1524 }
1525
1526 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001527 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001528
Calin Juravle7d765462017-09-04 15:57:10 -07001529 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001530 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001531 return false;
1532 }
1533
1534 return true;
1535}
1536
Calin Juravle7d765462017-09-04 15:57:10 -07001537// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1538// secondary dex files. This return codes are returned by the child process created for
1539// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001540
Andreas Gampe194fe422018-02-28 20:16:19 -08001541enum DexoptAnalyzerSkipCodes {
1542 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001543 // Specific errors are encoded in the name.
1544 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1545 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1546 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1547 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1548 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001549 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001550 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001551};
Calin Juravle7d765462017-09-04 15:57:10 -07001552
1553// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001554// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1555// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001556// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1557// of dexoptanalyzer.
1558static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001559 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001560 // The result values are defined in dexoptanalyzer.
1561 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001562 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001563 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001564 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001565 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001566 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001567 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001568 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001569 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001570 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1571 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001572 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1573 " Expected odex file status for secondary dex %s"
1574 " : dexoptanalyzer result=%d",
1575 dex_path.c_str(),
1576 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001577 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001578 }
1579
1580 // Use a second switch for enum switch-case analysis.
1581 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001582 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001583 // If the file does not exist there's no need for dexopt.
1584 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1585 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001586
1587 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1588 *error_msg = "Dexoptanalyzer path validation failed";
1589 return false;
1590 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1591 *error_msg = "Dexoptanalyzer open zip failed";
1592 return false;
1593 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1594 *error_msg = "Dexoptanalyzer dir preparation failed";
1595 return false;
1596 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1597 *error_msg = "Dexoptanalyzer open output failed";
1598 return false;
1599 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1600 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001601 return false;
1602 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001603
1604 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1605 dex_path.c_str(),
1606 result);
1607 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001608}
1609
Calin Juravle7d765462017-09-04 15:57:10 -07001610enum SecondaryDexAccess {
1611 kSecondaryDexAccessReadOk = 0,
1612 kSecondaryDexAccessDoesNotExist = 1,
1613 kSecondaryDexAccessPermissionError = 2,
1614 kSecondaryDexAccessIOError = 3
1615};
1616
1617static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1618 // Check if the path exists and can be read. If not, there's nothing to do.
1619 if (access(dex_path.c_str(), R_OK) == 0) {
1620 return kSecondaryDexAccessReadOk;
1621 } else {
1622 if (errno == ENOENT) {
1623 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1624 return kSecondaryDexAccessDoesNotExist;
1625 } else {
1626 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1627 return errno == EACCES
1628 ? kSecondaryDexAccessPermissionError
1629 : kSecondaryDexAccessIOError;
1630 }
1631 }
1632}
1633
1634static bool is_file_public(const std::string& filename) {
1635 struct stat file_stat;
1636 if (stat(filename.c_str(), &file_stat) == 0) {
1637 return (file_stat.st_mode & S_IROTH) != 0;
1638 }
1639 return false;
1640}
1641
1642// Create the oat file structure for the secondary dex 'dex_path' and assign
1643// the individual path component to the 'out_' parameters.
1644static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001645 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001646 size_t dirIndex = dex_path.rfind('/');
1647 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001648 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001649 return false;
1650 }
1651 // TODO(calin): we have similar computations in at lest 3 other places
1652 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1653 // using string append.
1654 std::string apk_dir = dex_path.substr(0, dirIndex);
1655 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1656 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1657
1658 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1659 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001660 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001661 return false;
1662 }
1663 return true;
1664}
1665
1666// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1667// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001668static bool validate_dexopt_storage_flags(int dexopt_flags,
1669 int* out_storage_flag,
1670 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001671 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1672 *out_storage_flag = FLAG_STORAGE_CE;
1673 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001674 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001675 return false;
1676 }
1677 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1678 *out_storage_flag = FLAG_STORAGE_DE;
1679 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001680 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001681 return false;
1682 }
1683 return true;
1684}
1685
Calin Juravlec9eab382017-01-25 01:17:17 -08001686// 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 -08001687// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1688// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001689// When returning true, the output parameters will be:
1690// - is_public_out: whether or not the oat file should not be made public
1691// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1692// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001693static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001694 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001695 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001696 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1697 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001698 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001699 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001700 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1701 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001702 return false;
1703 }
Calin Juravle7d765462017-09-04 15:57:10 -07001704 // Compute the oat dir as it's not easy to extract it from the child computation.
1705 char oat_path[PKG_PATH_MAX];
1706 char oat_dir[PKG_PATH_MAX];
1707 char oat_isa_dir[PKG_PATH_MAX];
1708 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001709 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1710 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001711 return false;
1712 }
Calin Juravle7d765462017-09-04 15:57:10 -07001713 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001714
Calin Juravle80a21252017-01-17 14:43:25 -08001715 pid_t pid = fork();
1716 if (pid == 0) {
1717 // child -- drop privileges before continuing.
1718 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001719
1720 // Validate the path structure.
1721 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1722 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001723 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001724 }
1725
1726 // Open the dex file.
1727 unique_fd zip_fd;
1728 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1729 if (zip_fd.get() < 0) {
1730 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001731 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001732 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001733 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001734 }
1735 }
1736
1737 // Prepare the oat directories.
1738 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001739 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001740 }
1741
1742 // Open the vdex/oat files if any.
1743 unique_fd oat_file_fd;
1744 unique_fd vdex_file_fd;
1745 if (!maybe_open_oat_and_vdex_file(dex_path,
1746 *oat_dir_out,
1747 instruction_set,
1748 true /* is_secondary_dex */,
1749 &oat_file_fd,
1750 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001751 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001752 }
1753
1754 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001755 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1756 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001757
1758 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001759 // Note that we do not do it before the fork since opening the files is required to happen
1760 // after forking.
1761 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1762 vdex_file_fd.get(),
1763 oat_file_fd.get(),
1764 zip_fd.get(),
1765 instruction_set,
1766 compiler_filter, profile_was_updated,
1767 downgrade,
1768 class_loader_context);
1769 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001770 }
1771
1772 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001773 int result = wait_child(pid);
1774 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001775 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1776 dex_path.c_str(),
1777 result);
1778 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001779 return false;
1780 }
1781 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001782 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001783 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1784 result,
1785 dexopt_needed_out,
1786 error_msg);
1787 if (!success) {
1788 LOG(ERROR) << *error_msg;
1789 }
Calin Juravle7d765462017-09-04 15:57:10 -07001790
1791 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1792
Calin Juravle80a21252017-01-17 14:43:25 -08001793 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001794 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1795 // makes the code simpler; force compilation is only needed during tests).
1796 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001797 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001798 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001799 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1800 }
1801
Calin Juravle7d765462017-09-04 15:57:10 -07001802 // Check if we should make the oat file public.
1803 // Note that if the dex file is not public the compiled code cannot be made public.
1804 // It is ok to check this flag outside in the parent process.
1805 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1806
Calin Juravle80a21252017-01-17 14:43:25 -08001807 return success;
1808}
1809
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001810static std::string format_dexopt_error(int status, const char* dex_path) {
1811 if (WIFEXITED(status)) {
1812 int int_code = WEXITSTATUS(status);
1813 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1814 if (code_name != nullptr) {
1815 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1816 }
1817 }
1818 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001819}
1820
Calin Juravlec9eab382017-01-25 01:17:17 -08001821int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001822 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001823 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001824 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001825 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001826 CHECK(pkgname != nullptr);
1827 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001828 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001829 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1830 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001831
Calin Juravled23dee72017-07-06 16:29:11 -07001832 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001833 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001834 return -1;
1835 }
1836
1837 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001838 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1839 class_loader_context);
1840 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001841 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001842 }
1843
Calin Juravleebc8a792017-04-04 20:21:05 -07001844 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001845 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1846 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1847 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001848 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001849 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001850 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001851 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001852 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001853
1854 // Check if we're dealing with a secondary dex file and if we need to compile it.
1855 std::string oat_dir_str;
1856 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001857 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001858 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001859 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001860 oat_dir = oat_dir_str.c_str();
1861 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1862 return 0; // Nothing to do, report success.
1863 }
1864 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001865 if (error_msg->empty()) { // TODO: Make this a CHECK.
1866 *error_msg = "Failed processing secondary.";
1867 }
Calin Juravle80a21252017-01-17 14:43:25 -08001868 return -1; // We had an error, logged in the process method.
1869 }
1870 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001871 // Currently these flags are only use for secondary dex files.
1872 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001873 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1874 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1875 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001876
1877 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001878 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001879 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001880 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1881 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001882 return -1;
1883 }
1884
1885 // Create the output OAT file.
1886 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001887 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001888 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001889 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001890 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001891 return -1;
1892 }
1893
1894 // Open vdex files.
1895 Dex2oatFileWrapper in_vdex_fd;
1896 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001897 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1898 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001899 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001900 return -1;
1901 }
1902
Calin Juravlecb556e32017-04-04 20:22:50 -07001903 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1904 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1905 // fully inherit their parent context).
1906 // Note that for primary apk the oat files are created before, in a separate installd
1907 // call which also does the restorecon. TODO(calin): unify the paths.
1908 if (is_secondary_dex) {
1909 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1910 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001911 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1912 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001913 return -1;
1914 }
1915 }
1916
Jeff Sharkey90aff262016-12-12 14:28:24 -07001917 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001918 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001919
Calin Juravle7a570e82017-01-14 16:23:30 -08001920 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001921 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1922 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001923
Calin Juravle7a570e82017-01-14 16:23:30 -08001924 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001925 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001926 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001927
Calin Juravle62c5a372018-02-01 17:03:23 +00001928 unique_fd dex_metadata_fd;
1929 if (dex_metadata_path != nullptr) {
1930 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1931 if (dex_metadata_fd.get() < 0) {
1932 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1933 }
1934 }
1935
Andreas Gampe023b2242018-02-28 16:03:25 -08001936 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001937
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001938 RunDex2Oat runner(input_fd.get(),
1939 out_oat_fd.get(),
1940 in_vdex_fd.get(),
1941 out_vdex_fd.get(),
1942 image_fd.get(),
1943 dex_path,
1944 out_oat_path,
1945 swap_fd.get(),
1946 instruction_set,
1947 compiler_filter,
1948 debuggable,
1949 boot_complete,
1950 background_job_compile,
1951 reference_profile_fd.get(),
1952 class_loader_context,
1953 target_sdk_version,
1954 enable_hidden_api_checks,
1955 generate_compact_dex,
1956 dex_metadata_fd.get(),
1957 compilation_reason);
1958
Jeff Sharkey90aff262016-12-12 14:28:24 -07001959 pid_t pid = fork();
1960 if (pid == 0) {
1961 /* child -- drop privileges before continuing */
1962 drop_capabilities(uid);
1963
Richard Uhler76cc0272016-12-08 10:46:35 +00001964 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001965 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001966 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001967 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001968 }
1969
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001970 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001971 } else {
1972 int res = wait_child(pid);
1973 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001974 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001975 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001976 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1977 << std::hex << std::setw(4) << res << ", process failed";
1978 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001979 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001980 }
1981 }
1982
Calin Juravlec9eab382017-01-25 01:17:17 -08001983 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001984
1985 // We've been successful, don't delete output.
1986 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001987 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001988 image_fd.SetCleanup(false);
1989 reference_profile_fd.SetCleanup(false);
1990
1991 return 0;
1992}
1993
Calin Juravlec9eab382017-01-25 01:17:17 -08001994// Try to remove the given directory. Log an error if the directory exists
1995// and is empty but could not be removed.
1996static bool rmdir_if_empty(const char* dir) {
1997 if (rmdir(dir) == 0) {
1998 return true;
1999 }
2000 if (errno == ENOENT || errno == ENOTEMPTY) {
2001 return true;
2002 }
2003 PLOG(ERROR) << "Failed to remove dir: " << dir;
2004 return false;
2005}
2006
2007// Try to unlink the given file. Log an error if the file exists and could not
2008// be unlinked.
2009static bool unlink_if_exists(const std::string& file) {
2010 if (unlink(file.c_str()) == 0) {
2011 return true;
2012 }
2013 if (errno == ENOENT) {
2014 return true;
2015
2016 }
2017 PLOG(ERROR) << "Could not unlink: " << file;
2018 return false;
2019}
2020
Calin Juravle7d765462017-09-04 15:57:10 -07002021enum ReconcileSecondaryDexResult {
2022 kReconcileSecondaryDexExists = 0,
2023 kReconcileSecondaryDexCleanedUp = 1,
2024 kReconcileSecondaryDexValidationError = 2,
2025 kReconcileSecondaryDexCleanUpError = 3,
2026 kReconcileSecondaryDexAccessIOError = 4,
2027};
Calin Juravlec9eab382017-01-25 01:17:17 -08002028
2029// Reconcile the secondary dex 'dex_path' and its generated oat files.
2030// Return true if all the parameters are valid and the secondary dex file was
2031// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2032// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2033// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2034// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2035// Return false if there were errors during processing. In this case
2036// out_secondary_dex_exists will be set to false.
2037bool reconcile_secondary_dex_file(const std::string& dex_path,
2038 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2039 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2040 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002041 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002042 if (isas.size() == 0) {
2043 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2044 return false;
2045 }
2046
Calin Juravle7d765462017-09-04 15:57:10 -07002047 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2048 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2049 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002050 return false;
2051 }
2052
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002053 // As a security measure we want to unlink art artifacts with the reduced capabilities
2054 // of the package user id. So we fork and drop capabilities in the child.
2055 pid_t pid = fork();
2056 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002057 /* child -- drop privileges before continuing */
2058 drop_capabilities(uid);
2059
2060 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2061 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2062 uid, storage_flag)) {
2063 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2064 _exit(kReconcileSecondaryDexValidationError);
2065 }
2066
2067 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2068 switch (access_check) {
2069 case kSecondaryDexAccessDoesNotExist:
2070 // File does not exist. Proceed with cleaning.
2071 break;
2072 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2073 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2074 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2075 default:
2076 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2077 _exit(kReconcileSecondaryDexValidationError);
2078 }
2079
2080 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002081 char oat_path[PKG_PATH_MAX];
2082 char oat_dir[PKG_PATH_MAX];
2083 char oat_isa_dir[PKG_PATH_MAX];
2084 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002085 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002086 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002087 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002088 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2089 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002090 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002091 }
Calin Juravle51314092017-05-18 15:33:05 -07002092
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002093 // Delete oat/vdex/art files.
2094 result = unlink_if_exists(oat_path) && result;
2095 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2096 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002097
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002098 // Delete profiles.
2099 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002100 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002101 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002102 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002103 result = unlink_if_exists(current_profile) && result;
2104 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002105
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002106 // We upgraded once the location of current profile for secondary dex files.
2107 // Check for any previous left-overs and remove them as well.
2108 std::string old_current_profile = dex_path + ".prof";
2109 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002110
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002111 // Try removing the directories as well, they might be empty.
2112 result = rmdir_if_empty(oat_isa_dir) && result;
2113 result = rmdir_if_empty(oat_dir) && result;
2114 }
Calin Juravle7d765462017-09-04 15:57:10 -07002115 if (!result) {
2116 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2117 }
2118 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002119 }
2120
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002121 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002122 if (!WIFEXITED(return_code)) {
2123 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2124 } else {
2125 return_code = WEXITSTATUS(return_code);
2126 }
2127
2128 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2129
2130 switch (return_code) {
2131 case kReconcileSecondaryDexCleanedUp:
2132 case kReconcileSecondaryDexValidationError:
2133 // If we couldn't validate assume the dex file does not exist.
2134 // This will purge the entry from the PM records.
2135 *out_secondary_dex_exists = false;
2136 return true;
2137 case kReconcileSecondaryDexExists:
2138 *out_secondary_dex_exists = true;
2139 return true;
2140 case kReconcileSecondaryDexAccessIOError:
2141 // We had an access IO error.
2142 // Return false so that we can try again.
2143 // The value of out_secondary_dex_exists does not matter in this case and by convention
2144 // is set to false.
2145 *out_secondary_dex_exists = false;
2146 return false;
2147 default:
2148 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2149 *out_secondary_dex_exists = false;
2150 return false;
2151 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002152}
2153
Alan Stokesa25d90c2017-10-16 10:56:00 +01002154// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2155// Returns true if all parameters are valid and the hash successfully computed and stored in
2156// out_secondary_dex_hash.
2157// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2158// the app.
2159// For any other errors (e.g. if any of the parameters are invalid) returns false.
2160bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2161 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2162 std::vector<uint8_t>* out_secondary_dex_hash) {
2163 out_secondary_dex_hash->clear();
2164
2165 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2166
2167 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2168 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2169 << storage_flag;
2170 return false;
2171 }
2172
2173 // Pipe to get the hash result back from our child process.
2174 unique_fd pipe_read, pipe_write;
2175 if (!Pipe(&pipe_read, &pipe_write)) {
2176 PLOG(ERROR) << "Failed to create pipe";
2177 return false;
2178 }
2179
2180 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2181 // access data the app itself can access.
2182 pid_t pid = fork();
2183 if (pid == 0) {
2184 // child -- drop privileges before continuing
2185 drop_capabilities(uid);
2186 pipe_read.reset();
2187
2188 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2189 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002190 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002191 }
2192
2193 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2194 if (fd == -1) {
2195 if (errno == EACCES || errno == ENOENT) {
2196 // Not treated as an error.
2197 _exit(0);
2198 }
2199 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002200 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002201 }
2202
2203 SHA256_CTX ctx;
2204 SHA256_Init(&ctx);
2205
2206 std::vector<uint8_t> buffer(65536);
2207 while (true) {
2208 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2209 if (bytes_read == 0) {
2210 break;
2211 } else if (bytes_read == -1) {
2212 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002213 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002214 }
2215
2216 SHA256_Update(&ctx, buffer.data(), bytes_read);
2217 }
2218
2219 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2220 SHA256_Final(hash.data(), &ctx);
2221 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002222 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002223 }
2224
2225 _exit(0);
2226 }
2227
2228 // parent
2229 pipe_write.reset();
2230
2231 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2232 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2233 out_secondary_dex_hash->clear();
2234 }
2235 return wait_child(pid) == 0;
2236}
2237
Jeff Sharkey90aff262016-12-12 14:28:24 -07002238// Helper for move_ab, so that we can have common failure-case cleanup.
2239static bool unlink_and_rename(const char* from, const char* to) {
2240 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2241 // return a failure.
2242 struct stat s;
2243 if (stat(to, &s) == 0) {
2244 if (!S_ISREG(s.st_mode)) {
2245 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2246 return false;
2247 }
2248 if (unlink(to) != 0) {
2249 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2250 return false;
2251 }
2252 } else {
2253 // This may be a permission problem. We could investigate the error code, but we'll just
2254 // let the rename failure do the work for us.
2255 }
2256
2257 // Try to rename "to" to "from."
2258 if (rename(from, to) != 0) {
2259 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2260 return false;
2261 }
2262 return true;
2263}
2264
2265// Move/rename a B artifact (from) to an A artifact (to).
2266static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2267 // Check whether B exists.
2268 {
2269 struct stat s;
2270 if (stat(b_path.c_str(), &s) != 0) {
2271 // Silently ignore for now. The service calling this isn't smart enough to understand
2272 // lack of artifacts at the moment.
2273 return false;
2274 }
2275 if (!S_ISREG(s.st_mode)) {
2276 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2277 // Try to unlink, but swallow errors.
2278 unlink(b_path.c_str());
2279 return false;
2280 }
2281 }
2282
2283 // Rename B to A.
2284 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2285 // Delete the b_path so we don't try again (or fail earlier).
2286 if (unlink(b_path.c_str()) != 0) {
2287 PLOG(ERROR) << "Could not unlink " << b_path;
2288 }
2289
2290 return false;
2291 }
2292
2293 return true;
2294}
2295
2296bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2297 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002298 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2299 if (slot_suffix.empty()) {
2300 return false;
2301 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002302
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002303 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2304 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2305 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002306 }
2307
2308 // Validate other inputs.
2309 if (validate_apk_path(apk_path) != 0) {
2310 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2311 return false;
2312 }
2313 if (validate_apk_path(oat_dir) != 0) {
2314 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2315 return false;
2316 }
2317
2318 char a_path[PKG_PATH_MAX];
2319 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2320 return false;
2321 }
2322 const std::string a_vdex_path = create_vdex_filename(a_path);
2323 const std::string a_image_path = create_image_filename(a_path);
2324
2325 // B path = A path + slot suffix.
2326 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2327 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2328 const std::string b_image_path = StringPrintf("%s.%s",
2329 a_image_path.c_str(),
2330 slot_suffix.c_str());
2331
2332 bool success = true;
2333 if (move_ab_path(b_path, a_path)) {
2334 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2335 // Note: we can live without an app image. As such, ignore failure to move the image file.
2336 // If we decide to require the app image, or the app image being moved correctly,
2337 // then change accordingly.
2338 constexpr bool kIgnoreAppImageFailure = true;
2339
2340 if (!a_image_path.empty()) {
2341 if (!move_ab_path(b_image_path, a_image_path)) {
2342 unlink(a_image_path.c_str());
2343 if (!kIgnoreAppImageFailure) {
2344 success = false;
2345 }
2346 }
2347 }
2348 } else {
2349 // Cleanup: delete B image, ignore errors.
2350 unlink(b_image_path.c_str());
2351 success = false;
2352 }
2353 } else {
2354 // Cleanup: delete B image, ignore errors.
2355 unlink(b_vdex_path.c_str());
2356 unlink(b_image_path.c_str());
2357 success = false;
2358 }
2359 return success;
2360}
2361
2362bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2363 // Delete the oat/odex file.
2364 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002365 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002366 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002367 return false;
2368 }
2369
2370 // In case of a permission failure report the issue. Otherwise just print a warning.
2371 auto unlink_and_check = [](const char* path) -> bool {
2372 int result = unlink(path);
2373 if (result != 0) {
2374 if (errno == EACCES || errno == EPERM) {
2375 PLOG(ERROR) << "Could not unlink " << path;
2376 return false;
2377 }
2378 PLOG(WARNING) << "Could not unlink " << path;
2379 }
2380 return true;
2381 };
2382
2383 // Delete the oat/odex file.
2384 bool return_value_oat = unlink_and_check(out_path);
2385
2386 // Derive and delete the app image.
2387 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2388
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002389 // Derive and delete the vdex file.
2390 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2391
Jeff Sharkey90aff262016-12-12 14:28:24 -07002392 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002393 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002394}
2395
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002396static bool is_absolute_path(const std::string& path) {
2397 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2398 LOG(ERROR) << "Invalid absolute path " << path;
2399 return false;
2400 } else {
2401 return true;
2402 }
2403}
2404
2405static bool is_valid_instruction_set(const std::string& instruction_set) {
2406 // TODO: add explicit whitelisting of instruction sets
2407 if (instruction_set.find('/') != std::string::npos) {
2408 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2409 return false;
2410 } else {
2411 return true;
2412 }
2413}
2414
2415bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2416 const char *apk_path, const char *instruction_set) {
2417 std::string oat_dir_ = oat_dir;
2418 std::string apk_path_ = apk_path;
2419 std::string instruction_set_ = instruction_set;
2420
2421 if (!is_absolute_path(oat_dir_)) return false;
2422 if (!is_absolute_path(apk_path_)) return false;
2423 if (!is_valid_instruction_set(instruction_set_)) return false;
2424
2425 std::string::size_type end = apk_path_.rfind('.');
2426 std::string::size_type start = apk_path_.rfind('/', end);
2427 if (end == std::string::npos || start == std::string::npos) {
2428 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2429 return false;
2430 }
2431
2432 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2433 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2434 const char* res = res_.c_str();
2435 if (strlen(res) >= PKG_PATH_MAX) {
2436 LOG(ERROR) << "Result too large";
2437 return false;
2438 } else {
2439 strlcpy(path, res, PKG_PATH_MAX);
2440 return true;
2441 }
2442}
2443
2444bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2445 const char *instruction_set) {
2446 std::string apk_path_ = apk_path;
2447 std::string instruction_set_ = instruction_set;
2448
2449 if (!is_absolute_path(apk_path_)) return false;
2450 if (!is_valid_instruction_set(instruction_set_)) return false;
2451
2452 std::string::size_type end = apk_path_.rfind('.');
2453 std::string::size_type start = apk_path_.rfind('/', end);
2454 if (end == std::string::npos || start == std::string::npos) {
2455 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2456 return false;
2457 }
2458
2459 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2460 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2461}
2462
2463bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2464 const char *instruction_set) {
2465 std::string src_ = src;
2466 std::string instruction_set_ = instruction_set;
2467
2468 if (!is_absolute_path(src_)) return false;
2469 if (!is_valid_instruction_set(instruction_set_)) return false;
2470
2471 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2472 if (*it == '/') {
2473 *it = '@';
2474 }
2475 }
2476
2477 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2478 + DALVIK_CACHE_POSTFIX;
2479 const char* res = res_.c_str();
2480 if (strlen(res) >= PKG_PATH_MAX) {
2481 LOG(ERROR) << "Result too large";
2482 return false;
2483 } else {
2484 strlcpy(path, res, PKG_PATH_MAX);
2485 return true;
2486 }
2487}
2488
Calin Juravle59f7ab82018-04-27 17:50:23 -07002489bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2490 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002491 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2492 for (const std::string& elem : classpaths_elems) {
2493 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2494 if (fd < 0) {
2495 PLOG(ERROR) << "Could not open classpath elem " << elem;
2496 return false;
2497 } else {
2498 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002499 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002500 }
2501 }
2502 return true;
2503}
2504
2505static bool create_app_profile_snapshot(int32_t app_id,
2506 const std::string& package_name,
2507 const std::string& profile_name,
2508 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002509 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2510
Calin Juravle824a64d2018-01-18 20:23:17 -08002511 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002512 if (snapshot_fd < 0) {
2513 return false;
2514 }
2515
2516 std::vector<unique_fd> profiles_fd;
2517 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002518 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2519 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002520 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2521 return false;
2522 }
2523
2524 profiles_fd.push_back(std::move(reference_profile_fd));
2525
Calin Juravle0d0a4922018-01-23 19:54:11 -08002526 // Open the class paths elements. These will be used to filter out profile data that does
2527 // not belong to the classpath during merge.
2528 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002529 std::vector<std::string> dex_locations;
2530 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002531 return false;
2532 }
2533
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002534 RunProfman args;
2535 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002536 pid_t pid = fork();
2537 if (pid == 0) {
2538 /* child -- drop privileges before continuing */
2539 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002540 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002541 }
2542
2543 /* parent */
2544 int return_code = wait_child(pid);
2545 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002546 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002547 return false;
2548 }
2549
2550 return true;
2551}
2552
Calin Juravle0d0a4922018-01-23 19:54:11 -08002553static bool create_boot_image_profile_snapshot(const std::string& package_name,
2554 const std::string& profile_name,
2555 const std::string& classpath) {
2556 // The reference profile directory for the android package might not be prepared. Do it now.
2557 const std::string ref_profile_dir =
2558 create_primary_reference_profile_package_dir_path(package_name);
2559 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2560 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2561 return false;
2562 }
2563
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002564 // Return false for empty class path since it may otherwise return true below if profiles is
2565 // empty.
2566 if (classpath.empty()) {
2567 PLOG(ERROR) << "Class path is empty";
2568 return false;
2569 }
2570
Calin Juravle0d0a4922018-01-23 19:54:11 -08002571 // Open and create the snapshot profile.
2572 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2573
2574 // Collect all non empty profiles.
2575 // The collection will traverse all applications profiles and find the non empty files.
2576 // This has the potential of inspecting a large number of files and directories (depending
2577 // on the number of applications and users). So there is a slight increase in the chance
2578 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2579 // fail the snapshot and aggregate whatever profile we could open.
2580 //
2581 // The profile snapshot is a best effort based on available data it's ok if some data
2582 // from some apps is missing. It will be counter productive for the snapshot to fail
2583 // because we could not open or read some of the files.
2584 std::vector<std::string> profiles;
2585 if (!collect_profiles(&profiles)) {
2586 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2587 }
2588
2589 // If we have no profiles return early.
2590 if (profiles.empty()) {
2591 return true;
2592 }
2593
2594 // Open the classpath elements. These will be used to filter out profile data that does
2595 // not belong to the classpath during merge.
2596 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002597 std::vector<std::string> dex_locations;
2598 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002599 return false;
2600 }
2601
2602 // If we could not open any files from the classpath return an error.
2603 if (apk_fds.empty()) {
2604 LOG(ERROR) << "Could not open any of the classpath elements.";
2605 return false;
2606 }
2607
2608 // Aggregate the profiles in batches of kAggregationBatchSize.
2609 // We do this to avoid opening a huge a amount of files.
2610 static constexpr size_t kAggregationBatchSize = 10;
2611
2612 std::vector<unique_fd> profiles_fd;
2613 for (size_t i = 0; i < profiles.size(); ) {
2614 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2615 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2616 if (fd.get() >= 0) {
2617 profiles_fd.push_back(std::move(fd));
2618 }
2619 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002620 RunProfman args;
2621 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002622 pid_t pid = fork();
2623 if (pid == 0) {
2624 /* child -- drop privileges before continuing */
2625 drop_capabilities(AID_SYSTEM);
2626
Calin Juravle59f7ab82018-04-27 17:50:23 -07002627 // The introduction of new access flags into boot jars causes them to
2628 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002629 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002630 }
2631
2632 /* parent */
2633 int return_code = wait_child(pid);
2634 if (!WIFEXITED(return_code)) {
2635 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2636 return false;
2637 }
2638 return true;
2639 }
2640 return true;
2641}
2642
2643bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2644 const std::string& profile_name, const std::string& classpath) {
2645 if (app_id == -1) {
2646 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2647 } else {
2648 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2649 }
2650}
2651
Calin Juravlec3b049e2018-01-18 22:32:58 -08002652bool prepare_app_profile(const std::string& package_name,
2653 userid_t user_id,
2654 appid_t app_id,
2655 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002656 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002657 const std::unique_ptr<std::string>& dex_metadata) {
2658 // Prepare the current profile.
2659 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2660 /*is_secondary_dex*/ false);
2661 uid_t uid = multiuser_get_uid(user_id, app_id);
2662 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2663 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2664 return false;
2665 }
2666
2667 // Check if we need to install the profile from the dex metadata.
2668 if (dex_metadata == nullptr) {
2669 return true;
2670 }
2671
2672 // We have a dex metdata. Merge the profile into the reference profile.
2673 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2674 /*read_write*/ true, /*is_secondary_dex*/ false);
2675 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2676 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002677 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2678 if (apk_fd < 0) {
2679 PLOG(ERROR) << "Could not open code path " << code_path;
2680 return false;
2681 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002682
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002683 RunProfman args;
2684 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2685 std::move(ref_profile_fd),
2686 std::move(apk_fd),
2687 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002688 pid_t pid = fork();
2689 if (pid == 0) {
2690 /* child -- drop privileges before continuing */
2691 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2692 drop_capabilities(app_shared_gid);
2693
Calin Juravlef63d4792018-01-30 17:43:34 +00002694 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002695 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002696 }
2697
2698 /* parent */
2699 int return_code = wait_child(pid);
2700 if (!WIFEXITED(return_code)) {
2701 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2702 return false;
2703 }
2704 return true;
2705}
2706
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002707} // namespace installd
2708} // namespace android