blob: 8136535ce50009481d8b85741e21d39d23922e31 [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
629static void drop_capabilities(uid_t uid) {
630 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800631 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
632 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 }
634 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800635 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
636 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700637 }
638 // drop capabilities
639 struct __user_cap_header_struct capheader;
640 struct __user_cap_data_struct capdata[2];
641 memset(&capheader, 0, sizeof(capheader));
642 memset(&capdata, 0, sizeof(capdata));
643 capheader.version = _LINUX_CAPABILITY_VERSION_3;
644 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800645 PLOG(ERROR) << "capset failed";
646 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700647 }
648}
649
650static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
651static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
652static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
653static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
654static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
655
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800656class RunProfman : public ExecVHelper {
657 public:
658 void SetupArgs(const std::vector<unique_fd>& profile_fds,
659 const unique_fd& reference_profile_fd,
660 const std::vector<unique_fd>& apk_fds,
661 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800662 bool copy_and_update,
663 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000664 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700665
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800666 if (copy_and_update) {
667 CHECK_EQ(1u, profile_fds.size());
668 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000669 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800670 if (reference_profile_fd != -1) {
671 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000672 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800673
674 for (const unique_fd& fd : profile_fds) {
675 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
676 }
677
678 for (const unique_fd& fd : apk_fds) {
679 AddArg("--apk-fd=" + std::to_string(fd.get()));
680 }
681
682 for (const std::string& dex_location : dex_locations) {
683 AddArg("--dex-location=" + dex_location);
684 }
685
686 if (copy_and_update) {
687 AddArg("--copy-and-update-profile-key");
688 }
689
Calin Juravleb3a929d2018-12-11 14:40:00 -0800690 if (store_aggregation_counters) {
691 AddArg("--store-aggregation-counters");
692 }
693
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800694 // Do not add after dex2oat_flags, they should override others for debugging.
695 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800696 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700697
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800698 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
699 const unique_fd& reference_profile_fd,
700 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800701 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
702 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800703 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800704 reference_profile_fd,
705 apk_fds,
706 dex_locations,
707 /*copy_and_update=*/false,
708 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800709 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700710
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800711 void SetupCopyAndUpdate(unique_fd&& profile_fd,
712 unique_fd&& reference_profile_fd,
713 unique_fd&& apk_fd,
714 const std::string& dex_location) {
715 // The fds need to stay open longer than the scope of the function, so put them into a local
716 // variable vector.
717 profiles_fd_.push_back(std::move(profile_fd));
718 apk_fds_.push_back(std::move(apk_fd));
719 reference_profile_fd_ = std::move(reference_profile_fd);
720 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800721 SetupArgs(profiles_fd_,
722 reference_profile_fd_,
723 apk_fds_,
724 dex_locations,
725 /*copy_and_update=*/true,
726 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800727 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000728
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800729 void SetupDump(const std::vector<unique_fd>& profiles_fd,
730 const unique_fd& reference_profile_fd,
731 const std::vector<std::string>& dex_locations,
732 const std::vector<unique_fd>& apk_fds,
733 const unique_fd& output_fd) {
734 AddArg("--dump-only");
735 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800736 SetupArgs(profiles_fd,
737 reference_profile_fd,
738 apk_fds,
739 dex_locations,
740 /*copy_and_update=*/false,
741 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800742 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000743
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800744 void Exec() {
745 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
746 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000747
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800748 private:
749 unique_fd reference_profile_fd_;
750 std::vector<unique_fd> profiles_fd_;
751 std::vector<unique_fd> apk_fds_;
752};
Mathieu Chartier31636522018-11-09 23:53:07 +0000753
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800754
Calin Juravlef63d4792018-01-30 17:43:34 +0000755
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800757// The location is the package name for primary apks or the dex path for secondary dex files.
758// Returns true if there is enough information in the current profiles that makes it
759// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700760// If the return value is true all the current profiles would have been merged into
761// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800762static bool analyze_profiles(uid_t uid, const std::string& package_name,
763 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800764 std::vector<unique_fd> profiles_fd;
765 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800766 open_profile_files(uid, package_name, location, is_secondary_dex,
767 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800768 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 // Skip profile guided compilation because no profiles were found.
770 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700771 return false;
772 }
773
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800774 RunProfman profman_merge;
775 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700776 pid_t pid = fork();
777 if (pid == 0) {
778 /* child -- drop privileges before continuing */
779 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800780 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700781 }
782 /* parent */
783 int return_code = wait_child(pid);
784 bool need_to_compile = false;
785 bool should_clear_current_profiles = false;
786 bool should_clear_reference_profile = false;
787 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800788 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789 } else {
790 return_code = WEXITSTATUS(return_code);
791 switch (return_code) {
792 case PROFMAN_BIN_RETURN_CODE_COMPILE:
793 need_to_compile = true;
794 should_clear_current_profiles = true;
795 should_clear_reference_profile = false;
796 break;
797 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
798 need_to_compile = false;
799 should_clear_current_profiles = false;
800 should_clear_reference_profile = false;
801 break;
802 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800803 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700804 need_to_compile = false;
805 should_clear_current_profiles = true;
806 should_clear_reference_profile = true;
807 break;
808 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
809 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
810 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800811 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700812 need_to_compile = false;
813 should_clear_current_profiles = false;
814 should_clear_reference_profile = false;
815 break;
816 default:
817 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800818 LOG(WARNING) << "Unknown error code while processing profiles for location "
819 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700820 need_to_compile = false;
821 should_clear_current_profiles = true;
822 should_clear_reference_profile = true;
823 break;
824 }
825 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800826
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800828 if (is_secondary_dex) {
829 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800830 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
831 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800832 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800833 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800834 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700835 }
836 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800837 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700838 }
839 return need_to_compile;
840}
841
Calin Juravle114f0812017-03-08 19:05:07 -0800842// Decides if profile guided compilation is needed or not based on existing profiles.
843// The analysis is done for the primary apks of the given package.
844// Returns true if there is enough information in the current profiles that makes it
845// worth to recompile the package.
846// If the return value is true all the current profiles would have been merged into
847// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800848bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
849 const std::string& profile_name) {
850 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800851}
852
Calin Juravle408cd4a2018-01-20 23:34:18 -0800853bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
854 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800855 std::vector<unique_fd> profile_fds;
856 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800857 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
858 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700859
Calin Juravle408cd4a2018-01-20 23:34:18 -0800860 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800861 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800863 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700864 const bool has_profiles = !profile_fds.empty();
865
866 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800867 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700868 return false;
869 }
870
Calin Juravle114f0812017-03-08 19:05:07 -0800871 unique_fd output_fd(open(out_file_name.c_str(),
872 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800874 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700875 return false;
876 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800877
Jeff Sharkey90aff262016-12-12 14:28:24 -0700878 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800879 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800880 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
881 if (apk_fd == -1) {
882 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
883 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800885 dex_locations.push_back(get_location_from_path(code_path.c_str()));
886 apk_fds.push_back(std::move(apk_fd));
887
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800889 RunProfman profman_dump;
890 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700891 pid_t pid = fork();
892 if (pid == 0) {
893 /* child -- drop privileges before continuing */
894 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800895 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 }
897 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700898 int return_code = wait_child(pid);
899 if (!WIFEXITED(return_code)) {
900 LOG(WARNING) << "profman failed for package " << pkgname << ": "
901 << return_code;
902 return false;
903 }
904 return true;
905}
906
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700907bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800908 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700909 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
910 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800911 package_name,
912 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700913 /*read_write*/ true,
914 /*secondary*/ false));
915 if (in_fd.get() < 0) {
916 PLOG(WARNING) << "Could not open profile " << system_profile;
917 return false;
918 }
919 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800920 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700921 return false;
922 }
923
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700924 // As a security measure we want to write the profile information with the reduced capabilities
925 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700926 pid_t pid = fork();
927 if (pid == 0) {
928 /* child -- drop privileges before continuing */
929 drop_capabilities(packageUid);
930
931 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
932 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800933 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700934 }
935 // This implies that the app owning this profile is running
936 // (and has acquired the lock).
937 //
938 // The app never acquires the lock for the reference profiles of primary apks.
939 // Only dex2oat from installd will do that. Since installd is single threaded
940 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800941 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700942 return false;
943 }
944
945 bool truncated = ftruncate(out_fd.get(), 0) == 0;
946 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800947 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700948 }
949
950 // Copy over data.
951 static constexpr size_t kBufferSize = 4 * 1024;
952 char buffer[kBufferSize];
953 while (true) {
954 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
955 if (bytes == 0) {
956 break;
957 }
958 write(out_fd.get(), buffer, bytes);
959 }
960 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800961 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700962 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700963 // Use _exit since we don't want to run the global destructors in the child.
964 // b/62597429
965 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700966 }
967 /* parent */
968 int return_code = wait_child(pid);
969 return return_code == 0;
970}
971
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
973 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
974 if (EndsWith(oat_path, ".dex")) {
975 std::string new_path = oat_path;
976 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800977 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700978 return new_path;
979 }
980
981 // An odex entry. Not that this may not be an extension, e.g., in the OTA
982 // case (where the base name will have an extension for the B artifact).
983 size_t odex_pos = oat_path.rfind(".odex");
984 if (odex_pos != std::string::npos) {
985 std::string new_path = oat_path;
986 new_path.replace(odex_pos, strlen(".odex"), new_ext);
987 CHECK_NE(new_path.find(new_ext), std::string::npos);
988 return new_path;
989 }
990
991 // Don't know how to handle this.
992 return "";
993}
994
995// Translate the given oat path to an art (app image) path. An empty string
996// denotes an error.
997static std::string create_image_filename(const std::string& oat_path) {
998 return replace_file_extension(oat_path, ".art");
999}
1000
1001// Translate the given oat path to a vdex path. An empty string denotes an error.
1002static std::string create_vdex_filename(const std::string& oat_path) {
1003 return replace_file_extension(oat_path, ".vdex");
1004}
1005
Jeff Sharkey90aff262016-12-12 14:28:24 -07001006static int open_output_file(const char* file_name, bool recreate, int permissions) {
1007 int flags = O_RDWR | O_CREAT;
1008 if (recreate) {
1009 if (unlink(file_name) < 0) {
1010 if (errno != ENOENT) {
1011 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1012 }
1013 }
1014 flags |= O_EXCL;
1015 }
1016 return open(file_name, flags, permissions);
1017}
1018
Calin Juravle2289c0a2017-02-15 12:44:14 -08001019static bool set_permissions_and_ownership(
1020 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1021 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1022 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001023 if (fchmod(fd,
1024 S_IRUSR|S_IWUSR|S_IRGRP |
1025 (is_public ? S_IROTH : 0)) < 0) {
1026 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1027 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001028 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001029 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1030 return false;
1031 }
1032 return true;
1033}
1034
1035static bool IsOutputDalvikCache(const char* oat_dir) {
1036 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1037 // into '!'. Play it safe by handling it both.
1038 // TODO: ensure we never get null.
1039 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1040 return oat_dir == nullptr || oat_dir[0] == '!';
1041}
1042
Calin Juravled23dee72017-07-06 16:29:11 -07001043// Best-effort check whether we can fit the the path into our buffers.
1044// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1045// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1046// extension to the cache path (5 bytes).
1047// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1048static bool validate_dex_path_size(const std::string& dex_path) {
1049 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1050 LOG(ERROR) << "dex_path too long: " << dex_path;
1051 return false;
1052 }
1053 return true;
1054}
1055
Jeff Sharkey90aff262016-12-12 14:28:24 -07001056static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001057 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001058 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001059 return false;
1060 }
1061
1062 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001063 // Oat dirs for secondary dex files are already validated.
1064 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001065 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1066 return false;
1067 }
1068 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1069 return false;
1070 }
1071 } else {
1072 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1073 return false;
1074 }
1075 }
1076 return true;
1077}
1078
1079// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1080// on destruction. It will also run the given cleanup (unless told not to) after closing.
1081//
1082// Usage example:
1083//
Calin Juravle7a570e82017-01-14 16:23:30 -08001084// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085// [name]() {
1086// unlink(name.c_str());
1087// });
1088// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1089// wrapper if captured as a reference.
1090//
1091// if (file.get() == -1) {
1092// // Error opening...
1093// }
1094//
1095// ...
1096// if (error) {
1097// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1098// // and delete the file (after the fd is closed).
1099// return -1;
1100// }
1101//
1102// (Success case)
1103// file.SetCleanup(false);
1104// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1105// // (leaving the file around; after the fd is closed).
1106//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001107class Dex2oatFileWrapper {
1108 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001109 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001110 }
1111
Calin Juravle7a570e82017-01-14 16:23:30 -08001112 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1113 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1114
1115 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1116 value_ = other.value_;
1117 cleanup_ = other.cleanup_;
1118 do_cleanup_ = other.do_cleanup_;
1119 auto_close_ = other.auto_close_;
1120 other.release();
1121 }
1122
1123 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1124 value_ = other.value_;
1125 cleanup_ = other.cleanup_;
1126 do_cleanup_ = other.do_cleanup_;
1127 auto_close_ = other.auto_close_;
1128 other.release();
1129 return *this;
1130 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131
1132 ~Dex2oatFileWrapper() {
1133 reset(-1);
1134 }
1135
1136 int get() {
1137 return value_;
1138 }
1139
1140 void SetCleanup(bool cleanup) {
1141 do_cleanup_ = cleanup;
1142 }
1143
1144 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001145 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146 close(value_);
1147 }
1148 if (do_cleanup_ && cleanup_ != nullptr) {
1149 cleanup_();
1150 }
1151
1152 value_ = new_value;
1153 }
1154
Calin Juravle7a570e82017-01-14 16:23:30 -08001155 void reset(int new_value, std::function<void ()> new_cleanup) {
1156 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 close(value_);
1158 }
1159 if (do_cleanup_ && cleanup_ != nullptr) {
1160 cleanup_();
1161 }
1162
1163 value_ = new_value;
1164 cleanup_ = new_cleanup;
1165 }
1166
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 void DisableAutoClose() {
1168 auto_close_ = false;
1169 }
1170
Jeff Sharkey90aff262016-12-12 14:28:24 -07001171 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001172 void release() {
1173 value_ = -1;
1174 do_cleanup_ = false;
1175 cleanup_ = nullptr;
1176 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001179 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001180 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001181};
1182
Calin Juravle7a570e82017-01-14 16:23:30 -08001183// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001184Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1185 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001186
1187 // We don't create an image for secondary dex files.
1188 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001189 return Dex2oatFileWrapper();
1190 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001191
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 const std::string image_path = create_image_filename(out_oat_path);
1193 if (image_path.empty()) {
1194 // Happens when the out_oat_path has an unknown extension.
1195 return Dex2oatFileWrapper();
1196 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001197
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001198 // In case there is a stale image, remove it now. Ignore any error.
1199 unlink(image_path.c_str());
1200
1201 // Not enabled, exit.
1202 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001203 return Dex2oatFileWrapper();
1204 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001205 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1206 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 return Dex2oatFileWrapper();
1208 }
1209 // Recreate is true since we do not want to modify a mapped image. If the app is
1210 // already running and we modify the image file, it can cause crashes (b/27493510).
1211 Dex2oatFileWrapper wrapper_fd(
1212 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1213 [image_path]() { unlink(image_path.c_str()); });
1214 if (wrapper_fd.get() < 0) {
1215 // Could not create application image file. Go on since we can compile without it.
1216 LOG(ERROR) << "installd could not create '" << image_path
1217 << "' for image file during dexopt";
1218 // If we have a valid image file path but no image fd, explicitly erase the image file.
1219 if (unlink(image_path.c_str()) < 0) {
1220 if (errno != ENOENT) {
1221 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1222 }
1223 }
1224 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001225 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001226 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1227 wrapper_fd.reset(-1);
1228 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001229
Calin Juravle7a570e82017-01-14 16:23:30 -08001230 return wrapper_fd;
1231}
1232
1233// Creates the dexopt swap file if necessary and return its fd.
1234// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001235unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001237 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001238 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001239 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001240 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001241 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001242 if (swap_fd.get() < 0) {
1243 // Could not create swap file. Optimistically go on and hope that we can compile
1244 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001245 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001246 } else {
1247 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001248 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1250 }
1251 }
1252 return swap_fd;
1253}
1254
1255// Opens the reference profiles if needed.
1256// 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 -08001257Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001258 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001259 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001260 // If we are not profile guided compilation, or we are compiling system server
1261 // do not bother to open the profiles; we won't be using them.
1262 if (!profile_guided || (pkgname[0] == '*')) {
1263 return Dex2oatFileWrapper();
1264 }
1265
1266 // If this is a secondary dex path which is public do not open the profile.
1267 // We cannot compile public secondary dex paths with profiles. That's because
1268 // it will expose how the dex files are used by their owner.
1269 //
1270 // Note that the PackageManager is responsible to set the is_public flag for
1271 // primary apks and we do not check it here. In some cases, e.g. when
1272 // compiling with a public profile from the .dm file the PackageManager will
1273 // set is_public toghether with the profile guided compilation.
1274 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001275 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001276 }
Calin Juravle114f0812017-03-08 19:05:07 -08001277
1278 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001279 std::string location;
1280 if (is_secondary_dex) {
1281 location = dex_path;
1282 } else {
1283 if (profile_name == nullptr) {
1284 // This path is taken for system server re-compilation lunched from ZygoteInit.
1285 return Dex2oatFileWrapper();
1286 } else {
1287 location = profile_name;
1288 }
1289 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001290 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1291 is_secondary_dex);
1292 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1293 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001294 };
1295 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001296}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001297
Calin Juravle7a570e82017-01-14 16:23:30 -08001298// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1299// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001300bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001301 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001302 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001303 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1304 CHECK(in_vdex_wrapper_fd != nullptr);
1305 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001306 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1307 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001308 char in_odex_path[PKG_PATH_MAX];
1309 int dexopt_action = abs(dexopt_needed);
1310 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001311 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001312
1313 // Infer the name of the output VDEX.
1314 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1315 if (out_vdex_path_str.empty()) {
1316 return false;
1317 }
1318
1319 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001320 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001321 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1322 const char* path = nullptr;
1323 if (is_odex_location) {
1324 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1325 path = in_odex_path;
1326 } else {
1327 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001328 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001329 }
1330 } else {
1331 path = out_oat_path;
1332 }
1333 in_vdex_path_str = create_vdex_filename(path);
1334 if (in_vdex_path_str.empty()) {
1335 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001336 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001337 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001338 // We can update in place when all these conditions are met:
1339 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1340 // on /system typically cannot be updated in place).
1341 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1342 // cannot be currently used by a running process.
1343 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1344 // different vdex files to operate.
1345 update_vdex_in_place =
1346 (in_vdex_path_str == out_vdex_path_str) &&
1347 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1348 !profile_guided;
1349 if (update_vdex_in_place) {
1350 // Open the file read-write to be able to update it.
1351 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1352 if (in_vdex_wrapper_fd->get() == -1) {
1353 // If we failed to open the file, we cannot update it in place.
1354 update_vdex_in_place = false;
1355 }
1356 } else {
1357 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1358 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001359 }
1360
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001361 // If we are updating the vdex in place, we do not need to recreate a vdex,
1362 // and can use the same existing one.
1363 if (update_vdex_in_place) {
1364 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1365 // have bogus stale vdex files.
1366 out_vdex_wrapper_fd->reset(
1367 in_vdex_wrapper_fd->get(),
1368 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1369 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1370 // wrapper).
1371 in_vdex_wrapper_fd->DisableAutoClose();
1372 } else {
1373 out_vdex_wrapper_fd->reset(
1374 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1375 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1376 if (out_vdex_wrapper_fd->get() < 0) {
1377 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1378 return false;
1379 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001380 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001381 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001382 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001383 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1384 return false;
1385 }
1386
1387 // If we got here we successfully opened the vdex files.
1388 return true;
1389}
1390
1391// Opens the output oat file for the given apk.
1392// If successful it stores the output path into out_oat_path and returns true.
1393Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001394 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1395 char* out_oat_path) {
1396 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001397 return Dex2oatFileWrapper();
1398 }
1399 const std::string out_oat_path_str(out_oat_path);
1400 Dex2oatFileWrapper wrapper_fd(
1401 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1402 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1403 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001404 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001405 } else if (!set_permissions_and_ownership(
1406 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001407 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1408 wrapper_fd.reset(-1);
1409 }
1410 return wrapper_fd;
1411}
1412
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001413// Creates RDONLY fds for oat and vdex files, if exist.
1414// Returns false if it fails to create oat out path for the given apk path.
1415// Note that the method returns true even if the files could not be opened.
1416bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1417 const std::string& oat_dir,
1418 const std::string& instruction_set,
1419 bool is_secondary_dex,
1420 unique_fd* oat_file_fd,
1421 unique_fd* vdex_file_fd) {
1422 char oat_path[PKG_PATH_MAX];
1423 if (!create_oat_out_path(apk_path.c_str(),
1424 instruction_set.c_str(),
1425 oat_dir.c_str(),
1426 is_secondary_dex,
1427 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001428 LOG(ERROR) << "Could not create oat out path for "
1429 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001430 return false;
1431 }
1432 oat_file_fd->reset(open(oat_path, O_RDONLY));
1433 if (oat_file_fd->get() < 0) {
1434 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1435 }
1436
1437 std::string vdex_filename = create_vdex_filename(oat_path);
1438 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1439 if (vdex_file_fd->get() < 0) {
1440 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1441 }
1442
1443 return true;
1444}
1445
Calin Juravle7a570e82017-01-14 16:23:30 -08001446// Updates the access times of out_oat_path based on those from apk_path.
1447void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1448 struct stat input_stat;
1449 memset(&input_stat, 0, sizeof(input_stat));
1450 if (stat(apk_path, &input_stat) != 0) {
1451 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1452 return;
1453 }
1454
1455 struct utimbuf ut;
1456 ut.actime = input_stat.st_atime;
1457 ut.modtime = input_stat.st_mtime;
1458 if (utime(out_oat_path, &ut) != 0) {
1459 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1460 }
1461}
1462
Calin Juravle80a21252017-01-17 14:43:25 -08001463// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001464// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1465// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1466// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001467class RunDexoptAnalyzer : public ExecVHelper {
1468 public:
1469 RunDexoptAnalyzer(const std::string& dex_file,
1470 int vdex_fd,
1471 int oat_fd,
1472 int zip_fd,
1473 const std::string& instruction_set,
1474 const std::string& compiler_filter,
1475 bool profile_was_updated,
1476 bool downgrade,
1477 const char* class_loader_context) {
1478 CHECK_GE(zip_fd, 0);
1479 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001480 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001481
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001482 std::string dex_file_arg = "--dex-file=" + dex_file;
1483 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1484 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1485 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1486 std::string isa_arg = "--isa=" + instruction_set;
1487 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1488 const char* assume_profile_changed = "--assume-profile-changed";
1489 const char* downgrade_flag = "--downgrade";
1490 std::string class_loader_context_arg = "--class-loader-context=";
1491 if (class_loader_context != nullptr) {
1492 class_loader_context_arg += class_loader_context;
1493 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001494
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001495 // program name, dex file, isa, filter
1496 AddArg(dex_file_arg);
1497 AddArg(isa_arg);
1498 AddArg(compiler_filter_arg);
1499 if (oat_fd >= 0) {
1500 AddArg(oat_fd_arg);
1501 }
1502 if (vdex_fd >= 0) {
1503 AddArg(vdex_fd_arg);
1504 }
1505 AddArg(zip_fd_arg.c_str());
1506 if (profile_was_updated) {
1507 AddArg(assume_profile_changed);
1508 }
1509 if (downgrade) {
1510 AddArg(downgrade_flag);
1511 }
1512 if (class_loader_context != nullptr) {
1513 AddArg(class_loader_context_arg.c_str());
1514 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001515
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001516 PrepareArgs(dexoptanalyzer_bin);
1517 }
1518};
Calin Juravle80a21252017-01-17 14:43:25 -08001519
1520// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001521static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001522 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001523 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001524 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001525 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001526 return false;
1527 }
Calin Juravle114f0812017-03-08 19:05:07 -08001528 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001529
Calin Juravle80a21252017-01-17 14:43:25 -08001530 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001531 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1532 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001533 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001534 return false;
1535 }
1536
1537 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001538 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001539
Calin Juravle7d765462017-09-04 15:57:10 -07001540 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001541 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001542 return false;
1543 }
1544
1545 return true;
1546}
1547
Calin Juravle7d765462017-09-04 15:57:10 -07001548// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1549// secondary dex files. This return codes are returned by the child process created for
1550// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001551
Andreas Gampe194fe422018-02-28 20:16:19 -08001552enum DexoptAnalyzerSkipCodes {
1553 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001554 // Specific errors are encoded in the name.
1555 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1556 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1557 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1558 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1559 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001560 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001561 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001562};
Calin Juravle7d765462017-09-04 15:57:10 -07001563
1564// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001565// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1566// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001567// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1568// of dexoptanalyzer.
1569static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001570 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001571 // The result values are defined in dexoptanalyzer.
1572 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001573 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001574 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001575 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001576 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001577 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001578 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001579 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001580 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001581 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1582 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001583 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1584 " Expected odex file status for secondary dex %s"
1585 " : dexoptanalyzer result=%d",
1586 dex_path.c_str(),
1587 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001588 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001589 }
1590
1591 // Use a second switch for enum switch-case analysis.
1592 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001593 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001594 // If the file does not exist there's no need for dexopt.
1595 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1596 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001597
1598 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1599 *error_msg = "Dexoptanalyzer path validation failed";
1600 return false;
1601 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1602 *error_msg = "Dexoptanalyzer open zip failed";
1603 return false;
1604 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1605 *error_msg = "Dexoptanalyzer dir preparation failed";
1606 return false;
1607 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1608 *error_msg = "Dexoptanalyzer open output failed";
1609 return false;
1610 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1611 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001612 return false;
1613 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001614
1615 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1616 dex_path.c_str(),
1617 result);
1618 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001619}
1620
Calin Juravle7d765462017-09-04 15:57:10 -07001621enum SecondaryDexAccess {
1622 kSecondaryDexAccessReadOk = 0,
1623 kSecondaryDexAccessDoesNotExist = 1,
1624 kSecondaryDexAccessPermissionError = 2,
1625 kSecondaryDexAccessIOError = 3
1626};
1627
1628static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1629 // Check if the path exists and can be read. If not, there's nothing to do.
1630 if (access(dex_path.c_str(), R_OK) == 0) {
1631 return kSecondaryDexAccessReadOk;
1632 } else {
1633 if (errno == ENOENT) {
1634 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1635 return kSecondaryDexAccessDoesNotExist;
1636 } else {
1637 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1638 return errno == EACCES
1639 ? kSecondaryDexAccessPermissionError
1640 : kSecondaryDexAccessIOError;
1641 }
1642 }
1643}
1644
1645static bool is_file_public(const std::string& filename) {
1646 struct stat file_stat;
1647 if (stat(filename.c_str(), &file_stat) == 0) {
1648 return (file_stat.st_mode & S_IROTH) != 0;
1649 }
1650 return false;
1651}
1652
1653// Create the oat file structure for the secondary dex 'dex_path' and assign
1654// the individual path component to the 'out_' parameters.
1655static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001656 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001657 size_t dirIndex = dex_path.rfind('/');
1658 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001659 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001660 return false;
1661 }
1662 // TODO(calin): we have similar computations in at lest 3 other places
1663 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1664 // using string append.
1665 std::string apk_dir = dex_path.substr(0, dirIndex);
1666 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1667 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1668
1669 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1670 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001671 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001672 return false;
1673 }
1674 return true;
1675}
1676
1677// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1678// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001679static bool validate_dexopt_storage_flags(int dexopt_flags,
1680 int* out_storage_flag,
1681 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001682 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1683 *out_storage_flag = FLAG_STORAGE_CE;
1684 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001685 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001686 return false;
1687 }
1688 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1689 *out_storage_flag = FLAG_STORAGE_DE;
1690 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001691 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001692 return false;
1693 }
1694 return true;
1695}
1696
Calin Juravlec9eab382017-01-25 01:17:17 -08001697// 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 -08001698// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1699// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001700// When returning true, the output parameters will be:
1701// - is_public_out: whether or not the oat file should not be made public
1702// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1703// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001704static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001705 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001706 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001707 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1708 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001709 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001710 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001711 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1712 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001713 return false;
1714 }
Calin Juravle7d765462017-09-04 15:57:10 -07001715 // Compute the oat dir as it's not easy to extract it from the child computation.
1716 char oat_path[PKG_PATH_MAX];
1717 char oat_dir[PKG_PATH_MAX];
1718 char oat_isa_dir[PKG_PATH_MAX];
1719 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001720 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1721 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001722 return false;
1723 }
Calin Juravle7d765462017-09-04 15:57:10 -07001724 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001725
Calin Juravle80a21252017-01-17 14:43:25 -08001726 pid_t pid = fork();
1727 if (pid == 0) {
1728 // child -- drop privileges before continuing.
1729 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001730
1731 // Validate the path structure.
1732 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1733 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001734 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001735 }
1736
1737 // Open the dex file.
1738 unique_fd zip_fd;
1739 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1740 if (zip_fd.get() < 0) {
1741 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001742 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001743 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001744 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001745 }
1746 }
1747
1748 // Prepare the oat directories.
1749 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001750 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001751 }
1752
1753 // Open the vdex/oat files if any.
1754 unique_fd oat_file_fd;
1755 unique_fd vdex_file_fd;
1756 if (!maybe_open_oat_and_vdex_file(dex_path,
1757 *oat_dir_out,
1758 instruction_set,
1759 true /* is_secondary_dex */,
1760 &oat_file_fd,
1761 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001762 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001763 }
1764
1765 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001766 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1767 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001768
1769 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001770 // Note that we do not do it before the fork since opening the files is required to happen
1771 // after forking.
1772 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1773 vdex_file_fd.get(),
1774 oat_file_fd.get(),
1775 zip_fd.get(),
1776 instruction_set,
1777 compiler_filter, profile_was_updated,
1778 downgrade,
1779 class_loader_context);
1780 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001781 }
1782
1783 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001784 int result = wait_child(pid);
1785 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001786 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1787 dex_path.c_str(),
1788 result);
1789 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001790 return false;
1791 }
1792 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001793 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001794 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1795 result,
1796 dexopt_needed_out,
1797 error_msg);
1798 if (!success) {
1799 LOG(ERROR) << *error_msg;
1800 }
Calin Juravle7d765462017-09-04 15:57:10 -07001801
1802 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1803
Calin Juravle80a21252017-01-17 14:43:25 -08001804 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001805 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1806 // makes the code simpler; force compilation is only needed during tests).
1807 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001808 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001809 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001810 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1811 }
1812
Calin Juravle7d765462017-09-04 15:57:10 -07001813 // Check if we should make the oat file public.
1814 // Note that if the dex file is not public the compiled code cannot be made public.
1815 // It is ok to check this flag outside in the parent process.
1816 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1817
Calin Juravle80a21252017-01-17 14:43:25 -08001818 return success;
1819}
1820
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001821static std::string format_dexopt_error(int status, const char* dex_path) {
1822 if (WIFEXITED(status)) {
1823 int int_code = WEXITSTATUS(status);
1824 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1825 if (code_name != nullptr) {
1826 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1827 }
1828 }
1829 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001830}
1831
Calin Juravlec9eab382017-01-25 01:17:17 -08001832int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001833 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001834 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001835 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001836 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001837 CHECK(pkgname != nullptr);
1838 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001839 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001840 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1841 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001842
Calin Juravled23dee72017-07-06 16:29:11 -07001843 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001844 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001845 return -1;
1846 }
1847
1848 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001849 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1850 class_loader_context);
1851 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001852 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001853 }
1854
Calin Juravleebc8a792017-04-04 20:21:05 -07001855 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001856 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1857 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1858 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001859 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001860 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001861 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001862 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001863 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001864
1865 // Check if we're dealing with a secondary dex file and if we need to compile it.
1866 std::string oat_dir_str;
1867 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001868 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001869 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001870 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001871 oat_dir = oat_dir_str.c_str();
1872 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1873 return 0; // Nothing to do, report success.
1874 }
1875 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001876 if (error_msg->empty()) { // TODO: Make this a CHECK.
1877 *error_msg = "Failed processing secondary.";
1878 }
Calin Juravle80a21252017-01-17 14:43:25 -08001879 return -1; // We had an error, logged in the process method.
1880 }
1881 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001882 // Currently these flags are only use for secondary dex files.
1883 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001884 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1885 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1886 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001887
1888 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001889 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001890 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001891 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1892 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001893 return -1;
1894 }
1895
1896 // Create the output OAT file.
1897 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001898 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001899 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001900 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001901 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001902 return -1;
1903 }
1904
1905 // Open vdex files.
1906 Dex2oatFileWrapper in_vdex_fd;
1907 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001908 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1909 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001910 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001911 return -1;
1912 }
1913
Calin Juravlecb556e32017-04-04 20:22:50 -07001914 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1915 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1916 // fully inherit their parent context).
1917 // Note that for primary apk the oat files are created before, in a separate installd
1918 // call which also does the restorecon. TODO(calin): unify the paths.
1919 if (is_secondary_dex) {
1920 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1921 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001922 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1923 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001924 return -1;
1925 }
1926 }
1927
Jeff Sharkey90aff262016-12-12 14:28:24 -07001928 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001929 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001930
Calin Juravle7a570e82017-01-14 16:23:30 -08001931 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001932 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1933 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001934
Calin Juravle7a570e82017-01-14 16:23:30 -08001935 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001936 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001937 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001938
Calin Juravle62c5a372018-02-01 17:03:23 +00001939 unique_fd dex_metadata_fd;
1940 if (dex_metadata_path != nullptr) {
1941 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1942 if (dex_metadata_fd.get() < 0) {
1943 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1944 }
1945 }
1946
Andreas Gampe023b2242018-02-28 16:03:25 -08001947 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001948
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001949 RunDex2Oat runner(input_fd.get(),
1950 out_oat_fd.get(),
1951 in_vdex_fd.get(),
1952 out_vdex_fd.get(),
1953 image_fd.get(),
1954 dex_path,
1955 out_oat_path,
1956 swap_fd.get(),
1957 instruction_set,
1958 compiler_filter,
1959 debuggable,
1960 boot_complete,
1961 background_job_compile,
1962 reference_profile_fd.get(),
1963 class_loader_context,
1964 target_sdk_version,
1965 enable_hidden_api_checks,
1966 generate_compact_dex,
1967 dex_metadata_fd.get(),
1968 compilation_reason);
1969
Jeff Sharkey90aff262016-12-12 14:28:24 -07001970 pid_t pid = fork();
1971 if (pid == 0) {
1972 /* child -- drop privileges before continuing */
1973 drop_capabilities(uid);
1974
Richard Uhler76cc0272016-12-08 10:46:35 +00001975 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001976 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001977 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001978 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001979 }
1980
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001981 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982 } else {
1983 int res = wait_child(pid);
1984 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001985 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001986 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001987 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1988 << std::hex << std::setw(4) << res << ", process failed";
1989 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001990 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001991 }
1992 }
1993
Calin Juravlec9eab382017-01-25 01:17:17 -08001994 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001995
1996 // We've been successful, don't delete output.
1997 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001998 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001999 image_fd.SetCleanup(false);
2000 reference_profile_fd.SetCleanup(false);
2001
2002 return 0;
2003}
2004
Calin Juravlec9eab382017-01-25 01:17:17 -08002005// Try to remove the given directory. Log an error if the directory exists
2006// and is empty but could not be removed.
2007static bool rmdir_if_empty(const char* dir) {
2008 if (rmdir(dir) == 0) {
2009 return true;
2010 }
2011 if (errno == ENOENT || errno == ENOTEMPTY) {
2012 return true;
2013 }
2014 PLOG(ERROR) << "Failed to remove dir: " << dir;
2015 return false;
2016}
2017
2018// Try to unlink the given file. Log an error if the file exists and could not
2019// be unlinked.
2020static bool unlink_if_exists(const std::string& file) {
2021 if (unlink(file.c_str()) == 0) {
2022 return true;
2023 }
2024 if (errno == ENOENT) {
2025 return true;
2026
2027 }
2028 PLOG(ERROR) << "Could not unlink: " << file;
2029 return false;
2030}
2031
Calin Juravle7d765462017-09-04 15:57:10 -07002032enum ReconcileSecondaryDexResult {
2033 kReconcileSecondaryDexExists = 0,
2034 kReconcileSecondaryDexCleanedUp = 1,
2035 kReconcileSecondaryDexValidationError = 2,
2036 kReconcileSecondaryDexCleanUpError = 3,
2037 kReconcileSecondaryDexAccessIOError = 4,
2038};
Calin Juravlec9eab382017-01-25 01:17:17 -08002039
2040// Reconcile the secondary dex 'dex_path' and its generated oat files.
2041// Return true if all the parameters are valid and the secondary dex file was
2042// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2043// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2044// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2045// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2046// Return false if there were errors during processing. In this case
2047// out_secondary_dex_exists will be set to false.
2048bool reconcile_secondary_dex_file(const std::string& dex_path,
2049 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2050 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2051 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002052 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002053 if (isas.size() == 0) {
2054 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2055 return false;
2056 }
2057
Calin Juravle7d765462017-09-04 15:57:10 -07002058 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2059 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2060 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002061 return false;
2062 }
2063
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002064 // As a security measure we want to unlink art artifacts with the reduced capabilities
2065 // of the package user id. So we fork and drop capabilities in the child.
2066 pid_t pid = fork();
2067 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002068 /* child -- drop privileges before continuing */
2069 drop_capabilities(uid);
2070
2071 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2072 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2073 uid, storage_flag)) {
2074 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2075 _exit(kReconcileSecondaryDexValidationError);
2076 }
2077
2078 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2079 switch (access_check) {
2080 case kSecondaryDexAccessDoesNotExist:
2081 // File does not exist. Proceed with cleaning.
2082 break;
2083 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2084 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2085 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2086 default:
2087 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2088 _exit(kReconcileSecondaryDexValidationError);
2089 }
2090
2091 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002092 char oat_path[PKG_PATH_MAX];
2093 char oat_dir[PKG_PATH_MAX];
2094 char oat_isa_dir[PKG_PATH_MAX];
2095 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002096 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002097 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002098 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002099 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2100 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002101 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002102 }
Calin Juravle51314092017-05-18 15:33:05 -07002103
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002104 // Delete oat/vdex/art files.
2105 result = unlink_if_exists(oat_path) && result;
2106 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2107 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002108
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002109 // Delete profiles.
2110 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002111 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002112 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002113 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002114 result = unlink_if_exists(current_profile) && result;
2115 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002116
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002117 // We upgraded once the location of current profile for secondary dex files.
2118 // Check for any previous left-overs and remove them as well.
2119 std::string old_current_profile = dex_path + ".prof";
2120 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002121
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002122 // Try removing the directories as well, they might be empty.
2123 result = rmdir_if_empty(oat_isa_dir) && result;
2124 result = rmdir_if_empty(oat_dir) && result;
2125 }
Calin Juravle7d765462017-09-04 15:57:10 -07002126 if (!result) {
2127 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2128 }
2129 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002130 }
2131
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002132 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002133 if (!WIFEXITED(return_code)) {
2134 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2135 } else {
2136 return_code = WEXITSTATUS(return_code);
2137 }
2138
2139 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2140
2141 switch (return_code) {
2142 case kReconcileSecondaryDexCleanedUp:
2143 case kReconcileSecondaryDexValidationError:
2144 // If we couldn't validate assume the dex file does not exist.
2145 // This will purge the entry from the PM records.
2146 *out_secondary_dex_exists = false;
2147 return true;
2148 case kReconcileSecondaryDexExists:
2149 *out_secondary_dex_exists = true;
2150 return true;
2151 case kReconcileSecondaryDexAccessIOError:
2152 // We had an access IO error.
2153 // Return false so that we can try again.
2154 // The value of out_secondary_dex_exists does not matter in this case and by convention
2155 // is set to false.
2156 *out_secondary_dex_exists = false;
2157 return false;
2158 default:
2159 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2160 *out_secondary_dex_exists = false;
2161 return false;
2162 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002163}
2164
Alan Stokesa25d90c2017-10-16 10:56:00 +01002165// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2166// Returns true if all parameters are valid and the hash successfully computed and stored in
2167// out_secondary_dex_hash.
2168// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2169// the app.
2170// For any other errors (e.g. if any of the parameters are invalid) returns false.
2171bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2172 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2173 std::vector<uint8_t>* out_secondary_dex_hash) {
2174 out_secondary_dex_hash->clear();
2175
2176 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2177
2178 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2179 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2180 << storage_flag;
2181 return false;
2182 }
2183
2184 // Pipe to get the hash result back from our child process.
2185 unique_fd pipe_read, pipe_write;
2186 if (!Pipe(&pipe_read, &pipe_write)) {
2187 PLOG(ERROR) << "Failed to create pipe";
2188 return false;
2189 }
2190
2191 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2192 // access data the app itself can access.
2193 pid_t pid = fork();
2194 if (pid == 0) {
2195 // child -- drop privileges before continuing
2196 drop_capabilities(uid);
2197 pipe_read.reset();
2198
2199 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2200 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002201 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002202 }
2203
2204 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2205 if (fd == -1) {
2206 if (errno == EACCES || errno == ENOENT) {
2207 // Not treated as an error.
2208 _exit(0);
2209 }
2210 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002211 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002212 }
2213
2214 SHA256_CTX ctx;
2215 SHA256_Init(&ctx);
2216
2217 std::vector<uint8_t> buffer(65536);
2218 while (true) {
2219 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2220 if (bytes_read == 0) {
2221 break;
2222 } else if (bytes_read == -1) {
2223 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002224 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002225 }
2226
2227 SHA256_Update(&ctx, buffer.data(), bytes_read);
2228 }
2229
2230 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2231 SHA256_Final(hash.data(), &ctx);
2232 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002233 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002234 }
2235
2236 _exit(0);
2237 }
2238
2239 // parent
2240 pipe_write.reset();
2241
2242 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2243 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2244 out_secondary_dex_hash->clear();
2245 }
2246 return wait_child(pid) == 0;
2247}
2248
Jeff Sharkey90aff262016-12-12 14:28:24 -07002249// Helper for move_ab, so that we can have common failure-case cleanup.
2250static bool unlink_and_rename(const char* from, const char* to) {
2251 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2252 // return a failure.
2253 struct stat s;
2254 if (stat(to, &s) == 0) {
2255 if (!S_ISREG(s.st_mode)) {
2256 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2257 return false;
2258 }
2259 if (unlink(to) != 0) {
2260 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2261 return false;
2262 }
2263 } else {
2264 // This may be a permission problem. We could investigate the error code, but we'll just
2265 // let the rename failure do the work for us.
2266 }
2267
2268 // Try to rename "to" to "from."
2269 if (rename(from, to) != 0) {
2270 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2271 return false;
2272 }
2273 return true;
2274}
2275
2276// Move/rename a B artifact (from) to an A artifact (to).
2277static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2278 // Check whether B exists.
2279 {
2280 struct stat s;
2281 if (stat(b_path.c_str(), &s) != 0) {
2282 // Silently ignore for now. The service calling this isn't smart enough to understand
2283 // lack of artifacts at the moment.
2284 return false;
2285 }
2286 if (!S_ISREG(s.st_mode)) {
2287 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2288 // Try to unlink, but swallow errors.
2289 unlink(b_path.c_str());
2290 return false;
2291 }
2292 }
2293
2294 // Rename B to A.
2295 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2296 // Delete the b_path so we don't try again (or fail earlier).
2297 if (unlink(b_path.c_str()) != 0) {
2298 PLOG(ERROR) << "Could not unlink " << b_path;
2299 }
2300
2301 return false;
2302 }
2303
2304 return true;
2305}
2306
2307bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2308 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002309 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2310 if (slot_suffix.empty()) {
2311 return false;
2312 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002313
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002314 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2315 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2316 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002317 }
2318
2319 // Validate other inputs.
2320 if (validate_apk_path(apk_path) != 0) {
2321 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2322 return false;
2323 }
2324 if (validate_apk_path(oat_dir) != 0) {
2325 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2326 return false;
2327 }
2328
2329 char a_path[PKG_PATH_MAX];
2330 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2331 return false;
2332 }
2333 const std::string a_vdex_path = create_vdex_filename(a_path);
2334 const std::string a_image_path = create_image_filename(a_path);
2335
2336 // B path = A path + slot suffix.
2337 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2338 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2339 const std::string b_image_path = StringPrintf("%s.%s",
2340 a_image_path.c_str(),
2341 slot_suffix.c_str());
2342
2343 bool success = true;
2344 if (move_ab_path(b_path, a_path)) {
2345 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2346 // Note: we can live without an app image. As such, ignore failure to move the image file.
2347 // If we decide to require the app image, or the app image being moved correctly,
2348 // then change accordingly.
2349 constexpr bool kIgnoreAppImageFailure = true;
2350
2351 if (!a_image_path.empty()) {
2352 if (!move_ab_path(b_image_path, a_image_path)) {
2353 unlink(a_image_path.c_str());
2354 if (!kIgnoreAppImageFailure) {
2355 success = false;
2356 }
2357 }
2358 }
2359 } else {
2360 // Cleanup: delete B image, ignore errors.
2361 unlink(b_image_path.c_str());
2362 success = false;
2363 }
2364 } else {
2365 // Cleanup: delete B image, ignore errors.
2366 unlink(b_vdex_path.c_str());
2367 unlink(b_image_path.c_str());
2368 success = false;
2369 }
2370 return success;
2371}
2372
2373bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2374 // Delete the oat/odex file.
2375 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002376 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002377 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002378 return false;
2379 }
2380
2381 // In case of a permission failure report the issue. Otherwise just print a warning.
2382 auto unlink_and_check = [](const char* path) -> bool {
2383 int result = unlink(path);
2384 if (result != 0) {
2385 if (errno == EACCES || errno == EPERM) {
2386 PLOG(ERROR) << "Could not unlink " << path;
2387 return false;
2388 }
2389 PLOG(WARNING) << "Could not unlink " << path;
2390 }
2391 return true;
2392 };
2393
2394 // Delete the oat/odex file.
2395 bool return_value_oat = unlink_and_check(out_path);
2396
2397 // Derive and delete the app image.
2398 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2399
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002400 // Derive and delete the vdex file.
2401 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2402
Jeff Sharkey90aff262016-12-12 14:28:24 -07002403 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002404 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002405}
2406
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002407static bool is_absolute_path(const std::string& path) {
2408 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2409 LOG(ERROR) << "Invalid absolute path " << path;
2410 return false;
2411 } else {
2412 return true;
2413 }
2414}
2415
2416static bool is_valid_instruction_set(const std::string& instruction_set) {
2417 // TODO: add explicit whitelisting of instruction sets
2418 if (instruction_set.find('/') != std::string::npos) {
2419 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2420 return false;
2421 } else {
2422 return true;
2423 }
2424}
2425
2426bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2427 const char *apk_path, const char *instruction_set) {
2428 std::string oat_dir_ = oat_dir;
2429 std::string apk_path_ = apk_path;
2430 std::string instruction_set_ = instruction_set;
2431
2432 if (!is_absolute_path(oat_dir_)) return false;
2433 if (!is_absolute_path(apk_path_)) return false;
2434 if (!is_valid_instruction_set(instruction_set_)) return false;
2435
2436 std::string::size_type end = apk_path_.rfind('.');
2437 std::string::size_type start = apk_path_.rfind('/', end);
2438 if (end == std::string::npos || start == std::string::npos) {
2439 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2440 return false;
2441 }
2442
2443 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2444 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2445 const char* res = res_.c_str();
2446 if (strlen(res) >= PKG_PATH_MAX) {
2447 LOG(ERROR) << "Result too large";
2448 return false;
2449 } else {
2450 strlcpy(path, res, PKG_PATH_MAX);
2451 return true;
2452 }
2453}
2454
2455bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2456 const char *instruction_set) {
2457 std::string apk_path_ = apk_path;
2458 std::string instruction_set_ = instruction_set;
2459
2460 if (!is_absolute_path(apk_path_)) return false;
2461 if (!is_valid_instruction_set(instruction_set_)) return false;
2462
2463 std::string::size_type end = apk_path_.rfind('.');
2464 std::string::size_type start = apk_path_.rfind('/', end);
2465 if (end == std::string::npos || start == std::string::npos) {
2466 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2467 return false;
2468 }
2469
2470 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2471 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2472}
2473
2474bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2475 const char *instruction_set) {
2476 std::string src_ = src;
2477 std::string instruction_set_ = instruction_set;
2478
2479 if (!is_absolute_path(src_)) return false;
2480 if (!is_valid_instruction_set(instruction_set_)) return false;
2481
2482 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2483 if (*it == '/') {
2484 *it = '@';
2485 }
2486 }
2487
2488 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2489 + DALVIK_CACHE_POSTFIX;
2490 const char* res = res_.c_str();
2491 if (strlen(res) >= PKG_PATH_MAX) {
2492 LOG(ERROR) << "Result too large";
2493 return false;
2494 } else {
2495 strlcpy(path, res, PKG_PATH_MAX);
2496 return true;
2497 }
2498}
2499
Calin Juravle59f7ab82018-04-27 17:50:23 -07002500bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2501 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002502 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2503 for (const std::string& elem : classpaths_elems) {
2504 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2505 if (fd < 0) {
2506 PLOG(ERROR) << "Could not open classpath elem " << elem;
2507 return false;
2508 } else {
2509 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002510 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002511 }
2512 }
2513 return true;
2514}
2515
2516static bool create_app_profile_snapshot(int32_t app_id,
2517 const std::string& package_name,
2518 const std::string& profile_name,
2519 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002520 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2521
Calin Juravle824a64d2018-01-18 20:23:17 -08002522 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002523 if (snapshot_fd < 0) {
2524 return false;
2525 }
2526
2527 std::vector<unique_fd> profiles_fd;
2528 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002529 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2530 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002531 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2532 return false;
2533 }
2534
2535 profiles_fd.push_back(std::move(reference_profile_fd));
2536
Calin Juravle0d0a4922018-01-23 19:54:11 -08002537 // Open the class paths elements. These will be used to filter out profile data that does
2538 // not belong to the classpath during merge.
2539 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002540 std::vector<std::string> dex_locations;
2541 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002542 return false;
2543 }
2544
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002545 RunProfman args;
2546 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002547 pid_t pid = fork();
2548 if (pid == 0) {
2549 /* child -- drop privileges before continuing */
2550 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002551 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002552 }
2553
2554 /* parent */
2555 int return_code = wait_child(pid);
2556 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002557 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002558 return false;
2559 }
2560
2561 return true;
2562}
2563
Calin Juravle0d0a4922018-01-23 19:54:11 -08002564static bool create_boot_image_profile_snapshot(const std::string& package_name,
2565 const std::string& profile_name,
2566 const std::string& classpath) {
2567 // The reference profile directory for the android package might not be prepared. Do it now.
2568 const std::string ref_profile_dir =
2569 create_primary_reference_profile_package_dir_path(package_name);
2570 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2571 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2572 return false;
2573 }
2574
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002575 // Return false for empty class path since it may otherwise return true below if profiles is
2576 // empty.
2577 if (classpath.empty()) {
2578 PLOG(ERROR) << "Class path is empty";
2579 return false;
2580 }
2581
Calin Juravle0d0a4922018-01-23 19:54:11 -08002582 // Open and create the snapshot profile.
2583 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2584
2585 // Collect all non empty profiles.
2586 // The collection will traverse all applications profiles and find the non empty files.
2587 // This has the potential of inspecting a large number of files and directories (depending
2588 // on the number of applications and users). So there is a slight increase in the chance
2589 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2590 // fail the snapshot and aggregate whatever profile we could open.
2591 //
2592 // The profile snapshot is a best effort based on available data it's ok if some data
2593 // from some apps is missing. It will be counter productive for the snapshot to fail
2594 // because we could not open or read some of the files.
2595 std::vector<std::string> profiles;
2596 if (!collect_profiles(&profiles)) {
2597 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2598 }
2599
2600 // If we have no profiles return early.
2601 if (profiles.empty()) {
2602 return true;
2603 }
2604
2605 // Open the classpath elements. These will be used to filter out profile data that does
2606 // not belong to the classpath during merge.
2607 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002608 std::vector<std::string> dex_locations;
2609 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002610 return false;
2611 }
2612
2613 // If we could not open any files from the classpath return an error.
2614 if (apk_fds.empty()) {
2615 LOG(ERROR) << "Could not open any of the classpath elements.";
2616 return false;
2617 }
2618
2619 // Aggregate the profiles in batches of kAggregationBatchSize.
2620 // We do this to avoid opening a huge a amount of files.
2621 static constexpr size_t kAggregationBatchSize = 10;
2622
2623 std::vector<unique_fd> profiles_fd;
2624 for (size_t i = 0; i < profiles.size(); ) {
2625 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2626 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2627 if (fd.get() >= 0) {
2628 profiles_fd.push_back(std::move(fd));
2629 }
2630 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002631 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002632 args.SetupMerge(profiles_fd,
2633 snapshot_fd,
2634 apk_fds,
2635 dex_locations,
2636 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002637 pid_t pid = fork();
2638 if (pid == 0) {
2639 /* child -- drop privileges before continuing */
2640 drop_capabilities(AID_SYSTEM);
2641
Calin Juravle59f7ab82018-04-27 17:50:23 -07002642 // The introduction of new access flags into boot jars causes them to
2643 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002644 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002645 }
2646
2647 /* parent */
2648 int return_code = wait_child(pid);
2649 if (!WIFEXITED(return_code)) {
2650 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2651 return false;
2652 }
2653 return true;
2654 }
2655 return true;
2656}
2657
2658bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2659 const std::string& profile_name, const std::string& classpath) {
2660 if (app_id == -1) {
2661 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2662 } else {
2663 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2664 }
2665}
2666
Calin Juravlec3b049e2018-01-18 22:32:58 -08002667bool prepare_app_profile(const std::string& package_name,
2668 userid_t user_id,
2669 appid_t app_id,
2670 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002671 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002672 const std::unique_ptr<std::string>& dex_metadata) {
2673 // Prepare the current profile.
2674 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2675 /*is_secondary_dex*/ false);
2676 uid_t uid = multiuser_get_uid(user_id, app_id);
2677 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2678 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2679 return false;
2680 }
2681
2682 // Check if we need to install the profile from the dex metadata.
2683 if (dex_metadata == nullptr) {
2684 return true;
2685 }
2686
2687 // We have a dex metdata. Merge the profile into the reference profile.
2688 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2689 /*read_write*/ true, /*is_secondary_dex*/ false);
2690 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2691 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002692 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2693 if (apk_fd < 0) {
2694 PLOG(ERROR) << "Could not open code path " << code_path;
2695 return false;
2696 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002697
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002698 RunProfman args;
2699 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2700 std::move(ref_profile_fd),
2701 std::move(apk_fd),
2702 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002703 pid_t pid = fork();
2704 if (pid == 0) {
2705 /* child -- drop privileges before continuing */
2706 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2707 drop_capabilities(app_shared_gid);
2708
Calin Juravlef63d4792018-01-30 17:43:34 +00002709 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002710 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002711 }
2712
2713 /* parent */
2714 int return_code = wait_child(pid);
2715 if (!WIFEXITED(return_code)) {
2716 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2717 return false;
2718 }
2719 return true;
2720}
2721
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002722} // namespace installd
2723} // namespace android