blob: eaf6831c1689f9ef47f2dc28e39dc32eb8c71855 [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.
Roland Levillain67a14f62019-01-23 15:59:50 +0000335 const char* dex2oat_bin = kDex2oatPath;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800336 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
337 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
338 if (is_debug_runtime() ||
339 (background_job_compile && is_debuggable_build() && !is_release)) {
340 if (access(kDex2oatDebugPath, X_OK) == 0) {
341 dex2oat_bin = kDex2oatDebugPath;
342 }
343 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000344
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800345 bool generate_minidebug_info = kEnableMinidebugInfo &&
346 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000347
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800348 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
349 // use arraysize instead.
350 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
351 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
352 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
353 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
354 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
355 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
356 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
357 std::string dex2oat_compiler_filter_arg;
358 std::string dex2oat_swap_fd;
359 std::string dex2oat_image_fd;
360 std::string target_sdk_version_arg;
361 if (target_sdk_version != 0) {
362 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
363 }
364 std::string class_loader_context_arg;
365 if (class_loader_context != nullptr) {
366 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
367 class_loader_context);
368 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000369
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800370 if (swap_fd >= 0) {
371 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
372 }
373 if (image_fd >= 0) {
374 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
375 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000376
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800377 // Compute compiler filter.
378 bool have_dex2oat_relocation_skip_flag = false;
379 if (skip_compilation) {
380 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
381 have_dex2oat_relocation_skip_flag = true;
382 } else if (compiler_filter != nullptr) {
383 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
384 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000385
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800386 if (dex2oat_compiler_filter_arg.empty()) {
387 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
388 "--compiler-filter=%s");
389 }
390
391 // Check whether all apps should be compiled debuggable.
392 if (!debuggable) {
393 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
394 }
395 std::string profile_arg;
396 if (profile_fd != -1) {
397 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
398 }
399
400 // Get the directory of the apk to pass as a base classpath directory.
401 std::string base_dir;
402 std::string apk_dir(input_file_name);
403 unsigned long dir_index = apk_dir.rfind('/');
404 bool has_base_dir = dir_index != std::string::npos;
405 if (has_base_dir) {
406 apk_dir = apk_dir.substr(0, dir_index);
407 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
408 }
409
410 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
411
412 std::string compilation_reason_arg = compilation_reason == nullptr
413 ? ""
414 : std::string("--compilation-reason=") + compilation_reason;
415
416 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
417
418 // Disable cdex if update input vdex is true since this combination of options is not
419 // supported.
420 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
421
422 AddArg(zip_fd_arg);
423 AddArg(zip_location_arg);
424 AddArg(input_vdex_fd_arg);
425 AddArg(output_vdex_fd_arg);
426 AddArg(oat_fd_arg);
427 AddArg(oat_location_arg);
428 AddArg(instruction_set_arg);
429
430 AddArg(instruction_set_variant_arg);
431 AddArg(instruction_set_features_arg);
432
433 AddRuntimeArg(dex2oat_Xms_arg);
434 AddRuntimeArg(dex2oat_Xmx_arg);
435
436 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800437 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800438 AddArg(dex2oat_compiler_filter_arg);
439 AddArg(dex2oat_threads_arg);
440 AddArg(dex2oat_swap_fd);
441 AddArg(dex2oat_image_fd);
442
443 if (generate_debug_info) {
444 AddArg("--generate-debug-info");
445 }
446 if (debuggable) {
447 AddArg("--debuggable");
448 }
449 AddArg(image_format_arg);
450 AddArg(dex2oat_large_app_threshold_arg);
451
452 if (have_dex2oat_relocation_skip_flag) {
453 AddRuntimeArg(dex2oat_norelocation);
454 }
455 AddArg(profile_arg);
456 AddArg(base_dir);
457 AddArg(class_loader_context_arg);
458 if (generate_minidebug_info) {
459 AddArg(kMinidebugDex2oatFlag);
460 }
461 if (disable_cdex) {
462 AddArg(kDisableCompactDexFlag);
463 }
464 AddArg(target_sdk_version_arg);
465 if (enable_hidden_api_checks) {
466 AddRuntimeArg("-Xhidden-api-checks");
467 }
468
469 if (dex_metadata_fd > -1) {
470 AddArg(dex_metadata_fd_arg);
471 }
472
473 AddArg(compilation_reason_arg);
474
475 // Do not add args after dex2oat_flags, they should override others for debugging.
476 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
477
478 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000479 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800480};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700481
482/*
483 * Whether dexopt should use a swap file when compiling an APK.
484 *
485 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
486 * itself, anyways).
487 *
488 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
489 *
490 * Otherwise, return true if this is a low-mem device.
491 *
492 * Otherwise, return default value.
493 */
494static bool kAlwaysProvideSwapFile = false;
495static bool kDefaultProvideSwapFile = true;
496
497static bool ShouldUseSwapFileForDexopt() {
498 if (kAlwaysProvideSwapFile) {
499 return true;
500 }
501
502 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700503 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
504 if (!dex2oat_prop_buf.empty()) {
505 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700506 }
507
508 // Shortcut for default value. This is an implementation optimization for the process sketched
509 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
510 // as low-mem is never returning false. The compiler will optimize this away if it can.
511 if (kDefaultProvideSwapFile) {
512 return true;
513 }
514
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700515 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700516 return true;
517 }
518
519 // Default value must be false here.
520 return kDefaultProvideSwapFile;
521}
522
Richard Uhler76cc0272016-12-08 10:46:35 +0000523static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700524 if (set_to_bg) {
525 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800526 PLOG(ERROR) << "set_sched_policy failed";
527 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700528 }
529 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800530 PLOG(ERROR) << "setpriority failed";
531 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700532 }
533 }
534}
535
Calin Juravle29591732017-11-20 17:46:19 -0800536static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
537 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800538 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800539 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800540 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800541 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800542 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700543 }
Calin Juravle114f0812017-03-08 19:05:07 -0800544 // Profiles should belong to the app; make sure of that by giving ownership to
545 // the app uid. If we cannot do that, there's no point in returning the fd
546 // since dex2oat/profman will fail with SElinux denials.
547 if (fchown(fd.get(), uid, uid) < 0) {
548 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800549 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800550 }
Calin Juravle29591732017-11-20 17:46:19 -0800551 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800552}
553
Calin Juravle29591732017-11-20 17:46:19 -0800554static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800555 // Do not follow symlinks when opening a profile:
556 // - primary profiles should not contain symlinks in their paths
557 // - secondary dex paths should have been already resolved and validated
558 flags |= O_NOFOLLOW;
559
Calin Juravle29591732017-11-20 17:46:19 -0800560 // Check if we need to create the profile
561 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
562 unique_fd fd;
563 if ((flags & O_CREAT) != 0) {
564 fd = create_profile(uid, profile, flags);
565 } else {
566 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
567 }
568
Calin Juravle114f0812017-03-08 19:05:07 -0800569 if (fd.get() < 0) {
570 if (errno != ENOENT) {
571 // Profiles might be missing for various reasons. For example, in a
572 // multi-user environment, the profile directory for one user can be created
573 // after we start a merge. In this case the current profile for that user
574 // will not be found.
575 // Also, the secondary dex profiles might be deleted by the app at any time,
576 // so we can't we need to prepare if they are missing.
577 PLOG(ERROR) << "Failed to open profile " << profile;
578 }
579 return invalid_unique_fd();
580 }
581
Jeff Sharkey90aff262016-12-12 14:28:24 -0700582 return fd;
583}
584
Calin Juravle824a64d2018-01-18 20:23:17 -0800585static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
586 const std::string& location, bool is_secondary_dex) {
587 std::string profile = create_current_profile_path(user, package_name, location,
588 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800589 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800590}
591
Calin Juravle824a64d2018-01-18 20:23:17 -0800592static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
593 const std::string& location, bool read_write, bool is_secondary_dex) {
594 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800595 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
596}
597
598static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800599 const std::string& location) {
600 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800601 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800602}
603
Calin Juravle824a64d2018-01-18 20:23:17 -0800604static void open_profile_files(uid_t uid, const std::string& package_name,
605 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800606 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700607 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800608 *reference_profile_fd = open_reference_profile(uid, package_name, location,
609 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700610
Calin Juravle114f0812017-03-08 19:05:07 -0800611 // For secondary dex files, we don't really need the user but we use it for sanity checks.
612 // Note: the user owning the dex file should be the current user.
613 std::vector<userid_t> users;
614 if (is_secondary_dex){
615 users.push_back(multiuser_get_user_id(uid));
616 } else {
617 users = get_known_users(/*volume_uuid*/ nullptr);
618 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700619 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800620 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
621 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700622 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800623 if (profile_fd.get() >= 0) {
624 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700625 }
626 }
627}
628
Jeff Sharkey90aff262016-12-12 14:28:24 -0700629static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
630static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
631static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
632static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
633static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
634
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800635class RunProfman : public ExecVHelper {
636 public:
637 void SetupArgs(const std::vector<unique_fd>& profile_fds,
638 const unique_fd& reference_profile_fd,
639 const std::vector<unique_fd>& apk_fds,
640 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800641 bool copy_and_update,
642 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000643 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800645 if (copy_and_update) {
646 CHECK_EQ(1u, profile_fds.size());
647 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000648 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800649 if (reference_profile_fd != -1) {
650 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000651 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800652
653 for (const unique_fd& fd : profile_fds) {
654 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
655 }
656
657 for (const unique_fd& fd : apk_fds) {
658 AddArg("--apk-fd=" + std::to_string(fd.get()));
659 }
660
661 for (const std::string& dex_location : dex_locations) {
662 AddArg("--dex-location=" + dex_location);
663 }
664
665 if (copy_and_update) {
666 AddArg("--copy-and-update-profile-key");
667 }
668
Calin Juravleb3a929d2018-12-11 14:40:00 -0800669 if (store_aggregation_counters) {
670 AddArg("--store-aggregation-counters");
671 }
672
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800673 // Do not add after dex2oat_flags, they should override others for debugging.
674 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800675 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700676
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800677 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
678 const unique_fd& reference_profile_fd,
679 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800680 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
681 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800682 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800683 reference_profile_fd,
684 apk_fds,
685 dex_locations,
686 /*copy_and_update=*/false,
687 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800688 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800690 void SetupCopyAndUpdate(unique_fd&& profile_fd,
691 unique_fd&& reference_profile_fd,
692 unique_fd&& apk_fd,
693 const std::string& dex_location) {
694 // The fds need to stay open longer than the scope of the function, so put them into a local
695 // variable vector.
696 profiles_fd_.push_back(std::move(profile_fd));
697 apk_fds_.push_back(std::move(apk_fd));
698 reference_profile_fd_ = std::move(reference_profile_fd);
699 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800700 SetupArgs(profiles_fd_,
701 reference_profile_fd_,
702 apk_fds_,
703 dex_locations,
704 /*copy_and_update=*/true,
705 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800706 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000707
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800708 void SetupDump(const std::vector<unique_fd>& profiles_fd,
709 const unique_fd& reference_profile_fd,
710 const std::vector<std::string>& dex_locations,
711 const std::vector<unique_fd>& apk_fds,
712 const unique_fd& output_fd) {
713 AddArg("--dump-only");
714 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800715 SetupArgs(profiles_fd,
716 reference_profile_fd,
717 apk_fds,
718 dex_locations,
719 /*copy_and_update=*/false,
720 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800721 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000722
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800723 void Exec() {
724 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
725 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000726
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800727 private:
728 unique_fd reference_profile_fd_;
729 std::vector<unique_fd> profiles_fd_;
730 std::vector<unique_fd> apk_fds_;
731};
Mathieu Chartier31636522018-11-09 23:53:07 +0000732
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800733
Calin Juravlef63d4792018-01-30 17:43:34 +0000734
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800736// The location is the package name for primary apks or the dex path for secondary dex files.
737// Returns true if there is enough information in the current profiles that makes it
738// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700739// If the return value is true all the current profiles would have been merged into
740// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800741static bool analyze_profiles(uid_t uid, const std::string& package_name,
742 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800743 std::vector<unique_fd> profiles_fd;
744 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800745 open_profile_files(uid, package_name, location, is_secondary_dex,
746 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800747 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700748 // Skip profile guided compilation because no profiles were found.
749 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750 return false;
751 }
752
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800753 RunProfman profman_merge;
754 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700755 pid_t pid = fork();
756 if (pid == 0) {
757 /* child -- drop privileges before continuing */
758 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800759 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700760 }
761 /* parent */
762 int return_code = wait_child(pid);
763 bool need_to_compile = false;
764 bool should_clear_current_profiles = false;
765 bool should_clear_reference_profile = false;
766 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800767 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700768 } else {
769 return_code = WEXITSTATUS(return_code);
770 switch (return_code) {
771 case PROFMAN_BIN_RETURN_CODE_COMPILE:
772 need_to_compile = true;
773 should_clear_current_profiles = true;
774 should_clear_reference_profile = false;
775 break;
776 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
777 need_to_compile = false;
778 should_clear_current_profiles = false;
779 should_clear_reference_profile = false;
780 break;
781 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800782 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783 need_to_compile = false;
784 should_clear_current_profiles = true;
785 should_clear_reference_profile = true;
786 break;
787 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
788 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
789 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800790 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700791 need_to_compile = false;
792 should_clear_current_profiles = false;
793 should_clear_reference_profile = false;
794 break;
795 default:
796 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800797 LOG(WARNING) << "Unknown error code while processing profiles for location "
798 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700799 need_to_compile = false;
800 should_clear_current_profiles = true;
801 should_clear_reference_profile = true;
802 break;
803 }
804 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800805
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800807 if (is_secondary_dex) {
808 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800809 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
810 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800811 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800812 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800813 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 }
815 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800816 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 }
818 return need_to_compile;
819}
820
Calin Juravle114f0812017-03-08 19:05:07 -0800821// Decides if profile guided compilation is needed or not based on existing profiles.
822// The analysis is done for the primary apks of the given package.
823// Returns true if there is enough information in the current profiles that makes it
824// worth to recompile the package.
825// If the return value is true all the current profiles would have been merged into
826// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800827bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
828 const std::string& profile_name) {
829 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800830}
831
Calin Juravle408cd4a2018-01-20 23:34:18 -0800832bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
833 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800834 std::vector<unique_fd> profile_fds;
835 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800836 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
837 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700838
Calin Juravle408cd4a2018-01-20 23:34:18 -0800839 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800840 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800842 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700843 const bool has_profiles = !profile_fds.empty();
844
845 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800846 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 return false;
848 }
849
Calin Juravle114f0812017-03-08 19:05:07 -0800850 unique_fd output_fd(open(out_file_name.c_str(),
851 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700852 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800853 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700854 return false;
855 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800856
Jeff Sharkey90aff262016-12-12 14:28:24 -0700857 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800858 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800859 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
860 if (apk_fd == -1) {
861 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
862 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700863 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800864 dex_locations.push_back(get_location_from_path(code_path.c_str()));
865 apk_fds.push_back(std::move(apk_fd));
866
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800868 RunProfman profman_dump;
869 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 pid_t pid = fork();
871 if (pid == 0) {
872 /* child -- drop privileges before continuing */
873 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800874 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700875 }
876 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877 int return_code = wait_child(pid);
878 if (!WIFEXITED(return_code)) {
879 LOG(WARNING) << "profman failed for package " << pkgname << ": "
880 << return_code;
881 return false;
882 }
883 return true;
884}
885
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700886bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800887 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700888 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
889 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800890 package_name,
891 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700892 /*read_write*/ true,
893 /*secondary*/ false));
894 if (in_fd.get() < 0) {
895 PLOG(WARNING) << "Could not open profile " << system_profile;
896 return false;
897 }
898 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800899 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700900 return false;
901 }
902
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700903 // As a security measure we want to write the profile information with the reduced capabilities
904 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700905 pid_t pid = fork();
906 if (pid == 0) {
907 /* child -- drop privileges before continuing */
908 drop_capabilities(packageUid);
909
910 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
911 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800912 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700913 }
914 // This implies that the app owning this profile is running
915 // (and has acquired the lock).
916 //
917 // The app never acquires the lock for the reference profiles of primary apks.
918 // Only dex2oat from installd will do that. Since installd is single threaded
919 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800920 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700921 return false;
922 }
923
924 bool truncated = ftruncate(out_fd.get(), 0) == 0;
925 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800926 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700927 }
928
929 // Copy over data.
930 static constexpr size_t kBufferSize = 4 * 1024;
931 char buffer[kBufferSize];
932 while (true) {
933 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
934 if (bytes == 0) {
935 break;
936 }
937 write(out_fd.get(), buffer, bytes);
938 }
939 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800940 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700941 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700942 // Use _exit since we don't want to run the global destructors in the child.
943 // b/62597429
944 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700945 }
946 /* parent */
947 int return_code = wait_child(pid);
948 return return_code == 0;
949}
950
Jeff Sharkey90aff262016-12-12 14:28:24 -0700951static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
952 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
953 if (EndsWith(oat_path, ".dex")) {
954 std::string new_path = oat_path;
955 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800956 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700957 return new_path;
958 }
959
960 // An odex entry. Not that this may not be an extension, e.g., in the OTA
961 // case (where the base name will have an extension for the B artifact).
962 size_t odex_pos = oat_path.rfind(".odex");
963 if (odex_pos != std::string::npos) {
964 std::string new_path = oat_path;
965 new_path.replace(odex_pos, strlen(".odex"), new_ext);
966 CHECK_NE(new_path.find(new_ext), std::string::npos);
967 return new_path;
968 }
969
970 // Don't know how to handle this.
971 return "";
972}
973
974// Translate the given oat path to an art (app image) path. An empty string
975// denotes an error.
976static std::string create_image_filename(const std::string& oat_path) {
977 return replace_file_extension(oat_path, ".art");
978}
979
980// Translate the given oat path to a vdex path. An empty string denotes an error.
981static std::string create_vdex_filename(const std::string& oat_path) {
982 return replace_file_extension(oat_path, ".vdex");
983}
984
Jeff Sharkey90aff262016-12-12 14:28:24 -0700985static int open_output_file(const char* file_name, bool recreate, int permissions) {
986 int flags = O_RDWR | O_CREAT;
987 if (recreate) {
988 if (unlink(file_name) < 0) {
989 if (errno != ENOENT) {
990 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
991 }
992 }
993 flags |= O_EXCL;
994 }
995 return open(file_name, flags, permissions);
996}
997
Calin Juravle2289c0a2017-02-15 12:44:14 -0800998static bool set_permissions_and_ownership(
999 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1000 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1001 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 if (fchmod(fd,
1003 S_IRUSR|S_IWUSR|S_IRGRP |
1004 (is_public ? S_IROTH : 0)) < 0) {
1005 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1006 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001007 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001008 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1009 return false;
1010 }
1011 return true;
1012}
1013
1014static bool IsOutputDalvikCache(const char* oat_dir) {
1015 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1016 // into '!'. Play it safe by handling it both.
1017 // TODO: ensure we never get null.
1018 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1019 return oat_dir == nullptr || oat_dir[0] == '!';
1020}
1021
Calin Juravled23dee72017-07-06 16:29:11 -07001022// Best-effort check whether we can fit the the path into our buffers.
1023// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1024// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1025// extension to the cache path (5 bytes).
1026// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1027static bool validate_dex_path_size(const std::string& dex_path) {
1028 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1029 LOG(ERROR) << "dex_path too long: " << dex_path;
1030 return false;
1031 }
1032 return true;
1033}
1034
Jeff Sharkey90aff262016-12-12 14:28:24 -07001035static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001036 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001037 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001038 return false;
1039 }
1040
1041 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001042 // Oat dirs for secondary dex files are already validated.
1043 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001044 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1045 return false;
1046 }
1047 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1048 return false;
1049 }
1050 } else {
1051 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1052 return false;
1053 }
1054 }
1055 return true;
1056}
1057
1058// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1059// on destruction. It will also run the given cleanup (unless told not to) after closing.
1060//
1061// Usage example:
1062//
Calin Juravle7a570e82017-01-14 16:23:30 -08001063// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001064// [name]() {
1065// unlink(name.c_str());
1066// });
1067// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1068// wrapper if captured as a reference.
1069//
1070// if (file.get() == -1) {
1071// // Error opening...
1072// }
1073//
1074// ...
1075// if (error) {
1076// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1077// // and delete the file (after the fd is closed).
1078// return -1;
1079// }
1080//
1081// (Success case)
1082// file.SetCleanup(false);
1083// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1084// // (leaving the file around; after the fd is closed).
1085//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001086class Dex2oatFileWrapper {
1087 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001088 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 }
1090
Calin Juravle7a570e82017-01-14 16:23:30 -08001091 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1092 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1093
1094 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1095 value_ = other.value_;
1096 cleanup_ = other.cleanup_;
1097 do_cleanup_ = other.do_cleanup_;
1098 auto_close_ = other.auto_close_;
1099 other.release();
1100 }
1101
1102 Dex2oatFileWrapper& operator=(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 return *this;
1109 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001110
1111 ~Dex2oatFileWrapper() {
1112 reset(-1);
1113 }
1114
1115 int get() {
1116 return value_;
1117 }
1118
1119 void SetCleanup(bool cleanup) {
1120 do_cleanup_ = cleanup;
1121 }
1122
1123 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001124 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 close(value_);
1126 }
1127 if (do_cleanup_ && cleanup_ != nullptr) {
1128 cleanup_();
1129 }
1130
1131 value_ = new_value;
1132 }
1133
Calin Juravle7a570e82017-01-14 16:23:30 -08001134 void reset(int new_value, std::function<void ()> new_cleanup) {
1135 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001136 close(value_);
1137 }
1138 if (do_cleanup_ && cleanup_ != nullptr) {
1139 cleanup_();
1140 }
1141
1142 value_ = new_value;
1143 cleanup_ = new_cleanup;
1144 }
1145
Calin Juravle7a570e82017-01-14 16:23:30 -08001146 void DisableAutoClose() {
1147 auto_close_ = false;
1148 }
1149
Jeff Sharkey90aff262016-12-12 14:28:24 -07001150 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001151 void release() {
1152 value_ = -1;
1153 do_cleanup_ = false;
1154 cleanup_ = nullptr;
1155 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001156 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001157 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001159 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001160};
1161
Calin Juravle7a570e82017-01-14 16:23:30 -08001162// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001163Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1164 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001165
1166 // We don't create an image for secondary dex files.
1167 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001168 return Dex2oatFileWrapper();
1169 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001170
Calin Juravle7a570e82017-01-14 16:23:30 -08001171 const std::string image_path = create_image_filename(out_oat_path);
1172 if (image_path.empty()) {
1173 // Happens when the out_oat_path has an unknown extension.
1174 return Dex2oatFileWrapper();
1175 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001176
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001177 // In case there is a stale image, remove it now. Ignore any error.
1178 unlink(image_path.c_str());
1179
1180 // Not enabled, exit.
1181 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001182 return Dex2oatFileWrapper();
1183 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001184 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1185 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 return Dex2oatFileWrapper();
1187 }
1188 // Recreate is true since we do not want to modify a mapped image. If the app is
1189 // already running and we modify the image file, it can cause crashes (b/27493510).
1190 Dex2oatFileWrapper wrapper_fd(
1191 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1192 [image_path]() { unlink(image_path.c_str()); });
1193 if (wrapper_fd.get() < 0) {
1194 // Could not create application image file. Go on since we can compile without it.
1195 LOG(ERROR) << "installd could not create '" << image_path
1196 << "' for image file during dexopt";
1197 // If we have a valid image file path but no image fd, explicitly erase the image file.
1198 if (unlink(image_path.c_str()) < 0) {
1199 if (errno != ENOENT) {
1200 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1201 }
1202 }
1203 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001204 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001205 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1206 wrapper_fd.reset(-1);
1207 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001208
Calin Juravle7a570e82017-01-14 16:23:30 -08001209 return wrapper_fd;
1210}
1211
1212// Creates the dexopt swap file if necessary and return its fd.
1213// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001214unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001215 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001216 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001218 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001219 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001220 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001221 if (swap_fd.get() < 0) {
1222 // Could not create swap file. Optimistically go on and hope that we can compile
1223 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001224 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 } else {
1226 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001227 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001228 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1229 }
1230 }
1231 return swap_fd;
1232}
1233
1234// Opens the reference profiles if needed.
1235// 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 -08001236Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001237 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001238 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001239 // If we are not profile guided compilation, or we are compiling system server
1240 // do not bother to open the profiles; we won't be using them.
1241 if (!profile_guided || (pkgname[0] == '*')) {
1242 return Dex2oatFileWrapper();
1243 }
1244
1245 // If this is a secondary dex path which is public do not open the profile.
1246 // We cannot compile public secondary dex paths with profiles. That's because
1247 // it will expose how the dex files are used by their owner.
1248 //
1249 // Note that the PackageManager is responsible to set the is_public flag for
1250 // primary apks and we do not check it here. In some cases, e.g. when
1251 // compiling with a public profile from the .dm file the PackageManager will
1252 // set is_public toghether with the profile guided compilation.
1253 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001254 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001255 }
Calin Juravle114f0812017-03-08 19:05:07 -08001256
1257 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001258 std::string location;
1259 if (is_secondary_dex) {
1260 location = dex_path;
1261 } else {
1262 if (profile_name == nullptr) {
1263 // This path is taken for system server re-compilation lunched from ZygoteInit.
1264 return Dex2oatFileWrapper();
1265 } else {
1266 location = profile_name;
1267 }
1268 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001269 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1270 is_secondary_dex);
1271 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1272 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001273 };
1274 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001275}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001276
Calin Juravle7a570e82017-01-14 16:23:30 -08001277// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1278// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001279bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001280 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001281 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001282 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1283 CHECK(in_vdex_wrapper_fd != nullptr);
1284 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001285 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1286 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001287 char in_odex_path[PKG_PATH_MAX];
1288 int dexopt_action = abs(dexopt_needed);
1289 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001290 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001291
1292 // Infer the name of the output VDEX.
1293 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1294 if (out_vdex_path_str.empty()) {
1295 return false;
1296 }
1297
1298 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001299 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001300 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1301 const char* path = nullptr;
1302 if (is_odex_location) {
1303 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1304 path = in_odex_path;
1305 } else {
1306 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001307 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001308 }
1309 } else {
1310 path = out_oat_path;
1311 }
1312 in_vdex_path_str = create_vdex_filename(path);
1313 if (in_vdex_path_str.empty()) {
1314 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001315 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001316 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001317 // We can update in place when all these conditions are met:
1318 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1319 // on /system typically cannot be updated in place).
1320 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1321 // cannot be currently used by a running process.
1322 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1323 // different vdex files to operate.
1324 update_vdex_in_place =
1325 (in_vdex_path_str == out_vdex_path_str) &&
1326 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1327 !profile_guided;
1328 if (update_vdex_in_place) {
1329 // Open the file read-write to be able to update it.
1330 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1331 if (in_vdex_wrapper_fd->get() == -1) {
1332 // If we failed to open the file, we cannot update it in place.
1333 update_vdex_in_place = false;
1334 }
1335 } else {
1336 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1337 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001338 }
1339
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001340 // If we are updating the vdex in place, we do not need to recreate a vdex,
1341 // and can use the same existing one.
1342 if (update_vdex_in_place) {
1343 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1344 // have bogus stale vdex files.
1345 out_vdex_wrapper_fd->reset(
1346 in_vdex_wrapper_fd->get(),
1347 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1348 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1349 // wrapper).
1350 in_vdex_wrapper_fd->DisableAutoClose();
1351 } else {
1352 out_vdex_wrapper_fd->reset(
1353 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1354 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1355 if (out_vdex_wrapper_fd->get() < 0) {
1356 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1357 return false;
1358 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001359 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001360 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001361 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001362 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1363 return false;
1364 }
1365
1366 // If we got here we successfully opened the vdex files.
1367 return true;
1368}
1369
1370// Opens the output oat file for the given apk.
1371// If successful it stores the output path into out_oat_path and returns true.
1372Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001373 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1374 char* out_oat_path) {
1375 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001376 return Dex2oatFileWrapper();
1377 }
1378 const std::string out_oat_path_str(out_oat_path);
1379 Dex2oatFileWrapper wrapper_fd(
1380 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1381 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1382 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001383 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001384 } else if (!set_permissions_and_ownership(
1385 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001386 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1387 wrapper_fd.reset(-1);
1388 }
1389 return wrapper_fd;
1390}
1391
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001392// Creates RDONLY fds for oat and vdex files, if exist.
1393// Returns false if it fails to create oat out path for the given apk path.
1394// Note that the method returns true even if the files could not be opened.
1395bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1396 const std::string& oat_dir,
1397 const std::string& instruction_set,
1398 bool is_secondary_dex,
1399 unique_fd* oat_file_fd,
1400 unique_fd* vdex_file_fd) {
1401 char oat_path[PKG_PATH_MAX];
1402 if (!create_oat_out_path(apk_path.c_str(),
1403 instruction_set.c_str(),
1404 oat_dir.c_str(),
1405 is_secondary_dex,
1406 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001407 LOG(ERROR) << "Could not create oat out path for "
1408 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001409 return false;
1410 }
1411 oat_file_fd->reset(open(oat_path, O_RDONLY));
1412 if (oat_file_fd->get() < 0) {
1413 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1414 }
1415
1416 std::string vdex_filename = create_vdex_filename(oat_path);
1417 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1418 if (vdex_file_fd->get() < 0) {
1419 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1420 }
1421
1422 return true;
1423}
1424
Calin Juravle7a570e82017-01-14 16:23:30 -08001425// Updates the access times of out_oat_path based on those from apk_path.
1426void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1427 struct stat input_stat;
1428 memset(&input_stat, 0, sizeof(input_stat));
1429 if (stat(apk_path, &input_stat) != 0) {
1430 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1431 return;
1432 }
1433
1434 struct utimbuf ut;
1435 ut.actime = input_stat.st_atime;
1436 ut.modtime = input_stat.st_mtime;
1437 if (utime(out_oat_path, &ut) != 0) {
1438 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1439 }
1440}
1441
Calin Juravle80a21252017-01-17 14:43:25 -08001442// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001443// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1444// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1445// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001446class RunDexoptAnalyzer : public ExecVHelper {
1447 public:
1448 RunDexoptAnalyzer(const std::string& dex_file,
1449 int vdex_fd,
1450 int oat_fd,
1451 int zip_fd,
1452 const std::string& instruction_set,
1453 const std::string& compiler_filter,
1454 bool profile_was_updated,
1455 bool downgrade,
1456 const char* class_loader_context) {
1457 CHECK_GE(zip_fd, 0);
1458 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001459 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001460
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001461 std::string dex_file_arg = "--dex-file=" + dex_file;
1462 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1463 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1464 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1465 std::string isa_arg = "--isa=" + instruction_set;
1466 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1467 const char* assume_profile_changed = "--assume-profile-changed";
1468 const char* downgrade_flag = "--downgrade";
1469 std::string class_loader_context_arg = "--class-loader-context=";
1470 if (class_loader_context != nullptr) {
1471 class_loader_context_arg += class_loader_context;
1472 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001473
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001474 // program name, dex file, isa, filter
1475 AddArg(dex_file_arg);
1476 AddArg(isa_arg);
1477 AddArg(compiler_filter_arg);
1478 if (oat_fd >= 0) {
1479 AddArg(oat_fd_arg);
1480 }
1481 if (vdex_fd >= 0) {
1482 AddArg(vdex_fd_arg);
1483 }
1484 AddArg(zip_fd_arg.c_str());
1485 if (profile_was_updated) {
1486 AddArg(assume_profile_changed);
1487 }
1488 if (downgrade) {
1489 AddArg(downgrade_flag);
1490 }
1491 if (class_loader_context != nullptr) {
1492 AddArg(class_loader_context_arg.c_str());
1493 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001494
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001495 PrepareArgs(dexoptanalyzer_bin);
1496 }
1497};
Calin Juravle80a21252017-01-17 14:43:25 -08001498
1499// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001500static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001501 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001502 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001503 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001504 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001505 return false;
1506 }
Calin Juravle114f0812017-03-08 19:05:07 -08001507 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001508
Calin Juravle80a21252017-01-17 14:43:25 -08001509 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001510 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1511 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001512 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001513 return false;
1514 }
1515
1516 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001517 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001518
Calin Juravle7d765462017-09-04 15:57:10 -07001519 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001520 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001521 return false;
1522 }
1523
1524 return true;
1525}
1526
Calin Juravle7d765462017-09-04 15:57:10 -07001527// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1528// secondary dex files. This return codes are returned by the child process created for
1529// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001530
Andreas Gampe194fe422018-02-28 20:16:19 -08001531enum DexoptAnalyzerSkipCodes {
1532 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001533 // Specific errors are encoded in the name.
1534 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1535 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1536 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1537 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1538 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001539 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001540 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001541};
Calin Juravle7d765462017-09-04 15:57:10 -07001542
1543// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001544// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1545// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001546// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1547// of dexoptanalyzer.
1548static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001549 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001550 // The result values are defined in dexoptanalyzer.
1551 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001552 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001553 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001554 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001555 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001556 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001557 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001558 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001559 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001560 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1561 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001562 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1563 " Expected odex file status for secondary dex %s"
1564 " : dexoptanalyzer result=%d",
1565 dex_path.c_str(),
1566 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001567 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001568 }
1569
1570 // Use a second switch for enum switch-case analysis.
1571 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001572 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001573 // If the file does not exist there's no need for dexopt.
1574 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1575 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001576
1577 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1578 *error_msg = "Dexoptanalyzer path validation failed";
1579 return false;
1580 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1581 *error_msg = "Dexoptanalyzer open zip failed";
1582 return false;
1583 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1584 *error_msg = "Dexoptanalyzer dir preparation failed";
1585 return false;
1586 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1587 *error_msg = "Dexoptanalyzer open output failed";
1588 return false;
1589 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1590 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001591 return false;
1592 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001593
1594 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1595 dex_path.c_str(),
1596 result);
1597 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001598}
1599
Calin Juravle7d765462017-09-04 15:57:10 -07001600enum SecondaryDexAccess {
1601 kSecondaryDexAccessReadOk = 0,
1602 kSecondaryDexAccessDoesNotExist = 1,
1603 kSecondaryDexAccessPermissionError = 2,
1604 kSecondaryDexAccessIOError = 3
1605};
1606
1607static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1608 // Check if the path exists and can be read. If not, there's nothing to do.
1609 if (access(dex_path.c_str(), R_OK) == 0) {
1610 return kSecondaryDexAccessReadOk;
1611 } else {
1612 if (errno == ENOENT) {
1613 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1614 return kSecondaryDexAccessDoesNotExist;
1615 } else {
1616 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1617 return errno == EACCES
1618 ? kSecondaryDexAccessPermissionError
1619 : kSecondaryDexAccessIOError;
1620 }
1621 }
1622}
1623
1624static bool is_file_public(const std::string& filename) {
1625 struct stat file_stat;
1626 if (stat(filename.c_str(), &file_stat) == 0) {
1627 return (file_stat.st_mode & S_IROTH) != 0;
1628 }
1629 return false;
1630}
1631
1632// Create the oat file structure for the secondary dex 'dex_path' and assign
1633// the individual path component to the 'out_' parameters.
1634static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001635 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001636 size_t dirIndex = dex_path.rfind('/');
1637 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001638 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001639 return false;
1640 }
1641 // TODO(calin): we have similar computations in at lest 3 other places
1642 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1643 // using string append.
1644 std::string apk_dir = dex_path.substr(0, dirIndex);
1645 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1646 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1647
1648 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1649 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001650 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001651 return false;
1652 }
1653 return true;
1654}
1655
1656// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1657// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001658static bool validate_dexopt_storage_flags(int dexopt_flags,
1659 int* out_storage_flag,
1660 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001661 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1662 *out_storage_flag = FLAG_STORAGE_CE;
1663 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001664 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001665 return false;
1666 }
1667 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1668 *out_storage_flag = FLAG_STORAGE_DE;
1669 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001670 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001671 return false;
1672 }
1673 return true;
1674}
1675
Calin Juravlec9eab382017-01-25 01:17:17 -08001676// 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 -08001677// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1678// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001679// When returning true, the output parameters will be:
1680// - is_public_out: whether or not the oat file should not be made public
1681// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1682// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001683static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001684 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001685 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001686 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1687 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001688 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001689 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001690 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1691 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001692 return false;
1693 }
Calin Juravle7d765462017-09-04 15:57:10 -07001694 // Compute the oat dir as it's not easy to extract it from the child computation.
1695 char oat_path[PKG_PATH_MAX];
1696 char oat_dir[PKG_PATH_MAX];
1697 char oat_isa_dir[PKG_PATH_MAX];
1698 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001699 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1700 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001701 return false;
1702 }
Calin Juravle7d765462017-09-04 15:57:10 -07001703 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001704
Calin Juravle80a21252017-01-17 14:43:25 -08001705 pid_t pid = fork();
1706 if (pid == 0) {
1707 // child -- drop privileges before continuing.
1708 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001709
1710 // Validate the path structure.
1711 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1712 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001713 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001714 }
1715
1716 // Open the dex file.
1717 unique_fd zip_fd;
1718 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1719 if (zip_fd.get() < 0) {
1720 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001721 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001722 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001723 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001724 }
1725 }
1726
1727 // Prepare the oat directories.
1728 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001729 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001730 }
1731
1732 // Open the vdex/oat files if any.
1733 unique_fd oat_file_fd;
1734 unique_fd vdex_file_fd;
1735 if (!maybe_open_oat_and_vdex_file(dex_path,
1736 *oat_dir_out,
1737 instruction_set,
1738 true /* is_secondary_dex */,
1739 &oat_file_fd,
1740 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001741 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001742 }
1743
1744 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001745 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1746 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001747
1748 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001749 // Note that we do not do it before the fork since opening the files is required to happen
1750 // after forking.
1751 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1752 vdex_file_fd.get(),
1753 oat_file_fd.get(),
1754 zip_fd.get(),
1755 instruction_set,
1756 compiler_filter, profile_was_updated,
1757 downgrade,
1758 class_loader_context);
1759 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001760 }
1761
1762 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001763 int result = wait_child(pid);
1764 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001765 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1766 dex_path.c_str(),
1767 result);
1768 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001769 return false;
1770 }
1771 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001772 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001773 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1774 result,
1775 dexopt_needed_out,
1776 error_msg);
1777 if (!success) {
1778 LOG(ERROR) << *error_msg;
1779 }
Calin Juravle7d765462017-09-04 15:57:10 -07001780
1781 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1782
Calin Juravle80a21252017-01-17 14:43:25 -08001783 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001784 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1785 // makes the code simpler; force compilation is only needed during tests).
1786 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001787 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001788 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001789 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1790 }
1791
Calin Juravle7d765462017-09-04 15:57:10 -07001792 // Check if we should make the oat file public.
1793 // Note that if the dex file is not public the compiled code cannot be made public.
1794 // It is ok to check this flag outside in the parent process.
1795 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1796
Calin Juravle80a21252017-01-17 14:43:25 -08001797 return success;
1798}
1799
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001800static std::string format_dexopt_error(int status, const char* dex_path) {
1801 if (WIFEXITED(status)) {
1802 int int_code = WEXITSTATUS(status);
1803 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1804 if (code_name != nullptr) {
1805 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1806 }
1807 }
1808 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001809}
1810
Calin Juravlec9eab382017-01-25 01:17:17 -08001811int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001812 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001813 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001814 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001815 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001816 CHECK(pkgname != nullptr);
1817 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001818 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001819 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1820 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001821
Calin Juravled23dee72017-07-06 16:29:11 -07001822 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001823 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001824 return -1;
1825 }
1826
1827 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001828 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1829 class_loader_context);
1830 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001831 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001832 }
1833
Calin Juravleebc8a792017-04-04 20:21:05 -07001834 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001835 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1836 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1837 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001838 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001839 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001840 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001841 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001842 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001843
1844 // Check if we're dealing with a secondary dex file and if we need to compile it.
1845 std::string oat_dir_str;
1846 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001847 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001848 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001849 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001850 oat_dir = oat_dir_str.c_str();
1851 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1852 return 0; // Nothing to do, report success.
1853 }
1854 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001855 if (error_msg->empty()) { // TODO: Make this a CHECK.
1856 *error_msg = "Failed processing secondary.";
1857 }
Calin Juravle80a21252017-01-17 14:43:25 -08001858 return -1; // We had an error, logged in the process method.
1859 }
1860 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001861 // Currently these flags are only use for secondary dex files.
1862 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001863 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1864 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1865 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001866
1867 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001868 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001869 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001870 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1871 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001872 return -1;
1873 }
1874
1875 // Create the output OAT file.
1876 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001877 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001878 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001879 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001880 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001881 return -1;
1882 }
1883
1884 // Open vdex files.
1885 Dex2oatFileWrapper in_vdex_fd;
1886 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001887 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1888 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001889 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001890 return -1;
1891 }
1892
Calin Juravlecb556e32017-04-04 20:22:50 -07001893 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1894 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1895 // fully inherit their parent context).
1896 // Note that for primary apk the oat files are created before, in a separate installd
1897 // call which also does the restorecon. TODO(calin): unify the paths.
1898 if (is_secondary_dex) {
1899 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1900 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001901 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1902 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001903 return -1;
1904 }
1905 }
1906
Jeff Sharkey90aff262016-12-12 14:28:24 -07001907 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001908 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001909
Calin Juravle7a570e82017-01-14 16:23:30 -08001910 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001911 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1912 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001913
Calin Juravle7a570e82017-01-14 16:23:30 -08001914 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001915 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001916 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001917
Calin Juravle62c5a372018-02-01 17:03:23 +00001918 unique_fd dex_metadata_fd;
1919 if (dex_metadata_path != nullptr) {
1920 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1921 if (dex_metadata_fd.get() < 0) {
1922 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1923 }
1924 }
1925
Andreas Gampe023b2242018-02-28 16:03:25 -08001926 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001927
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001928 RunDex2Oat runner(input_fd.get(),
1929 out_oat_fd.get(),
1930 in_vdex_fd.get(),
1931 out_vdex_fd.get(),
1932 image_fd.get(),
1933 dex_path,
1934 out_oat_path,
1935 swap_fd.get(),
1936 instruction_set,
1937 compiler_filter,
1938 debuggable,
1939 boot_complete,
1940 background_job_compile,
1941 reference_profile_fd.get(),
1942 class_loader_context,
1943 target_sdk_version,
1944 enable_hidden_api_checks,
1945 generate_compact_dex,
1946 dex_metadata_fd.get(),
1947 compilation_reason);
1948
Jeff Sharkey90aff262016-12-12 14:28:24 -07001949 pid_t pid = fork();
1950 if (pid == 0) {
1951 /* child -- drop privileges before continuing */
1952 drop_capabilities(uid);
1953
Richard Uhler76cc0272016-12-08 10:46:35 +00001954 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001955 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001956 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001957 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001958 }
1959
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001960 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001961 } else {
1962 int res = wait_child(pid);
1963 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001964 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001965 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001966 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1967 << std::hex << std::setw(4) << res << ", process failed";
1968 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001969 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001970 }
1971 }
1972
Calin Juravlec9eab382017-01-25 01:17:17 -08001973 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001974
1975 // We've been successful, don't delete output.
1976 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001977 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001978 image_fd.SetCleanup(false);
1979 reference_profile_fd.SetCleanup(false);
1980
1981 return 0;
1982}
1983
Calin Juravlec9eab382017-01-25 01:17:17 -08001984// Try to remove the given directory. Log an error if the directory exists
1985// and is empty but could not be removed.
1986static bool rmdir_if_empty(const char* dir) {
1987 if (rmdir(dir) == 0) {
1988 return true;
1989 }
1990 if (errno == ENOENT || errno == ENOTEMPTY) {
1991 return true;
1992 }
1993 PLOG(ERROR) << "Failed to remove dir: " << dir;
1994 return false;
1995}
1996
1997// Try to unlink the given file. Log an error if the file exists and could not
1998// be unlinked.
1999static bool unlink_if_exists(const std::string& file) {
2000 if (unlink(file.c_str()) == 0) {
2001 return true;
2002 }
2003 if (errno == ENOENT) {
2004 return true;
2005
2006 }
2007 PLOG(ERROR) << "Could not unlink: " << file;
2008 return false;
2009}
2010
Calin Juravle7d765462017-09-04 15:57:10 -07002011enum ReconcileSecondaryDexResult {
2012 kReconcileSecondaryDexExists = 0,
2013 kReconcileSecondaryDexCleanedUp = 1,
2014 kReconcileSecondaryDexValidationError = 2,
2015 kReconcileSecondaryDexCleanUpError = 3,
2016 kReconcileSecondaryDexAccessIOError = 4,
2017};
Calin Juravlec9eab382017-01-25 01:17:17 -08002018
2019// Reconcile the secondary dex 'dex_path' and its generated oat files.
2020// Return true if all the parameters are valid and the secondary dex file was
2021// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2022// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2023// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2024// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2025// Return false if there were errors during processing. In this case
2026// out_secondary_dex_exists will be set to false.
2027bool reconcile_secondary_dex_file(const std::string& dex_path,
2028 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2029 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2030 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002031 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002032 if (isas.size() == 0) {
2033 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2034 return false;
2035 }
2036
Calin Juravle7d765462017-09-04 15:57:10 -07002037 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2038 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2039 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002040 return false;
2041 }
2042
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002043 // As a security measure we want to unlink art artifacts with the reduced capabilities
2044 // of the package user id. So we fork and drop capabilities in the child.
2045 pid_t pid = fork();
2046 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002047 /* child -- drop privileges before continuing */
2048 drop_capabilities(uid);
2049
2050 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2051 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2052 uid, storage_flag)) {
2053 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2054 _exit(kReconcileSecondaryDexValidationError);
2055 }
2056
2057 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2058 switch (access_check) {
2059 case kSecondaryDexAccessDoesNotExist:
2060 // File does not exist. Proceed with cleaning.
2061 break;
2062 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2063 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2064 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2065 default:
2066 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2067 _exit(kReconcileSecondaryDexValidationError);
2068 }
2069
2070 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002071 char oat_path[PKG_PATH_MAX];
2072 char oat_dir[PKG_PATH_MAX];
2073 char oat_isa_dir[PKG_PATH_MAX];
2074 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002075 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002076 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002077 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002078 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2079 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002080 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002081 }
Calin Juravle51314092017-05-18 15:33:05 -07002082
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002083 // Delete oat/vdex/art files.
2084 result = unlink_if_exists(oat_path) && result;
2085 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2086 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002087
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002088 // Delete profiles.
2089 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002090 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002091 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002092 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002093 result = unlink_if_exists(current_profile) && result;
2094 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002095
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002096 // We upgraded once the location of current profile for secondary dex files.
2097 // Check for any previous left-overs and remove them as well.
2098 std::string old_current_profile = dex_path + ".prof";
2099 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002100
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002101 // Try removing the directories as well, they might be empty.
2102 result = rmdir_if_empty(oat_isa_dir) && result;
2103 result = rmdir_if_empty(oat_dir) && result;
2104 }
Calin Juravle7d765462017-09-04 15:57:10 -07002105 if (!result) {
2106 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2107 }
2108 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002109 }
2110
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002111 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002112 if (!WIFEXITED(return_code)) {
2113 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2114 } else {
2115 return_code = WEXITSTATUS(return_code);
2116 }
2117
2118 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2119
2120 switch (return_code) {
2121 case kReconcileSecondaryDexCleanedUp:
2122 case kReconcileSecondaryDexValidationError:
2123 // If we couldn't validate assume the dex file does not exist.
2124 // This will purge the entry from the PM records.
2125 *out_secondary_dex_exists = false;
2126 return true;
2127 case kReconcileSecondaryDexExists:
2128 *out_secondary_dex_exists = true;
2129 return true;
2130 case kReconcileSecondaryDexAccessIOError:
2131 // We had an access IO error.
2132 // Return false so that we can try again.
2133 // The value of out_secondary_dex_exists does not matter in this case and by convention
2134 // is set to false.
2135 *out_secondary_dex_exists = false;
2136 return false;
2137 default:
2138 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2139 *out_secondary_dex_exists = false;
2140 return false;
2141 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002142}
2143
Alan Stokesa25d90c2017-10-16 10:56:00 +01002144// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2145// Returns true if all parameters are valid and the hash successfully computed and stored in
2146// out_secondary_dex_hash.
2147// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2148// the app.
2149// For any other errors (e.g. if any of the parameters are invalid) returns false.
2150bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2151 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2152 std::vector<uint8_t>* out_secondary_dex_hash) {
2153 out_secondary_dex_hash->clear();
2154
2155 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2156
2157 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2158 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2159 << storage_flag;
2160 return false;
2161 }
2162
2163 // Pipe to get the hash result back from our child process.
2164 unique_fd pipe_read, pipe_write;
2165 if (!Pipe(&pipe_read, &pipe_write)) {
2166 PLOG(ERROR) << "Failed to create pipe";
2167 return false;
2168 }
2169
2170 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2171 // access data the app itself can access.
2172 pid_t pid = fork();
2173 if (pid == 0) {
2174 // child -- drop privileges before continuing
2175 drop_capabilities(uid);
2176 pipe_read.reset();
2177
2178 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2179 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002180 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002181 }
2182
2183 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2184 if (fd == -1) {
2185 if (errno == EACCES || errno == ENOENT) {
2186 // Not treated as an error.
2187 _exit(0);
2188 }
2189 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002190 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002191 }
2192
2193 SHA256_CTX ctx;
2194 SHA256_Init(&ctx);
2195
2196 std::vector<uint8_t> buffer(65536);
2197 while (true) {
2198 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2199 if (bytes_read == 0) {
2200 break;
2201 } else if (bytes_read == -1) {
2202 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002203 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002204 }
2205
2206 SHA256_Update(&ctx, buffer.data(), bytes_read);
2207 }
2208
2209 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2210 SHA256_Final(hash.data(), &ctx);
2211 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002212 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002213 }
2214
2215 _exit(0);
2216 }
2217
2218 // parent
2219 pipe_write.reset();
2220
2221 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2222 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2223 out_secondary_dex_hash->clear();
2224 }
2225 return wait_child(pid) == 0;
2226}
2227
Jeff Sharkey90aff262016-12-12 14:28:24 -07002228// Helper for move_ab, so that we can have common failure-case cleanup.
2229static bool unlink_and_rename(const char* from, const char* to) {
2230 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2231 // return a failure.
2232 struct stat s;
2233 if (stat(to, &s) == 0) {
2234 if (!S_ISREG(s.st_mode)) {
2235 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2236 return false;
2237 }
2238 if (unlink(to) != 0) {
2239 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2240 return false;
2241 }
2242 } else {
2243 // This may be a permission problem. We could investigate the error code, but we'll just
2244 // let the rename failure do the work for us.
2245 }
2246
2247 // Try to rename "to" to "from."
2248 if (rename(from, to) != 0) {
2249 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2250 return false;
2251 }
2252 return true;
2253}
2254
2255// Move/rename a B artifact (from) to an A artifact (to).
2256static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2257 // Check whether B exists.
2258 {
2259 struct stat s;
2260 if (stat(b_path.c_str(), &s) != 0) {
2261 // Silently ignore for now. The service calling this isn't smart enough to understand
2262 // lack of artifacts at the moment.
2263 return false;
2264 }
2265 if (!S_ISREG(s.st_mode)) {
2266 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2267 // Try to unlink, but swallow errors.
2268 unlink(b_path.c_str());
2269 return false;
2270 }
2271 }
2272
2273 // Rename B to A.
2274 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2275 // Delete the b_path so we don't try again (or fail earlier).
2276 if (unlink(b_path.c_str()) != 0) {
2277 PLOG(ERROR) << "Could not unlink " << b_path;
2278 }
2279
2280 return false;
2281 }
2282
2283 return true;
2284}
2285
2286bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2287 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002288 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2289 if (slot_suffix.empty()) {
2290 return false;
2291 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002292
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002293 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2294 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2295 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002296 }
2297
2298 // Validate other inputs.
2299 if (validate_apk_path(apk_path) != 0) {
2300 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2301 return false;
2302 }
2303 if (validate_apk_path(oat_dir) != 0) {
2304 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2305 return false;
2306 }
2307
2308 char a_path[PKG_PATH_MAX];
2309 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2310 return false;
2311 }
2312 const std::string a_vdex_path = create_vdex_filename(a_path);
2313 const std::string a_image_path = create_image_filename(a_path);
2314
2315 // B path = A path + slot suffix.
2316 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2317 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2318 const std::string b_image_path = StringPrintf("%s.%s",
2319 a_image_path.c_str(),
2320 slot_suffix.c_str());
2321
2322 bool success = true;
2323 if (move_ab_path(b_path, a_path)) {
2324 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2325 // Note: we can live without an app image. As such, ignore failure to move the image file.
2326 // If we decide to require the app image, or the app image being moved correctly,
2327 // then change accordingly.
2328 constexpr bool kIgnoreAppImageFailure = true;
2329
2330 if (!a_image_path.empty()) {
2331 if (!move_ab_path(b_image_path, a_image_path)) {
2332 unlink(a_image_path.c_str());
2333 if (!kIgnoreAppImageFailure) {
2334 success = false;
2335 }
2336 }
2337 }
2338 } else {
2339 // Cleanup: delete B image, ignore errors.
2340 unlink(b_image_path.c_str());
2341 success = false;
2342 }
2343 } else {
2344 // Cleanup: delete B image, ignore errors.
2345 unlink(b_vdex_path.c_str());
2346 unlink(b_image_path.c_str());
2347 success = false;
2348 }
2349 return success;
2350}
2351
2352bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2353 // Delete the oat/odex file.
2354 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002355 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002356 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002357 return false;
2358 }
2359
2360 // In case of a permission failure report the issue. Otherwise just print a warning.
2361 auto unlink_and_check = [](const char* path) -> bool {
2362 int result = unlink(path);
2363 if (result != 0) {
2364 if (errno == EACCES || errno == EPERM) {
2365 PLOG(ERROR) << "Could not unlink " << path;
2366 return false;
2367 }
2368 PLOG(WARNING) << "Could not unlink " << path;
2369 }
2370 return true;
2371 };
2372
2373 // Delete the oat/odex file.
2374 bool return_value_oat = unlink_and_check(out_path);
2375
2376 // Derive and delete the app image.
2377 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2378
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002379 // Derive and delete the vdex file.
2380 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2381
Jeff Sharkey90aff262016-12-12 14:28:24 -07002382 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002383 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002384}
2385
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002386static bool is_absolute_path(const std::string& path) {
2387 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2388 LOG(ERROR) << "Invalid absolute path " << path;
2389 return false;
2390 } else {
2391 return true;
2392 }
2393}
2394
2395static bool is_valid_instruction_set(const std::string& instruction_set) {
2396 // TODO: add explicit whitelisting of instruction sets
2397 if (instruction_set.find('/') != std::string::npos) {
2398 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2399 return false;
2400 } else {
2401 return true;
2402 }
2403}
2404
2405bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2406 const char *apk_path, const char *instruction_set) {
2407 std::string oat_dir_ = oat_dir;
2408 std::string apk_path_ = apk_path;
2409 std::string instruction_set_ = instruction_set;
2410
2411 if (!is_absolute_path(oat_dir_)) return false;
2412 if (!is_absolute_path(apk_path_)) return false;
2413 if (!is_valid_instruction_set(instruction_set_)) return false;
2414
2415 std::string::size_type end = apk_path_.rfind('.');
2416 std::string::size_type start = apk_path_.rfind('/', end);
2417 if (end == std::string::npos || start == std::string::npos) {
2418 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2419 return false;
2420 }
2421
2422 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2423 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2424 const char* res = res_.c_str();
2425 if (strlen(res) >= PKG_PATH_MAX) {
2426 LOG(ERROR) << "Result too large";
2427 return false;
2428 } else {
2429 strlcpy(path, res, PKG_PATH_MAX);
2430 return true;
2431 }
2432}
2433
2434bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2435 const char *instruction_set) {
2436 std::string apk_path_ = apk_path;
2437 std::string instruction_set_ = instruction_set;
2438
2439 if (!is_absolute_path(apk_path_)) return false;
2440 if (!is_valid_instruction_set(instruction_set_)) return false;
2441
2442 std::string::size_type end = apk_path_.rfind('.');
2443 std::string::size_type start = apk_path_.rfind('/', end);
2444 if (end == std::string::npos || start == std::string::npos) {
2445 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2446 return false;
2447 }
2448
2449 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2450 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2451}
2452
2453bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2454 const char *instruction_set) {
2455 std::string src_ = src;
2456 std::string instruction_set_ = instruction_set;
2457
2458 if (!is_absolute_path(src_)) return false;
2459 if (!is_valid_instruction_set(instruction_set_)) return false;
2460
2461 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2462 if (*it == '/') {
2463 *it = '@';
2464 }
2465 }
2466
2467 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2468 + DALVIK_CACHE_POSTFIX;
2469 const char* res = res_.c_str();
2470 if (strlen(res) >= PKG_PATH_MAX) {
2471 LOG(ERROR) << "Result too large";
2472 return false;
2473 } else {
2474 strlcpy(path, res, PKG_PATH_MAX);
2475 return true;
2476 }
2477}
2478
Calin Juravle59f7ab82018-04-27 17:50:23 -07002479bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2480 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002481 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2482 for (const std::string& elem : classpaths_elems) {
2483 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2484 if (fd < 0) {
2485 PLOG(ERROR) << "Could not open classpath elem " << elem;
2486 return false;
2487 } else {
2488 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002489 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002490 }
2491 }
2492 return true;
2493}
2494
2495static bool create_app_profile_snapshot(int32_t app_id,
2496 const std::string& package_name,
2497 const std::string& profile_name,
2498 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002499 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2500
Calin Juravle824a64d2018-01-18 20:23:17 -08002501 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002502 if (snapshot_fd < 0) {
2503 return false;
2504 }
2505
2506 std::vector<unique_fd> profiles_fd;
2507 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002508 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2509 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002510 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2511 return false;
2512 }
2513
2514 profiles_fd.push_back(std::move(reference_profile_fd));
2515
Calin Juravle0d0a4922018-01-23 19:54:11 -08002516 // Open the class paths elements. These will be used to filter out profile data that does
2517 // not belong to the classpath during merge.
2518 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002519 std::vector<std::string> dex_locations;
2520 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002521 return false;
2522 }
2523
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002524 RunProfman args;
2525 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002526 pid_t pid = fork();
2527 if (pid == 0) {
2528 /* child -- drop privileges before continuing */
2529 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002530 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002531 }
2532
2533 /* parent */
2534 int return_code = wait_child(pid);
2535 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002536 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002537 return false;
2538 }
2539
2540 return true;
2541}
2542
Calin Juravle0d0a4922018-01-23 19:54:11 -08002543static bool create_boot_image_profile_snapshot(const std::string& package_name,
2544 const std::string& profile_name,
2545 const std::string& classpath) {
2546 // The reference profile directory for the android package might not be prepared. Do it now.
2547 const std::string ref_profile_dir =
2548 create_primary_reference_profile_package_dir_path(package_name);
2549 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2550 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2551 return false;
2552 }
2553
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002554 // Return false for empty class path since it may otherwise return true below if profiles is
2555 // empty.
2556 if (classpath.empty()) {
2557 PLOG(ERROR) << "Class path is empty";
2558 return false;
2559 }
2560
Calin Juravle0d0a4922018-01-23 19:54:11 -08002561 // Open and create the snapshot profile.
2562 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2563
2564 // Collect all non empty profiles.
2565 // The collection will traverse all applications profiles and find the non empty files.
2566 // This has the potential of inspecting a large number of files and directories (depending
2567 // on the number of applications and users). So there is a slight increase in the chance
2568 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2569 // fail the snapshot and aggregate whatever profile we could open.
2570 //
2571 // The profile snapshot is a best effort based on available data it's ok if some data
2572 // from some apps is missing. It will be counter productive for the snapshot to fail
2573 // because we could not open or read some of the files.
2574 std::vector<std::string> profiles;
2575 if (!collect_profiles(&profiles)) {
2576 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2577 }
2578
2579 // If we have no profiles return early.
2580 if (profiles.empty()) {
2581 return true;
2582 }
2583
2584 // Open the classpath elements. These will be used to filter out profile data that does
2585 // not belong to the classpath during merge.
2586 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002587 std::vector<std::string> dex_locations;
2588 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002589 return false;
2590 }
2591
2592 // If we could not open any files from the classpath return an error.
2593 if (apk_fds.empty()) {
2594 LOG(ERROR) << "Could not open any of the classpath elements.";
2595 return false;
2596 }
2597
2598 // Aggregate the profiles in batches of kAggregationBatchSize.
2599 // We do this to avoid opening a huge a amount of files.
2600 static constexpr size_t kAggregationBatchSize = 10;
2601
2602 std::vector<unique_fd> profiles_fd;
2603 for (size_t i = 0; i < profiles.size(); ) {
2604 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2605 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2606 if (fd.get() >= 0) {
2607 profiles_fd.push_back(std::move(fd));
2608 }
2609 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002610 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002611 args.SetupMerge(profiles_fd,
2612 snapshot_fd,
2613 apk_fds,
2614 dex_locations,
2615 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002616 pid_t pid = fork();
2617 if (pid == 0) {
2618 /* child -- drop privileges before continuing */
2619 drop_capabilities(AID_SYSTEM);
2620
Calin Juravle59f7ab82018-04-27 17:50:23 -07002621 // The introduction of new access flags into boot jars causes them to
2622 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002623 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002624 }
2625
2626 /* parent */
2627 int return_code = wait_child(pid);
2628 if (!WIFEXITED(return_code)) {
2629 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2630 return false;
2631 }
2632 return true;
2633 }
2634 return true;
2635}
2636
2637bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2638 const std::string& profile_name, const std::string& classpath) {
2639 if (app_id == -1) {
2640 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2641 } else {
2642 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2643 }
2644}
2645
Calin Juravlec3b049e2018-01-18 22:32:58 -08002646bool prepare_app_profile(const std::string& package_name,
2647 userid_t user_id,
2648 appid_t app_id,
2649 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002650 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002651 const std::unique_ptr<std::string>& dex_metadata) {
2652 // Prepare the current profile.
2653 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2654 /*is_secondary_dex*/ false);
2655 uid_t uid = multiuser_get_uid(user_id, app_id);
2656 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2657 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2658 return false;
2659 }
2660
2661 // Check if we need to install the profile from the dex metadata.
2662 if (dex_metadata == nullptr) {
2663 return true;
2664 }
2665
2666 // We have a dex metdata. Merge the profile into the reference profile.
2667 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2668 /*read_write*/ true, /*is_secondary_dex*/ false);
2669 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2670 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002671 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2672 if (apk_fd < 0) {
2673 PLOG(ERROR) << "Could not open code path " << code_path;
2674 return false;
2675 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002676
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002677 RunProfman args;
2678 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2679 std::move(ref_profile_fd),
2680 std::move(apk_fd),
2681 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002682 pid_t pid = fork();
2683 if (pid == 0) {
2684 /* child -- drop privileges before continuing */
2685 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2686 drop_capabilities(app_shared_gid);
2687
Calin Juravlef63d4792018-01-30 17:43:34 +00002688 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002689 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002690 }
2691
2692 /* parent */
2693 int return_code = wait_child(pid);
2694 if (!WIFEXITED(return_code)) {
2695 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2696 return false;
2697 }
2698 return true;
2699}
2700
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002701} // namespace installd
2702} // namespace android