blob: 50a2412c6b1b2bab2a1fcc5945590fd85bf45e09 [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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier9b2da082018-10-26 13:23:11 -0700210
Mathieu Chartier62d218d2018-11-05 09:34:24 -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 Chartier9b2da082018-10-26 13:23:11 -0700220 }
Mathieu Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -0800305 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700306
Mathieu Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -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 Chartier62d218d2018-11-05 09:34:24 -0800316 const std::string resolve_startup_string_arg =
317 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
318 "--resolve-startup-const-strings=%s");
319 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700320
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800321 std::string image_format_arg;
322 if (image_fd >= 0) {
323 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Andreas Gampee87fe0a2018-03-01 23:55:53 -0800324 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700325
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800326 std::string dex2oat_large_app_threshold_arg =
327 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700328
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800329 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
330 const char* dex2oat_bin = "/system/bin/dex2oat";
331 constexpr const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
332 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
333 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
334 if (is_debug_runtime() ||
335 (background_job_compile && is_debuggable_build() && !is_release)) {
336 if (access(kDex2oatDebugPath, X_OK) == 0) {
337 dex2oat_bin = kDex2oatDebugPath;
338 }
339 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800341 bool generate_minidebug_info = kEnableMinidebugInfo &&
342 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700343
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800344 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
345 // use arraysize instead.
346 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
347 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
348 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
349 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
350 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
351 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
352 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
353 std::string dex2oat_compiler_filter_arg;
354 std::string dex2oat_swap_fd;
355 std::string dex2oat_image_fd;
356 std::string target_sdk_version_arg;
357 if (target_sdk_version != 0) {
358 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
359 }
360 std::string class_loader_context_arg;
361 if (class_loader_context != nullptr) {
362 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
363 class_loader_context);
364 }
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100365
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800366 if (swap_fd >= 0) {
367 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
368 }
369 if (image_fd >= 0) {
370 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
371 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700372
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800373 // Compute compiler filter.
374 bool have_dex2oat_relocation_skip_flag = false;
375 if (skip_compilation) {
376 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
377 have_dex2oat_relocation_skip_flag = true;
378 } else if (compiler_filter != nullptr) {
379 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
380 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700381
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800382 if (dex2oat_compiler_filter_arg.empty()) {
383 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
384 "--compiler-filter=%s");
385 }
386
387 // Check whether all apps should be compiled debuggable.
388 if (!debuggable) {
389 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
390 }
391 std::string profile_arg;
392 if (profile_fd != -1) {
393 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
394 }
395
396 // Get the directory of the apk to pass as a base classpath directory.
397 std::string base_dir;
398 std::string apk_dir(input_file_name);
399 unsigned long dir_index = apk_dir.rfind('/');
400 bool has_base_dir = dir_index != std::string::npos;
401 if (has_base_dir) {
402 apk_dir = apk_dir.substr(0, dir_index);
403 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
404 }
405
406 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
407
408 std::string compilation_reason_arg = compilation_reason == nullptr
409 ? ""
410 : std::string("--compilation-reason=") + compilation_reason;
411
412 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
413
414 // Disable cdex if update input vdex is true since this combination of options is not
415 // supported.
416 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
417
418 AddArg(zip_fd_arg);
419 AddArg(zip_location_arg);
420 AddArg(input_vdex_fd_arg);
421 AddArg(output_vdex_fd_arg);
422 AddArg(oat_fd_arg);
423 AddArg(oat_location_arg);
424 AddArg(instruction_set_arg);
425
426 AddArg(instruction_set_variant_arg);
427 AddArg(instruction_set_features_arg);
428
429 AddRuntimeArg(dex2oat_Xms_arg);
430 AddRuntimeArg(dex2oat_Xmx_arg);
431
432 AddArg(resolve_startup_string_arg);
433 AddArg(dex2oat_compiler_filter_arg);
434 AddArg(dex2oat_threads_arg);
435 AddArg(dex2oat_swap_fd);
436 AddArg(dex2oat_image_fd);
437
438 if (generate_debug_info) {
439 AddArg("--generate-debug-info");
440 }
441 if (debuggable) {
442 AddArg("--debuggable");
443 }
444 AddArg(image_format_arg);
445 AddArg(dex2oat_large_app_threshold_arg);
446
447 if (have_dex2oat_relocation_skip_flag) {
448 AddRuntimeArg(dex2oat_norelocation);
449 }
450 AddArg(profile_arg);
451 AddArg(base_dir);
452 AddArg(class_loader_context_arg);
453 if (generate_minidebug_info) {
454 AddArg(kMinidebugDex2oatFlag);
455 }
456 if (disable_cdex) {
457 AddArg(kDisableCompactDexFlag);
458 }
459 AddArg(target_sdk_version_arg);
460 if (enable_hidden_api_checks) {
461 AddRuntimeArg("-Xhidden-api-checks");
462 }
463
464 if (dex_metadata_fd > -1) {
465 AddArg(dex_metadata_fd_arg);
466 }
467
468 AddArg(compilation_reason_arg);
469
470 // Do not add args after dex2oat_flags, they should override others for debugging.
471 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
472
473 PrepareArgs(dex2oat_bin);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700474 }
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800475};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700476
477/*
478 * Whether dexopt should use a swap file when compiling an APK.
479 *
480 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
481 * itself, anyways).
482 *
483 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
484 *
485 * Otherwise, return true if this is a low-mem device.
486 *
487 * Otherwise, return default value.
488 */
489static bool kAlwaysProvideSwapFile = false;
490static bool kDefaultProvideSwapFile = true;
491
492static bool ShouldUseSwapFileForDexopt() {
493 if (kAlwaysProvideSwapFile) {
494 return true;
495 }
496
497 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700498 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
499 if (!dex2oat_prop_buf.empty()) {
500 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700501 }
502
503 // Shortcut for default value. This is an implementation optimization for the process sketched
504 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
505 // as low-mem is never returning false. The compiler will optimize this away if it can.
506 if (kDefaultProvideSwapFile) {
507 return true;
508 }
509
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700510 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700511 return true;
512 }
513
514 // Default value must be false here.
515 return kDefaultProvideSwapFile;
516}
517
Richard Uhler76cc0272016-12-08 10:46:35 +0000518static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700519 if (set_to_bg) {
520 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800521 PLOG(ERROR) << "set_sched_policy failed";
522 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700523 }
524 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800525 PLOG(ERROR) << "setpriority failed";
526 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700527 }
528 }
529}
530
Calin Juravle29591732017-11-20 17:46:19 -0800531static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
532 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800533 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800534 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800535 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800536 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800537 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700538 }
Calin Juravle114f0812017-03-08 19:05:07 -0800539 // Profiles should belong to the app; make sure of that by giving ownership to
540 // the app uid. If we cannot do that, there's no point in returning the fd
541 // since dex2oat/profman will fail with SElinux denials.
542 if (fchown(fd.get(), uid, uid) < 0) {
543 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800544 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800545 }
Calin Juravle29591732017-11-20 17:46:19 -0800546 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800547}
548
Calin Juravle29591732017-11-20 17:46:19 -0800549static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800550 // Do not follow symlinks when opening a profile:
551 // - primary profiles should not contain symlinks in their paths
552 // - secondary dex paths should have been already resolved and validated
553 flags |= O_NOFOLLOW;
554
Calin Juravle29591732017-11-20 17:46:19 -0800555 // Check if we need to create the profile
556 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
557 unique_fd fd;
558 if ((flags & O_CREAT) != 0) {
559 fd = create_profile(uid, profile, flags);
560 } else {
561 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
562 }
563
Calin Juravle114f0812017-03-08 19:05:07 -0800564 if (fd.get() < 0) {
565 if (errno != ENOENT) {
566 // Profiles might be missing for various reasons. For example, in a
567 // multi-user environment, the profile directory for one user can be created
568 // after we start a merge. In this case the current profile for that user
569 // will not be found.
570 // Also, the secondary dex profiles might be deleted by the app at any time,
571 // so we can't we need to prepare if they are missing.
572 PLOG(ERROR) << "Failed to open profile " << profile;
573 }
574 return invalid_unique_fd();
575 }
576
Jeff Sharkey90aff262016-12-12 14:28:24 -0700577 return fd;
578}
579
Calin Juravle824a64d2018-01-18 20:23:17 -0800580static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
581 const std::string& location, bool is_secondary_dex) {
582 std::string profile = create_current_profile_path(user, package_name, location,
583 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800584 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800585}
586
Calin Juravle824a64d2018-01-18 20:23:17 -0800587static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
588 const std::string& location, bool read_write, bool is_secondary_dex) {
589 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800590 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
591}
592
593static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800594 const std::string& location) {
595 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800596 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800597}
598
Calin Juravle824a64d2018-01-18 20:23:17 -0800599static void open_profile_files(uid_t uid, const std::string& package_name,
600 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800601 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700602 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800603 *reference_profile_fd = open_reference_profile(uid, package_name, location,
604 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605
Calin Juravle114f0812017-03-08 19:05:07 -0800606 // For secondary dex files, we don't really need the user but we use it for sanity checks.
607 // Note: the user owning the dex file should be the current user.
608 std::vector<userid_t> users;
609 if (is_secondary_dex){
610 users.push_back(multiuser_get_user_id(uid));
611 } else {
612 users = get_known_users(/*volume_uuid*/ nullptr);
613 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800615 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
616 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800618 if (profile_fd.get() >= 0) {
619 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700620 }
621 }
622}
623
624static void drop_capabilities(uid_t uid) {
625 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800626 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
627 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700628 }
629 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800630 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
631 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700632 }
633 // drop capabilities
634 struct __user_cap_header_struct capheader;
635 struct __user_cap_data_struct capdata[2];
636 memset(&capheader, 0, sizeof(capheader));
637 memset(&capdata, 0, sizeof(capdata));
638 capheader.version = _LINUX_CAPABILITY_VERSION_3;
639 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800640 PLOG(ERROR) << "capset failed";
641 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700642 }
643}
644
645static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
646static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
647static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
648static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
649static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
650
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800651class RunProfman : public ExecVHelper {
652 public:
653 void SetupArgs(const std::vector<unique_fd>& profile_fds,
654 const unique_fd& reference_profile_fd,
655 const std::vector<unique_fd>& apk_fds,
656 const std::vector<std::string>& dex_locations,
657 bool copy_and_update) {
658 const char* profman_bin =
659 is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700660
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800661 if (copy_and_update) {
662 CHECK_EQ(1u, profile_fds.size());
663 CHECK_EQ(1u, apk_fds.size());
Calin Juravle0d0a4922018-01-23 19:54:11 -0800664 }
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800665 if (reference_profile_fd != -1) {
666 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Calin Juravle59f7ab82018-04-27 17:50:23 -0700667 }
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800668
669 for (const unique_fd& fd : profile_fds) {
670 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
671 }
672
673 for (const unique_fd& fd : apk_fds) {
674 AddArg("--apk-fd=" + std::to_string(fd.get()));
675 }
676
677 for (const std::string& dex_location : dex_locations) {
678 AddArg("--dex-location=" + dex_location);
679 }
680
681 if (copy_and_update) {
682 AddArg("--copy-and-update-profile-key");
683 }
684
685 // Do not add after dex2oat_flags, they should override others for debugging.
686 PrepareArgs(profman_bin);
Calin Juravle59f7ab82018-04-27 17:50:23 -0700687 }
688
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800689 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
690 const unique_fd& reference_profile_fd,
691 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
692 const std::vector<std::string>& dex_locations = std::vector<std::string>()) {
693 SetupArgs(profiles_fd,
694 reference_profile_fd,
695 apk_fds,
696 dex_locations,
697 /*copy_and_update=*/false);
Calin Juravlef63d4792018-01-30 17:43:34 +0000698 }
Calin Juravle59f7ab82018-04-27 17:50:23 -0700699
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800700 void SetupCopyAndUpdate(unique_fd&& profile_fd,
701 unique_fd&& reference_profile_fd,
702 unique_fd&& apk_fd,
703 const std::string& dex_location) {
704 std::vector<unique_fd> profiles_fd;
705 profiles_fd.push_back(std::move(profile_fd));
706 std::vector<unique_fd> apk_fds;
707 profiles_fd.push_back(std::move(apk_fd));
708 std::vector<std::string> dex_locations = {dex_location};
709 SetupArgs(profiles_fd, reference_profile_fd, apk_fds, dex_locations,
710 /*copy_and_update=*/true);
711 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800713 void SetupDump(const std::vector<unique_fd>& profiles_fd,
714 const unique_fd& reference_profile_fd,
715 const std::vector<std::string>& dex_locations,
716 const std::vector<unique_fd>& apk_fds,
717 const unique_fd& output_fd) {
718 AddArg("--dump-only");
719 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
720 SetupArgs(profiles_fd, reference_profile_fd, apk_fds, dex_locations,
721 /*copy_and_update=*/false);
722 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700723
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800724 void Exec() {
725 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
726 }
727};
Calin Juravlef63d4792018-01-30 17:43:34 +0000728
Calin Juravlef63d4792018-01-30 17:43:34 +0000729
Calin Juravlef63d4792018-01-30 17:43:34 +0000730
Jeff Sharkey90aff262016-12-12 14:28:24 -0700731// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800732// The location is the package name for primary apks or the dex path for secondary dex files.
733// Returns true if there is enough information in the current profiles that makes it
734// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735// If the return value is true all the current profiles would have been merged into
736// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800737static bool analyze_profiles(uid_t uid, const std::string& package_name,
738 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800739 std::vector<unique_fd> profiles_fd;
740 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800741 open_profile_files(uid, package_name, location, is_secondary_dex,
742 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800743 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700744 // Skip profile guided compilation because no profiles were found.
745 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700746 return false;
747 }
748
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800749 RunProfman profman_merge;
750 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700751 pid_t pid = fork();
752 if (pid == 0) {
753 /* child -- drop privileges before continuing */
754 drop_capabilities(uid);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800755 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 }
757 /* parent */
758 int return_code = wait_child(pid);
759 bool need_to_compile = false;
760 bool should_clear_current_profiles = false;
761 bool should_clear_reference_profile = false;
762 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800763 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700764 } else {
765 return_code = WEXITSTATUS(return_code);
766 switch (return_code) {
767 case PROFMAN_BIN_RETURN_CODE_COMPILE:
768 need_to_compile = true;
769 should_clear_current_profiles = true;
770 should_clear_reference_profile = false;
771 break;
772 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
773 need_to_compile = false;
774 should_clear_current_profiles = false;
775 should_clear_reference_profile = false;
776 break;
777 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800778 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 need_to_compile = false;
780 should_clear_current_profiles = true;
781 should_clear_reference_profile = true;
782 break;
783 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
784 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
785 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800786 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700787 need_to_compile = false;
788 should_clear_current_profiles = false;
789 should_clear_reference_profile = false;
790 break;
791 default:
792 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800793 LOG(WARNING) << "Unknown error code while processing profiles for location "
794 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700795 need_to_compile = false;
796 should_clear_current_profiles = true;
797 should_clear_reference_profile = true;
798 break;
799 }
800 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800801
Jeff Sharkey90aff262016-12-12 14:28:24 -0700802 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800803 if (is_secondary_dex) {
804 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800805 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
806 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800807 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800808 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800809 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700810 }
811 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800812 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700813 }
814 return need_to_compile;
815}
816
Calin Juravle114f0812017-03-08 19:05:07 -0800817// Decides if profile guided compilation is needed or not based on existing profiles.
818// The analysis is done for the primary apks of the given package.
819// Returns true if there is enough information in the current profiles that makes it
820// worth to recompile the package.
821// If the return value is true all the current profiles would have been merged into
822// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800823bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
824 const std::string& profile_name) {
825 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800826}
827
Calin Juravle408cd4a2018-01-20 23:34:18 -0800828bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
829 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800830 std::vector<unique_fd> profile_fds;
831 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800832 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
833 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700834
Calin Juravle408cd4a2018-01-20 23:34:18 -0800835 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800836 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700837
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800838 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700839 const bool has_profiles = !profile_fds.empty();
840
841 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800842 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700843 return false;
844 }
845
Calin Juravle114f0812017-03-08 19:05:07 -0800846 unique_fd output_fd(open(out_file_name.c_str(),
847 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700848 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800849 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 return false;
851 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800852
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800854 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800855 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
856 if (apk_fd == -1) {
857 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
858 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700859 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800860 dex_locations.push_back(get_location_from_path(code_path.c_str()));
861 apk_fds.push_back(std::move(apk_fd));
862
Jeff Sharkey90aff262016-12-12 14:28:24 -0700863
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800864 RunProfman profman_dump;
865 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700866 pid_t pid = fork();
867 if (pid == 0) {
868 /* child -- drop privileges before continuing */
869 drop_capabilities(uid);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800870 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 }
872 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873 int return_code = wait_child(pid);
874 if (!WIFEXITED(return_code)) {
875 LOG(WARNING) << "profman failed for package " << pkgname << ": "
876 << return_code;
877 return false;
878 }
879 return true;
880}
881
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700882bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800883 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700884 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
885 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800886 package_name,
887 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700888 /*read_write*/ true,
889 /*secondary*/ false));
890 if (in_fd.get() < 0) {
891 PLOG(WARNING) << "Could not open profile " << system_profile;
892 return false;
893 }
894 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800895 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700896 return false;
897 }
898
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700899 // As a security measure we want to write the profile information with the reduced capabilities
900 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700901 pid_t pid = fork();
902 if (pid == 0) {
903 /* child -- drop privileges before continuing */
904 drop_capabilities(packageUid);
905
906 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
907 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800908 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700909 }
910 // This implies that the app owning this profile is running
911 // (and has acquired the lock).
912 //
913 // The app never acquires the lock for the reference profiles of primary apks.
914 // Only dex2oat from installd will do that. Since installd is single threaded
915 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800916 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700917 return false;
918 }
919
920 bool truncated = ftruncate(out_fd.get(), 0) == 0;
921 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800922 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700923 }
924
925 // Copy over data.
926 static constexpr size_t kBufferSize = 4 * 1024;
927 char buffer[kBufferSize];
928 while (true) {
929 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
930 if (bytes == 0) {
931 break;
932 }
933 write(out_fd.get(), buffer, bytes);
934 }
935 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800936 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700937 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700938 // Use _exit since we don't want to run the global destructors in the child.
939 // b/62597429
940 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700941 }
942 /* parent */
943 int return_code = wait_child(pid);
944 return return_code == 0;
945}
946
Jeff Sharkey90aff262016-12-12 14:28:24 -0700947static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
948 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
949 if (EndsWith(oat_path, ".dex")) {
950 std::string new_path = oat_path;
951 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800952 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700953 return new_path;
954 }
955
956 // An odex entry. Not that this may not be an extension, e.g., in the OTA
957 // case (where the base name will have an extension for the B artifact).
958 size_t odex_pos = oat_path.rfind(".odex");
959 if (odex_pos != std::string::npos) {
960 std::string new_path = oat_path;
961 new_path.replace(odex_pos, strlen(".odex"), new_ext);
962 CHECK_NE(new_path.find(new_ext), std::string::npos);
963 return new_path;
964 }
965
966 // Don't know how to handle this.
967 return "";
968}
969
970// Translate the given oat path to an art (app image) path. An empty string
971// denotes an error.
972static std::string create_image_filename(const std::string& oat_path) {
973 return replace_file_extension(oat_path, ".art");
974}
975
976// Translate the given oat path to a vdex path. An empty string denotes an error.
977static std::string create_vdex_filename(const std::string& oat_path) {
978 return replace_file_extension(oat_path, ".vdex");
979}
980
Jeff Sharkey90aff262016-12-12 14:28:24 -0700981static int open_output_file(const char* file_name, bool recreate, int permissions) {
982 int flags = O_RDWR | O_CREAT;
983 if (recreate) {
984 if (unlink(file_name) < 0) {
985 if (errno != ENOENT) {
986 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
987 }
988 }
989 flags |= O_EXCL;
990 }
991 return open(file_name, flags, permissions);
992}
993
Calin Juravle2289c0a2017-02-15 12:44:14 -0800994static bool set_permissions_and_ownership(
995 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
996 // Primary apks are owned by the system. Secondary dex files are owned by the app.
997 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700998 if (fchmod(fd,
999 S_IRUSR|S_IWUSR|S_IRGRP |
1000 (is_public ? S_IROTH : 0)) < 0) {
1001 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1002 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001003 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1005 return false;
1006 }
1007 return true;
1008}
1009
1010static bool IsOutputDalvikCache(const char* oat_dir) {
1011 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1012 // into '!'. Play it safe by handling it both.
1013 // TODO: ensure we never get null.
1014 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1015 return oat_dir == nullptr || oat_dir[0] == '!';
1016}
1017
Calin Juravled23dee72017-07-06 16:29:11 -07001018// Best-effort check whether we can fit the the path into our buffers.
1019// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1020// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1021// extension to the cache path (5 bytes).
1022// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1023static bool validate_dex_path_size(const std::string& dex_path) {
1024 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1025 LOG(ERROR) << "dex_path too long: " << dex_path;
1026 return false;
1027 }
1028 return true;
1029}
1030
Jeff Sharkey90aff262016-12-12 14:28:24 -07001031static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001032 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001033 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001034 return false;
1035 }
1036
1037 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001038 // Oat dirs for secondary dex files are already validated.
1039 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001040 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1041 return false;
1042 }
1043 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1044 return false;
1045 }
1046 } else {
1047 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1048 return false;
1049 }
1050 }
1051 return true;
1052}
1053
1054// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1055// on destruction. It will also run the given cleanup (unless told not to) after closing.
1056//
1057// Usage example:
1058//
Calin Juravle7a570e82017-01-14 16:23:30 -08001059// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001060// [name]() {
1061// unlink(name.c_str());
1062// });
1063// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1064// wrapper if captured as a reference.
1065//
1066// if (file.get() == -1) {
1067// // Error opening...
1068// }
1069//
1070// ...
1071// if (error) {
1072// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1073// // and delete the file (after the fd is closed).
1074// return -1;
1075// }
1076//
1077// (Success case)
1078// file.SetCleanup(false);
1079// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1080// // (leaving the file around; after the fd is closed).
1081//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001082class Dex2oatFileWrapper {
1083 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001084 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085 }
1086
Calin Juravle7a570e82017-01-14 16:23:30 -08001087 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1088 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1089
1090 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1091 value_ = other.value_;
1092 cleanup_ = other.cleanup_;
1093 do_cleanup_ = other.do_cleanup_;
1094 auto_close_ = other.auto_close_;
1095 other.release();
1096 }
1097
1098 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1099 value_ = other.value_;
1100 cleanup_ = other.cleanup_;
1101 do_cleanup_ = other.do_cleanup_;
1102 auto_close_ = other.auto_close_;
1103 other.release();
1104 return *this;
1105 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001106
1107 ~Dex2oatFileWrapper() {
1108 reset(-1);
1109 }
1110
1111 int get() {
1112 return value_;
1113 }
1114
1115 void SetCleanup(bool cleanup) {
1116 do_cleanup_ = cleanup;
1117 }
1118
1119 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001120 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 close(value_);
1122 }
1123 if (do_cleanup_ && cleanup_ != nullptr) {
1124 cleanup_();
1125 }
1126
1127 value_ = new_value;
1128 }
1129
Calin Juravle7a570e82017-01-14 16:23:30 -08001130 void reset(int new_value, std::function<void ()> new_cleanup) {
1131 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132 close(value_);
1133 }
1134 if (do_cleanup_ && cleanup_ != nullptr) {
1135 cleanup_();
1136 }
1137
1138 value_ = new_value;
1139 cleanup_ = new_cleanup;
1140 }
1141
Calin Juravle7a570e82017-01-14 16:23:30 -08001142 void DisableAutoClose() {
1143 auto_close_ = false;
1144 }
1145
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001147 void release() {
1148 value_ = -1;
1149 do_cleanup_ = false;
1150 cleanup_ = nullptr;
1151 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001152 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001153 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001154 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001155 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001156};
1157
Calin Juravle7a570e82017-01-14 16:23:30 -08001158// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001159Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1160 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001161
1162 // We don't create an image for secondary dex files.
1163 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 return Dex2oatFileWrapper();
1165 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001166
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 const std::string image_path = create_image_filename(out_oat_path);
1168 if (image_path.empty()) {
1169 // Happens when the out_oat_path has an unknown extension.
1170 return Dex2oatFileWrapper();
1171 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001172
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001173 // In case there is a stale image, remove it now. Ignore any error.
1174 unlink(image_path.c_str());
1175
1176 // Not enabled, exit.
1177 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001178 return Dex2oatFileWrapper();
1179 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001180 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1181 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001182 return Dex2oatFileWrapper();
1183 }
1184 // Recreate is true since we do not want to modify a mapped image. If the app is
1185 // already running and we modify the image file, it can cause crashes (b/27493510).
1186 Dex2oatFileWrapper wrapper_fd(
1187 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1188 [image_path]() { unlink(image_path.c_str()); });
1189 if (wrapper_fd.get() < 0) {
1190 // Could not create application image file. Go on since we can compile without it.
1191 LOG(ERROR) << "installd could not create '" << image_path
1192 << "' for image file during dexopt";
1193 // If we have a valid image file path but no image fd, explicitly erase the image file.
1194 if (unlink(image_path.c_str()) < 0) {
1195 if (errno != ENOENT) {
1196 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1197 }
1198 }
1199 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001200 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1202 wrapper_fd.reset(-1);
1203 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001204
Calin Juravle7a570e82017-01-14 16:23:30 -08001205 return wrapper_fd;
1206}
1207
1208// Creates the dexopt swap file if necessary and return its fd.
1209// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001210unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001211 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001212 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001214 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001215 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001216 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 if (swap_fd.get() < 0) {
1218 // Could not create swap file. Optimistically go on and hope that we can compile
1219 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001220 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001221 } else {
1222 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001223 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001224 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1225 }
1226 }
1227 return swap_fd;
1228}
1229
1230// Opens the reference profiles if needed.
1231// 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 -08001232Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001233 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001234 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001235 // If we are not profile guided compilation, or we are compiling system server
1236 // do not bother to open the profiles; we won't be using them.
1237 if (!profile_guided || (pkgname[0] == '*')) {
1238 return Dex2oatFileWrapper();
1239 }
1240
1241 // If this is a secondary dex path which is public do not open the profile.
1242 // We cannot compile public secondary dex paths with profiles. That's because
1243 // it will expose how the dex files are used by their owner.
1244 //
1245 // Note that the PackageManager is responsible to set the is_public flag for
1246 // primary apks and we do not check it here. In some cases, e.g. when
1247 // compiling with a public profile from the .dm file the PackageManager will
1248 // set is_public toghether with the profile guided compilation.
1249 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001250 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001251 }
Calin Juravle114f0812017-03-08 19:05:07 -08001252
1253 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001254 std::string location;
1255 if (is_secondary_dex) {
1256 location = dex_path;
1257 } else {
1258 if (profile_name == nullptr) {
1259 // This path is taken for system server re-compilation lunched from ZygoteInit.
1260 return Dex2oatFileWrapper();
1261 } else {
1262 location = profile_name;
1263 }
1264 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001265 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1266 is_secondary_dex);
1267 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1268 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001269 };
1270 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001271}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001272
Calin Juravle7a570e82017-01-14 16:23:30 -08001273// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1274// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001275bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001276 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001277 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001278 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1279 CHECK(in_vdex_wrapper_fd != nullptr);
1280 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001281 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1282 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001283 char in_odex_path[PKG_PATH_MAX];
1284 int dexopt_action = abs(dexopt_needed);
1285 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001286 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001287
1288 // Infer the name of the output VDEX.
1289 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1290 if (out_vdex_path_str.empty()) {
1291 return false;
1292 }
1293
1294 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001295 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001296 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1297 const char* path = nullptr;
1298 if (is_odex_location) {
1299 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1300 path = in_odex_path;
1301 } else {
1302 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001303 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001304 }
1305 } else {
1306 path = out_oat_path;
1307 }
1308 in_vdex_path_str = create_vdex_filename(path);
1309 if (in_vdex_path_str.empty()) {
1310 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001311 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001312 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001313 // We can update in place when all these conditions are met:
1314 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1315 // on /system typically cannot be updated in place).
1316 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1317 // cannot be currently used by a running process.
1318 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1319 // different vdex files to operate.
1320 update_vdex_in_place =
1321 (in_vdex_path_str == out_vdex_path_str) &&
1322 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1323 !profile_guided;
1324 if (update_vdex_in_place) {
1325 // Open the file read-write to be able to update it.
1326 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1327 if (in_vdex_wrapper_fd->get() == -1) {
1328 // If we failed to open the file, we cannot update it in place.
1329 update_vdex_in_place = false;
1330 }
1331 } else {
1332 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1333 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001334 }
1335
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001336 // If we are updating the vdex in place, we do not need to recreate a vdex,
1337 // and can use the same existing one.
1338 if (update_vdex_in_place) {
1339 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1340 // have bogus stale vdex files.
1341 out_vdex_wrapper_fd->reset(
1342 in_vdex_wrapper_fd->get(),
1343 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1344 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1345 // wrapper).
1346 in_vdex_wrapper_fd->DisableAutoClose();
1347 } else {
1348 out_vdex_wrapper_fd->reset(
1349 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1350 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1351 if (out_vdex_wrapper_fd->get() < 0) {
1352 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1353 return false;
1354 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001355 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001356 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001357 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001358 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1359 return false;
1360 }
1361
1362 // If we got here we successfully opened the vdex files.
1363 return true;
1364}
1365
1366// Opens the output oat file for the given apk.
1367// If successful it stores the output path into out_oat_path and returns true.
1368Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001369 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1370 char* out_oat_path) {
1371 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001372 return Dex2oatFileWrapper();
1373 }
1374 const std::string out_oat_path_str(out_oat_path);
1375 Dex2oatFileWrapper wrapper_fd(
1376 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1377 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1378 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001379 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001380 } else if (!set_permissions_and_ownership(
1381 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001382 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1383 wrapper_fd.reset(-1);
1384 }
1385 return wrapper_fd;
1386}
1387
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001388// Creates RDONLY fds for oat and vdex files, if exist.
1389// Returns false if it fails to create oat out path for the given apk path.
1390// Note that the method returns true even if the files could not be opened.
1391bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1392 const std::string& oat_dir,
1393 const std::string& instruction_set,
1394 bool is_secondary_dex,
1395 unique_fd* oat_file_fd,
1396 unique_fd* vdex_file_fd) {
1397 char oat_path[PKG_PATH_MAX];
1398 if (!create_oat_out_path(apk_path.c_str(),
1399 instruction_set.c_str(),
1400 oat_dir.c_str(),
1401 is_secondary_dex,
1402 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001403 LOG(ERROR) << "Could not create oat out path for "
1404 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001405 return false;
1406 }
1407 oat_file_fd->reset(open(oat_path, O_RDONLY));
1408 if (oat_file_fd->get() < 0) {
1409 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1410 }
1411
1412 std::string vdex_filename = create_vdex_filename(oat_path);
1413 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1414 if (vdex_file_fd->get() < 0) {
1415 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1416 }
1417
1418 return true;
1419}
1420
Calin Juravle7a570e82017-01-14 16:23:30 -08001421// Updates the access times of out_oat_path based on those from apk_path.
1422void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1423 struct stat input_stat;
1424 memset(&input_stat, 0, sizeof(input_stat));
1425 if (stat(apk_path, &input_stat) != 0) {
1426 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1427 return;
1428 }
1429
1430 struct utimbuf ut;
1431 ut.actime = input_stat.st_atime;
1432 ut.modtime = input_stat.st_mtime;
1433 if (utime(out_oat_path, &ut) != 0) {
1434 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1435 }
1436}
1437
Calin Juravle80a21252017-01-17 14:43:25 -08001438// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001439// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1440// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1441// the profile has changed.
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001442class RunDexoptAnalyzer : public ExecVHelper {
1443 public:
1444 RunDexoptAnalyzer(const std::string& dex_file,
1445 int vdex_fd,
1446 int oat_fd,
1447 int zip_fd,
1448 const std::string& instruction_set,
1449 const std::string& compiler_filter,
1450 bool profile_was_updated,
1451 bool downgrade,
1452 const char* class_loader_context) {
1453 CHECK_GE(zip_fd, 0);
1454 const char* dexoptanalyzer_bin =
1455 is_debug_runtime()
1456 ? "/system/bin/dexoptanalyzerd"
1457 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001458
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001459 std::string dex_file_arg = "--dex-file=" + dex_file;
1460 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1461 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1462 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1463 std::string isa_arg = "--isa=" + instruction_set;
1464 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1465 const char* assume_profile_changed = "--assume-profile-changed";
1466 const char* downgrade_flag = "--downgrade";
1467 std::string class_loader_context_arg = "--class-loader-context=";
1468 if (class_loader_context != nullptr) {
1469 class_loader_context_arg += class_loader_context;
1470 }
Calin Juravle80a21252017-01-17 14:43:25 -08001471
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001472 // program name, dex file, isa, filter
1473 AddArg(dex_file_arg);
1474 AddArg(isa_arg);
1475 AddArg(compiler_filter_arg);
1476 if (oat_fd >= 0) {
1477 AddArg(oat_fd_arg);
1478 }
1479 if (vdex_fd >= 0) {
1480 AddArg(vdex_fd_arg);
1481 }
1482 AddArg(zip_fd_arg.c_str());
1483 if (profile_was_updated) {
1484 AddArg(assume_profile_changed);
1485 }
1486 if (downgrade) {
1487 AddArg(downgrade_flag);
1488 }
1489 if (class_loader_context != nullptr) {
1490 AddArg(class_loader_context_arg.c_str());
1491 }
Calin Juravle80a21252017-01-17 14:43:25 -08001492
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001493 PrepareArgs(dexoptanalyzer_bin);
1494 }
1495};
Calin Juravle80a21252017-01-17 14:43:25 -08001496
1497// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001498static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001499 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001500 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001501 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001502 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001503 return false;
1504 }
Calin Juravle114f0812017-03-08 19:05:07 -08001505 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001506
Calin Juravle80a21252017-01-17 14:43:25 -08001507 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001508 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1509 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001510 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001511 return false;
1512 }
1513
1514 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001515 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001516
Calin Juravle7d765462017-09-04 15:57:10 -07001517 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001518 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001519 return false;
1520 }
1521
1522 return true;
1523}
1524
Calin Juravle7d765462017-09-04 15:57:10 -07001525// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1526// secondary dex files. This return codes are returned by the child process created for
1527// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001528
Andreas Gampe194fe422018-02-28 20:16:19 -08001529enum DexoptAnalyzerSkipCodes {
1530 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001531 // Specific errors are encoded in the name.
1532 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1533 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1534 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1535 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1536 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001537 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001538 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001539};
Calin Juravle7d765462017-09-04 15:57:10 -07001540
1541// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001542// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1543// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001544// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1545// of dexoptanalyzer.
1546static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001547 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001548 // The result values are defined in dexoptanalyzer.
1549 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001550 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001551 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001552 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001553 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001554 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001555 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001556 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001557 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001558 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1559 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001560 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1561 " Expected odex file status for secondary dex %s"
1562 " : dexoptanalyzer result=%d",
1563 dex_path.c_str(),
1564 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001565 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001566 }
1567
1568 // Use a second switch for enum switch-case analysis.
1569 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001570 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001571 // If the file does not exist there's no need for dexopt.
1572 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1573 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001574
1575 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1576 *error_msg = "Dexoptanalyzer path validation failed";
1577 return false;
1578 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1579 *error_msg = "Dexoptanalyzer open zip failed";
1580 return false;
1581 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1582 *error_msg = "Dexoptanalyzer dir preparation failed";
1583 return false;
1584 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1585 *error_msg = "Dexoptanalyzer open output failed";
1586 return false;
1587 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1588 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001589 return false;
1590 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001591
1592 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1593 dex_path.c_str(),
1594 result);
1595 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001596}
1597
Calin Juravle7d765462017-09-04 15:57:10 -07001598enum SecondaryDexAccess {
1599 kSecondaryDexAccessReadOk = 0,
1600 kSecondaryDexAccessDoesNotExist = 1,
1601 kSecondaryDexAccessPermissionError = 2,
1602 kSecondaryDexAccessIOError = 3
1603};
1604
1605static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1606 // Check if the path exists and can be read. If not, there's nothing to do.
1607 if (access(dex_path.c_str(), R_OK) == 0) {
1608 return kSecondaryDexAccessReadOk;
1609 } else {
1610 if (errno == ENOENT) {
1611 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1612 return kSecondaryDexAccessDoesNotExist;
1613 } else {
1614 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1615 return errno == EACCES
1616 ? kSecondaryDexAccessPermissionError
1617 : kSecondaryDexAccessIOError;
1618 }
1619 }
1620}
1621
1622static bool is_file_public(const std::string& filename) {
1623 struct stat file_stat;
1624 if (stat(filename.c_str(), &file_stat) == 0) {
1625 return (file_stat.st_mode & S_IROTH) != 0;
1626 }
1627 return false;
1628}
1629
1630// Create the oat file structure for the secondary dex 'dex_path' and assign
1631// the individual path component to the 'out_' parameters.
1632static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001633 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001634 size_t dirIndex = dex_path.rfind('/');
1635 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001636 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001637 return false;
1638 }
1639 // TODO(calin): we have similar computations in at lest 3 other places
1640 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1641 // using string append.
1642 std::string apk_dir = dex_path.substr(0, dirIndex);
1643 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1644 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1645
1646 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1647 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001648 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001649 return false;
1650 }
1651 return true;
1652}
1653
1654// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1655// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001656static bool validate_dexopt_storage_flags(int dexopt_flags,
1657 int* out_storage_flag,
1658 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001659 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1660 *out_storage_flag = FLAG_STORAGE_CE;
1661 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001662 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001663 return false;
1664 }
1665 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1666 *out_storage_flag = FLAG_STORAGE_DE;
1667 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001668 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001669 return false;
1670 }
1671 return true;
1672}
1673
Calin Juravlec9eab382017-01-25 01:17:17 -08001674// 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 -08001675// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1676// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001677// When returning true, the output parameters will be:
1678// - is_public_out: whether or not the oat file should not be made public
1679// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1680// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001681static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001682 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001683 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001684 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1685 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001686 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001687 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001688 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1689 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001690 return false;
1691 }
Calin Juravle7d765462017-09-04 15:57:10 -07001692 // Compute the oat dir as it's not easy to extract it from the child computation.
1693 char oat_path[PKG_PATH_MAX];
1694 char oat_dir[PKG_PATH_MAX];
1695 char oat_isa_dir[PKG_PATH_MAX];
1696 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001697 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1698 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001699 return false;
1700 }
Calin Juravle7d765462017-09-04 15:57:10 -07001701 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001702
Calin Juravle80a21252017-01-17 14:43:25 -08001703 pid_t pid = fork();
1704 if (pid == 0) {
1705 // child -- drop privileges before continuing.
1706 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001707
1708 // Validate the path structure.
1709 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1710 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001711 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001712 }
1713
1714 // Open the dex file.
1715 unique_fd zip_fd;
1716 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1717 if (zip_fd.get() < 0) {
1718 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001719 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001720 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001721 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001722 }
1723 }
1724
1725 // Prepare the oat directories.
1726 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001727 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001728 }
1729
1730 // Open the vdex/oat files if any.
1731 unique_fd oat_file_fd;
1732 unique_fd vdex_file_fd;
1733 if (!maybe_open_oat_and_vdex_file(dex_path,
1734 *oat_dir_out,
1735 instruction_set,
1736 true /* is_secondary_dex */,
1737 &oat_file_fd,
1738 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001739 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001740 }
1741
1742 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001743 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1744 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001745
1746 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001747 // Note that we do not do it before the fork since opening the files is required to happen
1748 // after forking.
1749 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1750 vdex_file_fd.get(),
1751 oat_file_fd.get(),
1752 zip_fd.get(),
1753 instruction_set,
1754 compiler_filter, profile_was_updated,
1755 downgrade,
1756 class_loader_context);
1757 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001758 }
1759
1760 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001761 int result = wait_child(pid);
1762 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001763 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1764 dex_path.c_str(),
1765 result);
1766 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001767 return false;
1768 }
1769 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001770 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001771 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1772 result,
1773 dexopt_needed_out,
1774 error_msg);
1775 if (!success) {
1776 LOG(ERROR) << *error_msg;
1777 }
Calin Juravle7d765462017-09-04 15:57:10 -07001778
1779 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1780
Calin Juravle80a21252017-01-17 14:43:25 -08001781 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001782 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1783 // makes the code simpler; force compilation is only needed during tests).
1784 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001785 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001786 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001787 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1788 }
1789
Calin Juravle7d765462017-09-04 15:57:10 -07001790 // Check if we should make the oat file public.
1791 // Note that if the dex file is not public the compiled code cannot be made public.
1792 // It is ok to check this flag outside in the parent process.
1793 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1794
Calin Juravle80a21252017-01-17 14:43:25 -08001795 return success;
1796}
1797
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001798static std::string format_dexopt_error(int status, const char* dex_path) {
1799 if (WIFEXITED(status)) {
1800 int int_code = WEXITSTATUS(status);
1801 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1802 if (code_name != nullptr) {
1803 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1804 }
1805 }
1806 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001807}
1808
Calin Juravlec9eab382017-01-25 01:17:17 -08001809int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001810 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001811 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001812 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001813 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001814 CHECK(pkgname != nullptr);
1815 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001816 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001817 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1818 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001819
Calin Juravled23dee72017-07-06 16:29:11 -07001820 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001821 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001822 return -1;
1823 }
1824
1825 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001826 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1827 class_loader_context);
1828 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001829 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001830 }
1831
Calin Juravleebc8a792017-04-04 20:21:05 -07001832 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001833 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1834 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1835 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001836 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001837 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001838 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001839 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001840 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001841
1842 // Check if we're dealing with a secondary dex file and if we need to compile it.
1843 std::string oat_dir_str;
1844 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001845 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001846 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001847 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001848 oat_dir = oat_dir_str.c_str();
1849 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1850 return 0; // Nothing to do, report success.
1851 }
1852 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001853 if (error_msg->empty()) { // TODO: Make this a CHECK.
1854 *error_msg = "Failed processing secondary.";
1855 }
Calin Juravle80a21252017-01-17 14:43:25 -08001856 return -1; // We had an error, logged in the process method.
1857 }
1858 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001859 // Currently these flags are only use for secondary dex files.
1860 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001861 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1862 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1863 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001864
1865 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001866 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001867 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001868 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1869 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001870 return -1;
1871 }
1872
1873 // Create the output OAT file.
1874 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001875 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001876 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001877 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001878 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001879 return -1;
1880 }
1881
1882 // Open vdex files.
1883 Dex2oatFileWrapper in_vdex_fd;
1884 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001885 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1886 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001887 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001888 return -1;
1889 }
1890
Calin Juravlecb556e32017-04-04 20:22:50 -07001891 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1892 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1893 // fully inherit their parent context).
1894 // Note that for primary apk the oat files are created before, in a separate installd
1895 // call which also does the restorecon. TODO(calin): unify the paths.
1896 if (is_secondary_dex) {
1897 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1898 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001899 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1900 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001901 return -1;
1902 }
1903 }
1904
Jeff Sharkey90aff262016-12-12 14:28:24 -07001905 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001906 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001907
Calin Juravle7a570e82017-01-14 16:23:30 -08001908 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001909 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1910 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001911
Calin Juravle7a570e82017-01-14 16:23:30 -08001912 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001913 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001914 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001915
Calin Juravle62c5a372018-02-01 17:03:23 +00001916 unique_fd dex_metadata_fd;
1917 if (dex_metadata_path != nullptr) {
1918 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1919 if (dex_metadata_fd.get() < 0) {
1920 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1921 }
1922 }
1923
Andreas Gampe023b2242018-02-28 16:03:25 -08001924 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001925
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001926 RunDex2Oat runner(input_fd.get(),
1927 out_oat_fd.get(),
1928 in_vdex_fd.get(),
1929 out_vdex_fd.get(),
1930 image_fd.get(),
1931 dex_path,
1932 out_oat_path,
1933 swap_fd.get(),
1934 instruction_set,
1935 compiler_filter,
1936 debuggable,
1937 boot_complete,
1938 background_job_compile,
1939 reference_profile_fd.get(),
1940 class_loader_context,
1941 target_sdk_version,
1942 enable_hidden_api_checks,
1943 generate_compact_dex,
1944 dex_metadata_fd.get(),
1945 compilation_reason);
1946
Jeff Sharkey90aff262016-12-12 14:28:24 -07001947 pid_t pid = fork();
1948 if (pid == 0) {
1949 /* child -- drop privileges before continuing */
1950 drop_capabilities(uid);
1951
Richard Uhler76cc0272016-12-08 10:46:35 +00001952 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001953 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001954 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001955 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001956 }
1957
Mathieu Chartier62d218d2018-11-05 09:34:24 -08001958 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001959 } else {
1960 int res = wait_child(pid);
1961 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001962 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001963 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001964 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1965 << std::hex << std::setw(4) << res << ", process failed";
1966 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001967 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001968 }
1969 }
1970
Calin Juravlec9eab382017-01-25 01:17:17 -08001971 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001972
1973 // We've been successful, don't delete output.
1974 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001975 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001976 image_fd.SetCleanup(false);
1977 reference_profile_fd.SetCleanup(false);
1978
1979 return 0;
1980}
1981
Calin Juravlec9eab382017-01-25 01:17:17 -08001982// Try to remove the given directory. Log an error if the directory exists
1983// and is empty but could not be removed.
1984static bool rmdir_if_empty(const char* dir) {
1985 if (rmdir(dir) == 0) {
1986 return true;
1987 }
1988 if (errno == ENOENT || errno == ENOTEMPTY) {
1989 return true;
1990 }
1991 PLOG(ERROR) << "Failed to remove dir: " << dir;
1992 return false;
1993}
1994
1995// Try to unlink the given file. Log an error if the file exists and could not
1996// be unlinked.
1997static bool unlink_if_exists(const std::string& file) {
1998 if (unlink(file.c_str()) == 0) {
1999 return true;
2000 }
2001 if (errno == ENOENT) {
2002 return true;
2003
2004 }
2005 PLOG(ERROR) << "Could not unlink: " << file;
2006 return false;
2007}
2008
Calin Juravle7d765462017-09-04 15:57:10 -07002009enum ReconcileSecondaryDexResult {
2010 kReconcileSecondaryDexExists = 0,
2011 kReconcileSecondaryDexCleanedUp = 1,
2012 kReconcileSecondaryDexValidationError = 2,
2013 kReconcileSecondaryDexCleanUpError = 3,
2014 kReconcileSecondaryDexAccessIOError = 4,
2015};
Calin Juravlec9eab382017-01-25 01:17:17 -08002016
2017// Reconcile the secondary dex 'dex_path' and its generated oat files.
2018// Return true if all the parameters are valid and the secondary dex file was
2019// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2020// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2021// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2022// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2023// Return false if there were errors during processing. In this case
2024// out_secondary_dex_exists will be set to false.
2025bool reconcile_secondary_dex_file(const std::string& dex_path,
2026 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2027 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2028 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002029 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002030 if (isas.size() == 0) {
2031 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2032 return false;
2033 }
2034
Calin Juravle7d765462017-09-04 15:57:10 -07002035 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2036 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2037 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002038 return false;
2039 }
2040
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002041 // As a security measure we want to unlink art artifacts with the reduced capabilities
2042 // of the package user id. So we fork and drop capabilities in the child.
2043 pid_t pid = fork();
2044 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002045 /* child -- drop privileges before continuing */
2046 drop_capabilities(uid);
2047
2048 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2049 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2050 uid, storage_flag)) {
2051 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2052 _exit(kReconcileSecondaryDexValidationError);
2053 }
2054
2055 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2056 switch (access_check) {
2057 case kSecondaryDexAccessDoesNotExist:
2058 // File does not exist. Proceed with cleaning.
2059 break;
2060 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2061 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2062 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2063 default:
2064 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2065 _exit(kReconcileSecondaryDexValidationError);
2066 }
2067
2068 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002069 char oat_path[PKG_PATH_MAX];
2070 char oat_dir[PKG_PATH_MAX];
2071 char oat_isa_dir[PKG_PATH_MAX];
2072 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002073 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002074 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002075 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002076 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2077 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002078 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002079 }
Calin Juravle51314092017-05-18 15:33:05 -07002080
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002081 // Delete oat/vdex/art files.
2082 result = unlink_if_exists(oat_path) && result;
2083 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2084 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002085
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002086 // Delete profiles.
2087 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002088 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002089 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002090 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002091 result = unlink_if_exists(current_profile) && result;
2092 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002093
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002094 // We upgraded once the location of current profile for secondary dex files.
2095 // Check for any previous left-overs and remove them as well.
2096 std::string old_current_profile = dex_path + ".prof";
2097 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002098
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002099 // Try removing the directories as well, they might be empty.
2100 result = rmdir_if_empty(oat_isa_dir) && result;
2101 result = rmdir_if_empty(oat_dir) && result;
2102 }
Calin Juravle7d765462017-09-04 15:57:10 -07002103 if (!result) {
2104 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2105 }
2106 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002107 }
2108
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002109 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002110 if (!WIFEXITED(return_code)) {
2111 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2112 } else {
2113 return_code = WEXITSTATUS(return_code);
2114 }
2115
2116 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2117
2118 switch (return_code) {
2119 case kReconcileSecondaryDexCleanedUp:
2120 case kReconcileSecondaryDexValidationError:
2121 // If we couldn't validate assume the dex file does not exist.
2122 // This will purge the entry from the PM records.
2123 *out_secondary_dex_exists = false;
2124 return true;
2125 case kReconcileSecondaryDexExists:
2126 *out_secondary_dex_exists = true;
2127 return true;
2128 case kReconcileSecondaryDexAccessIOError:
2129 // We had an access IO error.
2130 // Return false so that we can try again.
2131 // The value of out_secondary_dex_exists does not matter in this case and by convention
2132 // is set to false.
2133 *out_secondary_dex_exists = false;
2134 return false;
2135 default:
2136 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2137 *out_secondary_dex_exists = false;
2138 return false;
2139 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002140}
2141
Alan Stokesa25d90c2017-10-16 10:56:00 +01002142// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2143// Returns true if all parameters are valid and the hash successfully computed and stored in
2144// out_secondary_dex_hash.
2145// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2146// the app.
2147// For any other errors (e.g. if any of the parameters are invalid) returns false.
2148bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2149 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2150 std::vector<uint8_t>* out_secondary_dex_hash) {
2151 out_secondary_dex_hash->clear();
2152
2153 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2154
2155 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2156 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2157 << storage_flag;
2158 return false;
2159 }
2160
2161 // Pipe to get the hash result back from our child process.
2162 unique_fd pipe_read, pipe_write;
2163 if (!Pipe(&pipe_read, &pipe_write)) {
2164 PLOG(ERROR) << "Failed to create pipe";
2165 return false;
2166 }
2167
2168 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2169 // access data the app itself can access.
2170 pid_t pid = fork();
2171 if (pid == 0) {
2172 // child -- drop privileges before continuing
2173 drop_capabilities(uid);
2174 pipe_read.reset();
2175
2176 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2177 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002178 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002179 }
2180
2181 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2182 if (fd == -1) {
2183 if (errno == EACCES || errno == ENOENT) {
2184 // Not treated as an error.
2185 _exit(0);
2186 }
2187 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002188 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002189 }
2190
2191 SHA256_CTX ctx;
2192 SHA256_Init(&ctx);
2193
2194 std::vector<uint8_t> buffer(65536);
2195 while (true) {
2196 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2197 if (bytes_read == 0) {
2198 break;
2199 } else if (bytes_read == -1) {
2200 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002201 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002202 }
2203
2204 SHA256_Update(&ctx, buffer.data(), bytes_read);
2205 }
2206
2207 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2208 SHA256_Final(hash.data(), &ctx);
2209 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002210 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002211 }
2212
2213 _exit(0);
2214 }
2215
2216 // parent
2217 pipe_write.reset();
2218
2219 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2220 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2221 out_secondary_dex_hash->clear();
2222 }
2223 return wait_child(pid) == 0;
2224}
2225
Jeff Sharkey90aff262016-12-12 14:28:24 -07002226// Helper for move_ab, so that we can have common failure-case cleanup.
2227static bool unlink_and_rename(const char* from, const char* to) {
2228 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2229 // return a failure.
2230 struct stat s;
2231 if (stat(to, &s) == 0) {
2232 if (!S_ISREG(s.st_mode)) {
2233 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2234 return false;
2235 }
2236 if (unlink(to) != 0) {
2237 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2238 return false;
2239 }
2240 } else {
2241 // This may be a permission problem. We could investigate the error code, but we'll just
2242 // let the rename failure do the work for us.
2243 }
2244
2245 // Try to rename "to" to "from."
2246 if (rename(from, to) != 0) {
2247 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2248 return false;
2249 }
2250 return true;
2251}
2252
2253// Move/rename a B artifact (from) to an A artifact (to).
2254static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2255 // Check whether B exists.
2256 {
2257 struct stat s;
2258 if (stat(b_path.c_str(), &s) != 0) {
2259 // Silently ignore for now. The service calling this isn't smart enough to understand
2260 // lack of artifacts at the moment.
2261 return false;
2262 }
2263 if (!S_ISREG(s.st_mode)) {
2264 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2265 // Try to unlink, but swallow errors.
2266 unlink(b_path.c_str());
2267 return false;
2268 }
2269 }
2270
2271 // Rename B to A.
2272 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2273 // Delete the b_path so we don't try again (or fail earlier).
2274 if (unlink(b_path.c_str()) != 0) {
2275 PLOG(ERROR) << "Could not unlink " << b_path;
2276 }
2277
2278 return false;
2279 }
2280
2281 return true;
2282}
2283
2284bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2285 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002286 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2287 if (slot_suffix.empty()) {
2288 return false;
2289 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002290
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002291 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2292 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2293 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002294 }
2295
2296 // Validate other inputs.
2297 if (validate_apk_path(apk_path) != 0) {
2298 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2299 return false;
2300 }
2301 if (validate_apk_path(oat_dir) != 0) {
2302 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2303 return false;
2304 }
2305
2306 char a_path[PKG_PATH_MAX];
2307 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2308 return false;
2309 }
2310 const std::string a_vdex_path = create_vdex_filename(a_path);
2311 const std::string a_image_path = create_image_filename(a_path);
2312
2313 // B path = A path + slot suffix.
2314 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2315 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2316 const std::string b_image_path = StringPrintf("%s.%s",
2317 a_image_path.c_str(),
2318 slot_suffix.c_str());
2319
2320 bool success = true;
2321 if (move_ab_path(b_path, a_path)) {
2322 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2323 // Note: we can live without an app image. As such, ignore failure to move the image file.
2324 // If we decide to require the app image, or the app image being moved correctly,
2325 // then change accordingly.
2326 constexpr bool kIgnoreAppImageFailure = true;
2327
2328 if (!a_image_path.empty()) {
2329 if (!move_ab_path(b_image_path, a_image_path)) {
2330 unlink(a_image_path.c_str());
2331 if (!kIgnoreAppImageFailure) {
2332 success = false;
2333 }
2334 }
2335 }
2336 } else {
2337 // Cleanup: delete B image, ignore errors.
2338 unlink(b_image_path.c_str());
2339 success = false;
2340 }
2341 } else {
2342 // Cleanup: delete B image, ignore errors.
2343 unlink(b_vdex_path.c_str());
2344 unlink(b_image_path.c_str());
2345 success = false;
2346 }
2347 return success;
2348}
2349
2350bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2351 // Delete the oat/odex file.
2352 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002353 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002354 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002355 return false;
2356 }
2357
2358 // In case of a permission failure report the issue. Otherwise just print a warning.
2359 auto unlink_and_check = [](const char* path) -> bool {
2360 int result = unlink(path);
2361 if (result != 0) {
2362 if (errno == EACCES || errno == EPERM) {
2363 PLOG(ERROR) << "Could not unlink " << path;
2364 return false;
2365 }
2366 PLOG(WARNING) << "Could not unlink " << path;
2367 }
2368 return true;
2369 };
2370
2371 // Delete the oat/odex file.
2372 bool return_value_oat = unlink_and_check(out_path);
2373
2374 // Derive and delete the app image.
2375 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2376
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002377 // Derive and delete the vdex file.
2378 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2379
Jeff Sharkey90aff262016-12-12 14:28:24 -07002380 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002381 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002382}
2383
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002384static bool is_absolute_path(const std::string& path) {
2385 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2386 LOG(ERROR) << "Invalid absolute path " << path;
2387 return false;
2388 } else {
2389 return true;
2390 }
2391}
2392
2393static bool is_valid_instruction_set(const std::string& instruction_set) {
2394 // TODO: add explicit whitelisting of instruction sets
2395 if (instruction_set.find('/') != std::string::npos) {
2396 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2397 return false;
2398 } else {
2399 return true;
2400 }
2401}
2402
2403bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2404 const char *apk_path, const char *instruction_set) {
2405 std::string oat_dir_ = oat_dir;
2406 std::string apk_path_ = apk_path;
2407 std::string instruction_set_ = instruction_set;
2408
2409 if (!is_absolute_path(oat_dir_)) return false;
2410 if (!is_absolute_path(apk_path_)) return false;
2411 if (!is_valid_instruction_set(instruction_set_)) return false;
2412
2413 std::string::size_type end = apk_path_.rfind('.');
2414 std::string::size_type start = apk_path_.rfind('/', end);
2415 if (end == std::string::npos || start == std::string::npos) {
2416 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2417 return false;
2418 }
2419
2420 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2421 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2422 const char* res = res_.c_str();
2423 if (strlen(res) >= PKG_PATH_MAX) {
2424 LOG(ERROR) << "Result too large";
2425 return false;
2426 } else {
2427 strlcpy(path, res, PKG_PATH_MAX);
2428 return true;
2429 }
2430}
2431
2432bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2433 const char *instruction_set) {
2434 std::string apk_path_ = apk_path;
2435 std::string instruction_set_ = instruction_set;
2436
2437 if (!is_absolute_path(apk_path_)) return false;
2438 if (!is_valid_instruction_set(instruction_set_)) return false;
2439
2440 std::string::size_type end = apk_path_.rfind('.');
2441 std::string::size_type start = apk_path_.rfind('/', end);
2442 if (end == std::string::npos || start == std::string::npos) {
2443 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2444 return false;
2445 }
2446
2447 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2448 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2449}
2450
2451bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2452 const char *instruction_set) {
2453 std::string src_ = src;
2454 std::string instruction_set_ = instruction_set;
2455
2456 if (!is_absolute_path(src_)) return false;
2457 if (!is_valid_instruction_set(instruction_set_)) return false;
2458
2459 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2460 if (*it == '/') {
2461 *it = '@';
2462 }
2463 }
2464
2465 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2466 + DALVIK_CACHE_POSTFIX;
2467 const char* res = res_.c_str();
2468 if (strlen(res) >= PKG_PATH_MAX) {
2469 LOG(ERROR) << "Result too large";
2470 return false;
2471 } else {
2472 strlcpy(path, res, PKG_PATH_MAX);
2473 return true;
2474 }
2475}
2476
Calin Juravle59f7ab82018-04-27 17:50:23 -07002477bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2478 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002479 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2480 for (const std::string& elem : classpaths_elems) {
2481 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2482 if (fd < 0) {
2483 PLOG(ERROR) << "Could not open classpath elem " << elem;
2484 return false;
2485 } else {
2486 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002487 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002488 }
2489 }
2490 return true;
2491}
2492
2493static bool create_app_profile_snapshot(int32_t app_id,
2494 const std::string& package_name,
2495 const std::string& profile_name,
2496 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002497 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2498
Calin Juravle824a64d2018-01-18 20:23:17 -08002499 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002500 if (snapshot_fd < 0) {
2501 return false;
2502 }
2503
2504 std::vector<unique_fd> profiles_fd;
2505 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002506 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2507 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002508 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2509 return false;
2510 }
2511
2512 profiles_fd.push_back(std::move(reference_profile_fd));
2513
Calin Juravle0d0a4922018-01-23 19:54:11 -08002514 // Open the class paths elements. These will be used to filter out profile data that does
2515 // not belong to the classpath during merge.
2516 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002517 std::vector<std::string> dex_locations;
2518 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002519 return false;
2520 }
2521
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002522 RunProfman args;
2523 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002524 pid_t pid = fork();
2525 if (pid == 0) {
2526 /* child -- drop privileges before continuing */
2527 drop_capabilities(app_shared_gid);
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002528 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002529 }
2530
2531 /* parent */
2532 int return_code = wait_child(pid);
2533 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002534 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002535 return false;
2536 }
2537
2538 return true;
2539}
2540
Calin Juravle0d0a4922018-01-23 19:54:11 -08002541static bool create_boot_image_profile_snapshot(const std::string& package_name,
2542 const std::string& profile_name,
2543 const std::string& classpath) {
2544 // The reference profile directory for the android package might not be prepared. Do it now.
2545 const std::string ref_profile_dir =
2546 create_primary_reference_profile_package_dir_path(package_name);
2547 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2548 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2549 return false;
2550 }
2551
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002552 // Return false for empty class path since it may otherwise return true below if profiles is
2553 // empty.
2554 if (classpath.empty()) {
2555 PLOG(ERROR) << "Class path is empty";
2556 return false;
2557 }
2558
Calin Juravle0d0a4922018-01-23 19:54:11 -08002559 // Open and create the snapshot profile.
2560 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2561
2562 // Collect all non empty profiles.
2563 // The collection will traverse all applications profiles and find the non empty files.
2564 // This has the potential of inspecting a large number of files and directories (depending
2565 // on the number of applications and users). So there is a slight increase in the chance
2566 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2567 // fail the snapshot and aggregate whatever profile we could open.
2568 //
2569 // The profile snapshot is a best effort based on available data it's ok if some data
2570 // from some apps is missing. It will be counter productive for the snapshot to fail
2571 // because we could not open or read some of the files.
2572 std::vector<std::string> profiles;
2573 if (!collect_profiles(&profiles)) {
2574 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2575 }
2576
2577 // If we have no profiles return early.
2578 if (profiles.empty()) {
2579 return true;
2580 }
2581
2582 // Open the classpath elements. These will be used to filter out profile data that does
2583 // not belong to the classpath during merge.
2584 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002585 std::vector<std::string> dex_locations;
2586 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002587 return false;
2588 }
2589
2590 // If we could not open any files from the classpath return an error.
2591 if (apk_fds.empty()) {
2592 LOG(ERROR) << "Could not open any of the classpath elements.";
2593 return false;
2594 }
2595
2596 // Aggregate the profiles in batches of kAggregationBatchSize.
2597 // We do this to avoid opening a huge a amount of files.
2598 static constexpr size_t kAggregationBatchSize = 10;
2599
2600 std::vector<unique_fd> profiles_fd;
2601 for (size_t i = 0; i < profiles.size(); ) {
2602 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2603 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2604 if (fd.get() >= 0) {
2605 profiles_fd.push_back(std::move(fd));
2606 }
2607 }
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002608 RunProfman args;
2609 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002610 pid_t pid = fork();
2611 if (pid == 0) {
2612 /* child -- drop privileges before continuing */
2613 drop_capabilities(AID_SYSTEM);
2614
Calin Juravle59f7ab82018-04-27 17:50:23 -07002615 // The introduction of new access flags into boot jars causes them to
2616 // fail dex file verification.
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002617 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002618 }
2619
2620 /* parent */
2621 int return_code = wait_child(pid);
2622 if (!WIFEXITED(return_code)) {
2623 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2624 return false;
2625 }
2626 return true;
2627 }
2628 return true;
2629}
2630
2631bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2632 const std::string& profile_name, const std::string& classpath) {
2633 if (app_id == -1) {
2634 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2635 } else {
2636 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2637 }
2638}
2639
Calin Juravlec3b049e2018-01-18 22:32:58 -08002640bool prepare_app_profile(const std::string& package_name,
2641 userid_t user_id,
2642 appid_t app_id,
2643 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002644 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002645 const std::unique_ptr<std::string>& dex_metadata) {
2646 // Prepare the current profile.
2647 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2648 /*is_secondary_dex*/ false);
2649 uid_t uid = multiuser_get_uid(user_id, app_id);
2650 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2651 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2652 return false;
2653 }
2654
2655 // Check if we need to install the profile from the dex metadata.
2656 if (dex_metadata == nullptr) {
2657 return true;
2658 }
2659
2660 // We have a dex metdata. Merge the profile into the reference profile.
2661 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2662 /*read_write*/ true, /*is_secondary_dex*/ false);
2663 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2664 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002665 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2666 if (apk_fd < 0) {
2667 PLOG(ERROR) << "Could not open code path " << code_path;
2668 return false;
2669 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002670
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002671 RunProfman args;
2672 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2673 std::move(ref_profile_fd),
2674 std::move(apk_fd),
2675 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002676 pid_t pid = fork();
2677 if (pid == 0) {
2678 /* child -- drop privileges before continuing */
2679 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2680 drop_capabilities(app_shared_gid);
2681
Calin Juravlef63d4792018-01-30 17:43:34 +00002682 // The copy and update takes ownership over the fds.
Mathieu Chartier62d218d2018-11-05 09:34:24 -08002683 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002684 }
2685
2686 /* parent */
2687 int return_code = wait_child(pid);
2688 if (!WIFEXITED(return_code)) {
2689 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2690 return false;
2691 }
2692 return true;
2693}
2694
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002695} // namespace installd
2696} // namespace android