blob: 940ba79bef7b518020fc811ccfd33554a2b673d9 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Suren Baghdasaryan1cc5de62019-01-25 05:29:23 +000046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
50#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080051#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060052#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070053#include "installd_deps.h"
54#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070055#include "utils.h"
56
Jeff Sharkey90aff262016-12-12 14:28:24 -070057using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070058using android::base::GetBoolProperty;
59using android::base::GetProperty;
Alan Stokesa25d90c2017-10-16 10:56:00 +010060using android::base::ReadFully;
61using android::base::StringPrintf;
62using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080063using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070064
65namespace android {
66namespace installd {
67
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070068// Should minidebug info be included in compiled artifacts? Even if this value is
69// "true," usage might still be conditional to other constraints, e.g., system
70// property overrides.
71static constexpr bool kEnableMinidebugInfo = true;
72
73static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
74static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
75static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080076static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070077
Andreas Gampefa2dadd2018-02-28 19:52:47 -080078
Calin Juravle114f0812017-03-08 19:05:07 -080079// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
80struct FreeDelete {
81 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
82 void operator()(const void* ptr) const {
83 free(const_cast<void*>(ptr));
84 }
85};
86
87// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
88template <typename T>
89using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
90
Calin Juravle1a0af3b2017-03-09 14:33:33 -080091static unique_fd invalid_unique_fd() {
92 return unique_fd(-1);
93}
94
Andreas Gampe6a9cf722017-07-24 16:49:10 -070095static bool is_debug_runtime() {
96 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
97}
98
David Sehra3b5ab62017-10-25 14:27:29 -070099static bool is_debuggable_build() {
100 return android::base::GetBoolProperty("ro.debuggable", false);
101}
102
Jeff Sharkey90aff262016-12-12 14:28:24 -0700103static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800104 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700105 if (ufd.get() < 0) {
106 if (errno != ENOENT) {
107 PLOG(WARNING) << "Could not open profile " << profile;
108 return false;
109 } else {
110 // Nothing to clear. That's ok.
111 return true;
112 }
113 }
114
115 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
116 if (errno != EWOULDBLOCK) {
117 PLOG(WARNING) << "Error locking profile " << profile;
118 }
119 // This implies that the app owning this profile is running
120 // (and has acquired the lock).
121 //
122 // If we can't acquire the lock bail out since clearing is useless anyway
123 // (the app will write again to the profile).
124 //
125 // Note:
126 // This does not impact the this is not an issue for the profiling correctness.
127 // In case this is needed because of an app upgrade, profiles will still be
128 // eventually cleared by the app itself due to checksum mismatch.
129 // If this is needed because profman advised, then keeping the data around
130 // until the next run is again not an issue.
131 //
132 // If the app attempts to acquire a lock while we've held one here,
133 // it will simply skip the current write cycle.
134 return false;
135 }
136
137 bool truncated = ftruncate(ufd.get(), 0) == 0;
138 if (!truncated) {
139 PLOG(WARNING) << "Could not truncate " << profile;
140 }
141 if (flock(ufd.get(), LOCK_UN) != 0) {
142 PLOG(WARNING) << "Error unlocking profile " << profile;
143 }
144 return truncated;
145}
146
Calin Juravle114f0812017-03-08 19:05:07 -0800147// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800148// The location is the profile name for primary apks or the dex path for secondary dex files.
149static bool clear_reference_profile(const std::string& package_name, const std::string& location,
150 bool is_secondary_dex) {
151 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700152}
153
Calin Juravle114f0812017-03-08 19:05:07 -0800154// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800155// The location is the profile name for primary apks or the dex path for secondary dex files.
156static bool clear_current_profile(const std::string& package_name, const std::string& location,
157 userid_t user, bool is_secondary_dex) {
158 return clear_profile(create_current_profile_path(user, package_name, location,
159 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700160}
161
Calin Juravle114f0812017-03-08 19:05:07 -0800162// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800163// The location is the profile name for primary apks or the dex path for secondary dex files.
164bool clear_primary_reference_profile(const std::string& package_name,
165 const std::string& location) {
166 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800167}
168
169// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800170// The location is the profile name for primary apks or the dex path for secondary dex files.
171bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700172 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800173 // 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 -0700174 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
175 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800176 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700177 }
178 return success;
179}
180
Calin Juravle114f0812017-03-08 19:05:07 -0800181// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800182bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
183 userid_t user) {
184 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800185}
186
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700187static std::vector<std::string> SplitBySpaces(const std::string& str) {
188 if (str.empty()) {
189 return {};
190 }
191 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700192}
193
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700194static const char* get_location_from_path(const char* path) {
195 static constexpr char kLocationSeparator = '/';
196 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700197 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700198 return path;
199 } else {
200 // Skip the separator character.
201 return location + 1;
202 }
203}
204
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800205// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
206// need to be performed between the fork and exec.
207class ExecVHelper {
208 public:
209 // Store a placeholder for the binary name.
210 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800211
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800212 void PrepareArgs(const std::string& bin) {
213 CHECK(!args_.empty());
214 CHECK(args_[0].empty());
215 args_[0] = bin;
216 // Write char* into array.
217 for (const std::string& arg : args_) {
218 argv_.push_back(arg.c_str());
219 }
220 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800221 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800222
223 [[ noreturn ]]
224 void Exec(int exit_code) {
225 execv(argv_[0], (char * const *)&argv_[0]);
226 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
227 exit(exit_code);
228 }
229
230 // Add an arg if it's not empty.
231 void AddArg(const std::string& arg) {
232 if (!arg.empty()) {
233 args_.push_back(arg);
234 }
235 }
236
237 // Add a runtime arg if it's not empty.
238 void AddRuntimeArg(const std::string& arg) {
239 if (!arg.empty()) {
240 args_.push_back("--runtime-arg");
241 args_.push_back(arg);
242 }
243 }
244
245 protected:
246 // Holder arrays for backing arg storage.
247 std::vector<std::string> args_;
248
249 // Argument poiners.
250 std::vector<const char*> argv_;
251};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700252
253static std::string MapPropertyToArg(const std::string& property,
254 const std::string& format,
255 const std::string& default_value = "") {
256 std::string prop = GetProperty(property, default_value);
257 if (!prop.empty()) {
258 return StringPrintf(format.c_str(), prop.c_str());
259 }
260 return "";
261}
262
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800263class RunDex2Oat : public ExecVHelper {
264 public:
265 RunDex2Oat(int zip_fd,
266 int oat_fd,
267 int input_vdex_fd,
268 int output_vdex_fd,
269 int image_fd,
270 const char* input_file_name,
271 const char* output_file_name,
272 int swap_fd,
273 const char* instruction_set,
274 const char* compiler_filter,
275 bool debuggable,
276 bool post_bootcomplete,
277 bool background_job_compile,
278 int profile_fd,
279 const char* class_loader_context,
280 int target_sdk_version,
281 bool enable_hidden_api_checks,
282 bool generate_compact_dex,
283 int dex_metadata_fd,
284 const char* compilation_reason) {
285 // Get the relative path to the input file.
286 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700287
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800288 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
289 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700290
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800291 const char* threads_property = post_bootcomplete
292 ? "dalvik.vm.dex2oat-threads"
293 : "dalvik.vm.boot-dex2oat-threads";
294 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700295
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800296 const std::string dex2oat_isa_features_key =
297 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
298 std::string instruction_set_features_arg =
299 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700300
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800301 const std::string dex2oat_isa_variant_key =
302 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
303 std::string instruction_set_variant_arg =
304 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700305
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800306 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700307
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800308 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
309 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
310 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700311
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800312 // If we are booting without the real /data, don't spend time compiling.
313 std::string vold_decrypt = GetProperty("vold.decrypt", "");
314 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
315 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700316
Mathieu Chartier5880c032018-11-28 19:15:41 -0800317 const std::string resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800318 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
319 "--resolve-startup-const-strings=%s");
Mathieu Chartier5880c032018-11-28 19:15:41 -0800320
321 const std::string image_block_size_arg =
322 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
323 "--max-image-block-size=%s");
324
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800325 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700326
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800327 std::string image_format_arg;
328 if (image_fd >= 0) {
329 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000330 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000331
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800332 std::string dex2oat_large_app_threshold_arg =
333 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000334
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800335 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
Roland Levillain67a14f62019-01-23 15:59:50 +0000336 const char* dex2oat_bin = kDex2oatPath;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800337 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
338 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
339 if (is_debug_runtime() ||
340 (background_job_compile && is_debuggable_build() && !is_release)) {
341 if (access(kDex2oatDebugPath, X_OK) == 0) {
342 dex2oat_bin = kDex2oatDebugPath;
343 }
344 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000345
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800346 bool generate_minidebug_info = kEnableMinidebugInfo &&
347 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000348
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800349 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
350 // use arraysize instead.
351 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
352 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
353 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
354 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
355 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
356 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
357 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
358 std::string dex2oat_compiler_filter_arg;
359 std::string dex2oat_swap_fd;
360 std::string dex2oat_image_fd;
361 std::string target_sdk_version_arg;
362 if (target_sdk_version != 0) {
363 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
364 }
365 std::string class_loader_context_arg;
366 if (class_loader_context != nullptr) {
367 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
368 class_loader_context);
369 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000370
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800371 if (swap_fd >= 0) {
372 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
373 }
374 if (image_fd >= 0) {
375 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
376 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000377
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800378 // Compute compiler filter.
379 bool have_dex2oat_relocation_skip_flag = false;
380 if (skip_compilation) {
381 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
382 have_dex2oat_relocation_skip_flag = true;
383 } else if (compiler_filter != nullptr) {
384 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
385 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000386
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800387 if (dex2oat_compiler_filter_arg.empty()) {
388 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
389 "--compiler-filter=%s");
390 }
391
392 // Check whether all apps should be compiled debuggable.
393 if (!debuggable) {
394 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
395 }
396 std::string profile_arg;
397 if (profile_fd != -1) {
398 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
399 }
400
401 // Get the directory of the apk to pass as a base classpath directory.
402 std::string base_dir;
403 std::string apk_dir(input_file_name);
404 unsigned long dir_index = apk_dir.rfind('/');
405 bool has_base_dir = dir_index != std::string::npos;
406 if (has_base_dir) {
407 apk_dir = apk_dir.substr(0, dir_index);
408 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
409 }
410
411 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
412
413 std::string compilation_reason_arg = compilation_reason == nullptr
414 ? ""
415 : std::string("--compilation-reason=") + compilation_reason;
416
417 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
418
419 // Disable cdex if update input vdex is true since this combination of options is not
420 // supported.
421 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
422
423 AddArg(zip_fd_arg);
424 AddArg(zip_location_arg);
425 AddArg(input_vdex_fd_arg);
426 AddArg(output_vdex_fd_arg);
427 AddArg(oat_fd_arg);
428 AddArg(oat_location_arg);
429 AddArg(instruction_set_arg);
430
431 AddArg(instruction_set_variant_arg);
432 AddArg(instruction_set_features_arg);
433
434 AddRuntimeArg(dex2oat_Xms_arg);
435 AddRuntimeArg(dex2oat_Xmx_arg);
436
437 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800438 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800439 AddArg(dex2oat_compiler_filter_arg);
440 AddArg(dex2oat_threads_arg);
441 AddArg(dex2oat_swap_fd);
442 AddArg(dex2oat_image_fd);
443
444 if (generate_debug_info) {
445 AddArg("--generate-debug-info");
446 }
447 if (debuggable) {
448 AddArg("--debuggable");
449 }
450 AddArg(image_format_arg);
451 AddArg(dex2oat_large_app_threshold_arg);
452
453 if (have_dex2oat_relocation_skip_flag) {
454 AddRuntimeArg(dex2oat_norelocation);
455 }
456 AddArg(profile_arg);
457 AddArg(base_dir);
458 AddArg(class_loader_context_arg);
459 if (generate_minidebug_info) {
460 AddArg(kMinidebugDex2oatFlag);
461 }
462 if (disable_cdex) {
463 AddArg(kDisableCompactDexFlag);
464 }
465 AddArg(target_sdk_version_arg);
466 if (enable_hidden_api_checks) {
467 AddRuntimeArg("-Xhidden-api-checks");
468 }
469
470 if (dex_metadata_fd > -1) {
471 AddArg(dex_metadata_fd_arg);
472 }
473
474 AddArg(compilation_reason_arg);
475
476 // Do not add args after dex2oat_flags, they should override others for debugging.
477 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
478
479 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000480 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800481};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700482
483/*
484 * Whether dexopt should use a swap file when compiling an APK.
485 *
486 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
487 * itself, anyways).
488 *
489 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
490 *
491 * Otherwise, return true if this is a low-mem device.
492 *
493 * Otherwise, return default value.
494 */
495static bool kAlwaysProvideSwapFile = false;
496static bool kDefaultProvideSwapFile = true;
497
498static bool ShouldUseSwapFileForDexopt() {
499 if (kAlwaysProvideSwapFile) {
500 return true;
501 }
502
503 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700504 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
505 if (!dex2oat_prop_buf.empty()) {
506 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700507 }
508
509 // Shortcut for default value. This is an implementation optimization for the process sketched
510 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
511 // as low-mem is never returning false. The compiler will optimize this away if it can.
512 if (kDefaultProvideSwapFile) {
513 return true;
514 }
515
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700516 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700517 return true;
518 }
519
520 // Default value must be false here.
521 return kDefaultProvideSwapFile;
522}
523
Richard Uhler76cc0272016-12-08 10:46:35 +0000524static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525 if (set_to_bg) {
526 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800527 PLOG(ERROR) << "set_sched_policy failed";
528 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700529 }
530 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800531 PLOG(ERROR) << "setpriority failed";
532 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700533 }
534 }
535}
536
Calin Juravle29591732017-11-20 17:46:19 -0800537static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
538 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800539 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800540 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800541 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800542 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800543 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700544 }
Calin Juravle114f0812017-03-08 19:05:07 -0800545 // Profiles should belong to the app; make sure of that by giving ownership to
546 // the app uid. If we cannot do that, there's no point in returning the fd
547 // since dex2oat/profman will fail with SElinux denials.
548 if (fchown(fd.get(), uid, uid) < 0) {
549 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800550 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800551 }
Calin Juravle29591732017-11-20 17:46:19 -0800552 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800553}
554
Calin Juravle29591732017-11-20 17:46:19 -0800555static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800556 // Do not follow symlinks when opening a profile:
557 // - primary profiles should not contain symlinks in their paths
558 // - secondary dex paths should have been already resolved and validated
559 flags |= O_NOFOLLOW;
560
Calin Juravle29591732017-11-20 17:46:19 -0800561 // Check if we need to create the profile
562 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
563 unique_fd fd;
564 if ((flags & O_CREAT) != 0) {
565 fd = create_profile(uid, profile, flags);
566 } else {
567 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
568 }
569
Calin Juravle114f0812017-03-08 19:05:07 -0800570 if (fd.get() < 0) {
571 if (errno != ENOENT) {
572 // Profiles might be missing for various reasons. For example, in a
573 // multi-user environment, the profile directory for one user can be created
574 // after we start a merge. In this case the current profile for that user
575 // will not be found.
576 // Also, the secondary dex profiles might be deleted by the app at any time,
577 // so we can't we need to prepare if they are missing.
578 PLOG(ERROR) << "Failed to open profile " << profile;
579 }
580 return invalid_unique_fd();
581 }
582
Jeff Sharkey90aff262016-12-12 14:28:24 -0700583 return fd;
584}
585
Calin Juravle824a64d2018-01-18 20:23:17 -0800586static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
587 const std::string& location, bool is_secondary_dex) {
588 std::string profile = create_current_profile_path(user, package_name, location,
589 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800590 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800591}
592
Calin Juravle824a64d2018-01-18 20:23:17 -0800593static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
594 const std::string& location, bool read_write, bool is_secondary_dex) {
595 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800596 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
597}
598
599static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800600 const std::string& location) {
601 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800602 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800603}
604
Calin Juravle824a64d2018-01-18 20:23:17 -0800605static void open_profile_files(uid_t uid, const std::string& package_name,
606 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800607 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700608 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800609 *reference_profile_fd = open_reference_profile(uid, package_name, location,
610 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611
Calin Juravle114f0812017-03-08 19:05:07 -0800612 // For secondary dex files, we don't really need the user but we use it for sanity checks.
613 // Note: the user owning the dex file should be the current user.
614 std::vector<userid_t> users;
615 if (is_secondary_dex){
616 users.push_back(multiuser_get_user_id(uid));
617 } else {
618 users = get_known_users(/*volume_uuid*/ nullptr);
619 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700620 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800621 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
622 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700623 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800624 if (profile_fd.get() >= 0) {
625 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 }
627 }
628}
629
Jeff Sharkey90aff262016-12-12 14:28:24 -0700630static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
631static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
632static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
633static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
634static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
635
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800636class RunProfman : public ExecVHelper {
637 public:
638 void SetupArgs(const std::vector<unique_fd>& profile_fds,
639 const unique_fd& reference_profile_fd,
640 const std::vector<unique_fd>& apk_fds,
641 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800642 bool copy_and_update,
643 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000644 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700645
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800646 if (copy_and_update) {
647 CHECK_EQ(1u, profile_fds.size());
648 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000649 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800650 if (reference_profile_fd != -1) {
651 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000652 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800653
654 for (const unique_fd& fd : profile_fds) {
655 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
656 }
657
658 for (const unique_fd& fd : apk_fds) {
659 AddArg("--apk-fd=" + std::to_string(fd.get()));
660 }
661
662 for (const std::string& dex_location : dex_locations) {
663 AddArg("--dex-location=" + dex_location);
664 }
665
666 if (copy_and_update) {
667 AddArg("--copy-and-update-profile-key");
668 }
669
Calin Juravleb3a929d2018-12-11 14:40:00 -0800670 if (store_aggregation_counters) {
671 AddArg("--store-aggregation-counters");
672 }
673
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800674 // Do not add after dex2oat_flags, they should override others for debugging.
675 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800676 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700677
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800678 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
679 const unique_fd& reference_profile_fd,
680 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800681 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
682 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800683 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800684 reference_profile_fd,
685 apk_fds,
686 dex_locations,
687 /*copy_and_update=*/false,
688 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800689 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800691 void SetupCopyAndUpdate(unique_fd&& profile_fd,
692 unique_fd&& reference_profile_fd,
693 unique_fd&& apk_fd,
694 const std::string& dex_location) {
695 // The fds need to stay open longer than the scope of the function, so put them into a local
696 // variable vector.
697 profiles_fd_.push_back(std::move(profile_fd));
698 apk_fds_.push_back(std::move(apk_fd));
699 reference_profile_fd_ = std::move(reference_profile_fd);
700 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800701 SetupArgs(profiles_fd_,
702 reference_profile_fd_,
703 apk_fds_,
704 dex_locations,
705 /*copy_and_update=*/true,
706 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800707 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000708
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800709 void SetupDump(const std::vector<unique_fd>& profiles_fd,
710 const unique_fd& reference_profile_fd,
711 const std::vector<std::string>& dex_locations,
712 const std::vector<unique_fd>& apk_fds,
713 const unique_fd& output_fd) {
714 AddArg("--dump-only");
715 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800716 SetupArgs(profiles_fd,
717 reference_profile_fd,
718 apk_fds,
719 dex_locations,
720 /*copy_and_update=*/false,
721 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800722 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000723
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800724 void Exec() {
725 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
726 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000727
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800728 private:
729 unique_fd reference_profile_fd_;
730 std::vector<unique_fd> profiles_fd_;
731 std::vector<unique_fd> apk_fds_;
732};
Mathieu Chartier31636522018-11-09 23:53:07 +0000733
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800734
Calin Juravlef63d4792018-01-30 17:43:34 +0000735
Jeff Sharkey90aff262016-12-12 14:28:24 -0700736// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800737// The location is the package name for primary apks or the dex path for secondary dex files.
738// Returns true if there is enough information in the current profiles that makes it
739// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700740// If the return value is true all the current profiles would have been merged into
741// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800742static bool analyze_profiles(uid_t uid, const std::string& package_name,
743 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800744 std::vector<unique_fd> profiles_fd;
745 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800746 open_profile_files(uid, package_name, location, is_secondary_dex,
747 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800748 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700749 // Skip profile guided compilation because no profiles were found.
750 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700751 return false;
752 }
753
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800754 RunProfman profman_merge;
755 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 pid_t pid = fork();
757 if (pid == 0) {
758 /* child -- drop privileges before continuing */
759 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800760 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700761 }
762 /* parent */
763 int return_code = wait_child(pid);
764 bool need_to_compile = false;
765 bool should_clear_current_profiles = false;
766 bool should_clear_reference_profile = false;
767 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800768 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 } else {
770 return_code = WEXITSTATUS(return_code);
771 switch (return_code) {
772 case PROFMAN_BIN_RETURN_CODE_COMPILE:
773 need_to_compile = true;
774 should_clear_current_profiles = true;
775 should_clear_reference_profile = false;
776 break;
777 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
778 need_to_compile = false;
779 should_clear_current_profiles = false;
780 should_clear_reference_profile = false;
781 break;
782 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800783 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 need_to_compile = false;
785 should_clear_current_profiles = true;
786 should_clear_reference_profile = true;
787 break;
788 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
789 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
790 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800791 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792 need_to_compile = false;
793 should_clear_current_profiles = false;
794 should_clear_reference_profile = false;
795 break;
796 default:
797 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800798 LOG(WARNING) << "Unknown error code while processing profiles for location "
799 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800 need_to_compile = false;
801 should_clear_current_profiles = true;
802 should_clear_reference_profile = true;
803 break;
804 }
805 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800806
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800808 if (is_secondary_dex) {
809 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800810 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
811 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800812 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800813 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800814 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700815 }
816 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800817 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700818 }
819 return need_to_compile;
820}
821
Calin Juravle114f0812017-03-08 19:05:07 -0800822// Decides if profile guided compilation is needed or not based on existing profiles.
823// The analysis is done for the primary apks of the given package.
824// Returns true if there is enough information in the current profiles that makes it
825// worth to recompile the package.
826// If the return value is true all the current profiles would have been merged into
827// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800828bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
829 const std::string& profile_name) {
830 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800831}
832
Calin Juravle408cd4a2018-01-20 23:34:18 -0800833bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
834 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800835 std::vector<unique_fd> profile_fds;
836 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800837 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
838 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700839
Calin Juravle408cd4a2018-01-20 23:34:18 -0800840 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800841 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800843 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700844 const bool has_profiles = !profile_fds.empty();
845
846 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800847 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700848 return false;
849 }
850
Calin Juravle114f0812017-03-08 19:05:07 -0800851 unique_fd output_fd(open(out_file_name.c_str(),
852 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800854 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700855 return false;
856 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800857
Jeff Sharkey90aff262016-12-12 14:28:24 -0700858 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800859 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800860 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
861 if (apk_fd == -1) {
862 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
863 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700864 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800865 dex_locations.push_back(get_location_from_path(code_path.c_str()));
866 apk_fds.push_back(std::move(apk_fd));
867
Jeff Sharkey90aff262016-12-12 14:28:24 -0700868
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800869 RunProfman profman_dump;
870 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 pid_t pid = fork();
872 if (pid == 0) {
873 /* child -- drop privileges before continuing */
874 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800875 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700876 }
877 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700878 int return_code = wait_child(pid);
879 if (!WIFEXITED(return_code)) {
880 LOG(WARNING) << "profman failed for package " << pkgname << ": "
881 << return_code;
882 return false;
883 }
884 return true;
885}
886
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700887bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800888 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700889 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
890 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800891 package_name,
892 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700893 /*read_write*/ true,
894 /*secondary*/ false));
895 if (in_fd.get() < 0) {
896 PLOG(WARNING) << "Could not open profile " << system_profile;
897 return false;
898 }
899 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800900 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700901 return false;
902 }
903
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700904 // As a security measure we want to write the profile information with the reduced capabilities
905 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700906 pid_t pid = fork();
907 if (pid == 0) {
908 /* child -- drop privileges before continuing */
909 drop_capabilities(packageUid);
910
911 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
912 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800913 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700914 }
915 // This implies that the app owning this profile is running
916 // (and has acquired the lock).
917 //
918 // The app never acquires the lock for the reference profiles of primary apks.
919 // Only dex2oat from installd will do that. Since installd is single threaded
920 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800921 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700922 return false;
923 }
924
925 bool truncated = ftruncate(out_fd.get(), 0) == 0;
926 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800927 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700928 }
929
930 // Copy over data.
931 static constexpr size_t kBufferSize = 4 * 1024;
932 char buffer[kBufferSize];
933 while (true) {
934 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
935 if (bytes == 0) {
936 break;
937 }
938 write(out_fd.get(), buffer, bytes);
939 }
940 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800941 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700942 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700943 // Use _exit since we don't want to run the global destructors in the child.
944 // b/62597429
945 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700946 }
947 /* parent */
948 int return_code = wait_child(pid);
949 return return_code == 0;
950}
951
Jeff Sharkey90aff262016-12-12 14:28:24 -0700952static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
953 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
954 if (EndsWith(oat_path, ".dex")) {
955 std::string new_path = oat_path;
956 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800957 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700958 return new_path;
959 }
960
961 // An odex entry. Not that this may not be an extension, e.g., in the OTA
962 // case (where the base name will have an extension for the B artifact).
963 size_t odex_pos = oat_path.rfind(".odex");
964 if (odex_pos != std::string::npos) {
965 std::string new_path = oat_path;
966 new_path.replace(odex_pos, strlen(".odex"), new_ext);
967 CHECK_NE(new_path.find(new_ext), std::string::npos);
968 return new_path;
969 }
970
971 // Don't know how to handle this.
972 return "";
973}
974
975// Translate the given oat path to an art (app image) path. An empty string
976// denotes an error.
977static std::string create_image_filename(const std::string& oat_path) {
978 return replace_file_extension(oat_path, ".art");
979}
980
981// Translate the given oat path to a vdex path. An empty string denotes an error.
982static std::string create_vdex_filename(const std::string& oat_path) {
983 return replace_file_extension(oat_path, ".vdex");
984}
985
Jeff Sharkey90aff262016-12-12 14:28:24 -0700986static int open_output_file(const char* file_name, bool recreate, int permissions) {
987 int flags = O_RDWR | O_CREAT;
988 if (recreate) {
989 if (unlink(file_name) < 0) {
990 if (errno != ENOENT) {
991 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
992 }
993 }
994 flags |= O_EXCL;
995 }
996 return open(file_name, flags, permissions);
997}
998
Calin Juravle2289c0a2017-02-15 12:44:14 -0800999static bool set_permissions_and_ownership(
1000 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1001 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1002 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001003 if (fchmod(fd,
1004 S_IRUSR|S_IWUSR|S_IRGRP |
1005 (is_public ? S_IROTH : 0)) < 0) {
1006 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1007 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001008 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1010 return false;
1011 }
1012 return true;
1013}
1014
1015static bool IsOutputDalvikCache(const char* oat_dir) {
1016 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1017 // into '!'. Play it safe by handling it both.
1018 // TODO: ensure we never get null.
1019 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1020 return oat_dir == nullptr || oat_dir[0] == '!';
1021}
1022
Calin Juravled23dee72017-07-06 16:29:11 -07001023// Best-effort check whether we can fit the the path into our buffers.
1024// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1025// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1026// extension to the cache path (5 bytes).
1027// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1028static bool validate_dex_path_size(const std::string& dex_path) {
1029 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1030 LOG(ERROR) << "dex_path too long: " << dex_path;
1031 return false;
1032 }
1033 return true;
1034}
1035
Jeff Sharkey90aff262016-12-12 14:28:24 -07001036static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001037 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001038 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001039 return false;
1040 }
1041
1042 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001043 // Oat dirs for secondary dex files are already validated.
1044 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001045 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1046 return false;
1047 }
1048 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1049 return false;
1050 }
1051 } else {
1052 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1053 return false;
1054 }
1055 }
1056 return true;
1057}
1058
1059// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1060// on destruction. It will also run the given cleanup (unless told not to) after closing.
1061//
1062// Usage example:
1063//
Calin Juravle7a570e82017-01-14 16:23:30 -08001064// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001065// [name]() {
1066// unlink(name.c_str());
1067// });
1068// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1069// wrapper if captured as a reference.
1070//
1071// if (file.get() == -1) {
1072// // Error opening...
1073// }
1074//
1075// ...
1076// if (error) {
1077// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1078// // and delete the file (after the fd is closed).
1079// return -1;
1080// }
1081//
1082// (Success case)
1083// file.SetCleanup(false);
1084// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1085// // (leaving the file around; after the fd is closed).
1086//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001087class Dex2oatFileWrapper {
1088 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001089 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001090 }
1091
Calin Juravle7a570e82017-01-14 16:23:30 -08001092 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1093 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1094
1095 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1096 value_ = other.value_;
1097 cleanup_ = other.cleanup_;
1098 do_cleanup_ = other.do_cleanup_;
1099 auto_close_ = other.auto_close_;
1100 other.release();
1101 }
1102
1103 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1104 value_ = other.value_;
1105 cleanup_ = other.cleanup_;
1106 do_cleanup_ = other.do_cleanup_;
1107 auto_close_ = other.auto_close_;
1108 other.release();
1109 return *this;
1110 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001111
1112 ~Dex2oatFileWrapper() {
1113 reset(-1);
1114 }
1115
1116 int get() {
1117 return value_;
1118 }
1119
1120 void SetCleanup(bool cleanup) {
1121 do_cleanup_ = cleanup;
1122 }
1123
1124 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001125 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001126 close(value_);
1127 }
1128 if (do_cleanup_ && cleanup_ != nullptr) {
1129 cleanup_();
1130 }
1131
1132 value_ = new_value;
1133 }
1134
Calin Juravle7a570e82017-01-14 16:23:30 -08001135 void reset(int new_value, std::function<void ()> new_cleanup) {
1136 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001137 close(value_);
1138 }
1139 if (do_cleanup_ && cleanup_ != nullptr) {
1140 cleanup_();
1141 }
1142
1143 value_ = new_value;
1144 cleanup_ = new_cleanup;
1145 }
1146
Calin Juravle7a570e82017-01-14 16:23:30 -08001147 void DisableAutoClose() {
1148 auto_close_ = false;
1149 }
1150
Jeff Sharkey90aff262016-12-12 14:28:24 -07001151 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001152 void release() {
1153 value_ = -1;
1154 do_cleanup_ = false;
1155 cleanup_ = nullptr;
1156 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001159 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001160 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001161};
1162
Calin Juravle7a570e82017-01-14 16:23:30 -08001163// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001164Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1165 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001166
1167 // We don't create an image for secondary dex files.
1168 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001169 return Dex2oatFileWrapper();
1170 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001171
Calin Juravle7a570e82017-01-14 16:23:30 -08001172 const std::string image_path = create_image_filename(out_oat_path);
1173 if (image_path.empty()) {
1174 // Happens when the out_oat_path has an unknown extension.
1175 return Dex2oatFileWrapper();
1176 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001177
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001178 // In case there is a stale image, remove it now. Ignore any error.
1179 unlink(image_path.c_str());
1180
1181 // Not enabled, exit.
1182 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001183 return Dex2oatFileWrapper();
1184 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001185 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1186 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001187 return Dex2oatFileWrapper();
1188 }
1189 // Recreate is true since we do not want to modify a mapped image. If the app is
1190 // already running and we modify the image file, it can cause crashes (b/27493510).
1191 Dex2oatFileWrapper wrapper_fd(
1192 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1193 [image_path]() { unlink(image_path.c_str()); });
1194 if (wrapper_fd.get() < 0) {
1195 // Could not create application image file. Go on since we can compile without it.
1196 LOG(ERROR) << "installd could not create '" << image_path
1197 << "' for image file during dexopt";
1198 // If we have a valid image file path but no image fd, explicitly erase the image file.
1199 if (unlink(image_path.c_str()) < 0) {
1200 if (errno != ENOENT) {
1201 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1202 }
1203 }
1204 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001205 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001206 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1207 wrapper_fd.reset(-1);
1208 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001209
Calin Juravle7a570e82017-01-14 16:23:30 -08001210 return wrapper_fd;
1211}
1212
1213// Creates the dexopt swap file if necessary and return its fd.
1214// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001215unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001216 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001217 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001218 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001219 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001220 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001221 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001222 if (swap_fd.get() < 0) {
1223 // Could not create swap file. Optimistically go on and hope that we can compile
1224 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001225 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001226 } else {
1227 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001228 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001229 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1230 }
1231 }
1232 return swap_fd;
1233}
1234
1235// Opens the reference profiles if needed.
1236// 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 -08001237Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001238 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001239 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001240 // If we are not profile guided compilation, or we are compiling system server
1241 // do not bother to open the profiles; we won't be using them.
1242 if (!profile_guided || (pkgname[0] == '*')) {
1243 return Dex2oatFileWrapper();
1244 }
1245
1246 // If this is a secondary dex path which is public do not open the profile.
1247 // We cannot compile public secondary dex paths with profiles. That's because
1248 // it will expose how the dex files are used by their owner.
1249 //
1250 // Note that the PackageManager is responsible to set the is_public flag for
1251 // primary apks and we do not check it here. In some cases, e.g. when
1252 // compiling with a public profile from the .dm file the PackageManager will
1253 // set is_public toghether with the profile guided compilation.
1254 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001255 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001256 }
Calin Juravle114f0812017-03-08 19:05:07 -08001257
1258 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001259 std::string location;
1260 if (is_secondary_dex) {
1261 location = dex_path;
1262 } else {
1263 if (profile_name == nullptr) {
1264 // This path is taken for system server re-compilation lunched from ZygoteInit.
1265 return Dex2oatFileWrapper();
1266 } else {
1267 location = profile_name;
1268 }
1269 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001270 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1271 is_secondary_dex);
1272 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1273 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001274 };
1275 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001276}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001277
Calin Juravle7a570e82017-01-14 16:23:30 -08001278// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1279// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001280bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001281 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001282 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001283 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1284 CHECK(in_vdex_wrapper_fd != nullptr);
1285 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001286 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1287 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001288 char in_odex_path[PKG_PATH_MAX];
1289 int dexopt_action = abs(dexopt_needed);
1290 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001291 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001292
1293 // Infer the name of the output VDEX.
1294 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1295 if (out_vdex_path_str.empty()) {
1296 return false;
1297 }
1298
1299 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001300 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001301 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1302 const char* path = nullptr;
1303 if (is_odex_location) {
1304 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1305 path = in_odex_path;
1306 } else {
1307 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001308 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001309 }
1310 } else {
1311 path = out_oat_path;
1312 }
1313 in_vdex_path_str = create_vdex_filename(path);
1314 if (in_vdex_path_str.empty()) {
1315 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001316 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001317 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001318 // We can update in place when all these conditions are met:
1319 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1320 // on /system typically cannot be updated in place).
1321 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1322 // cannot be currently used by a running process.
1323 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1324 // different vdex files to operate.
1325 update_vdex_in_place =
1326 (in_vdex_path_str == out_vdex_path_str) &&
1327 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1328 !profile_guided;
1329 if (update_vdex_in_place) {
1330 // Open the file read-write to be able to update it.
1331 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1332 if (in_vdex_wrapper_fd->get() == -1) {
1333 // If we failed to open the file, we cannot update it in place.
1334 update_vdex_in_place = false;
1335 }
1336 } else {
1337 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1338 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001339 }
1340
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001341 // If we are updating the vdex in place, we do not need to recreate a vdex,
1342 // and can use the same existing one.
1343 if (update_vdex_in_place) {
1344 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1345 // have bogus stale vdex files.
1346 out_vdex_wrapper_fd->reset(
1347 in_vdex_wrapper_fd->get(),
1348 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1349 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1350 // wrapper).
1351 in_vdex_wrapper_fd->DisableAutoClose();
1352 } else {
1353 out_vdex_wrapper_fd->reset(
1354 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1355 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1356 if (out_vdex_wrapper_fd->get() < 0) {
1357 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1358 return false;
1359 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001360 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001361 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001362 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001363 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1364 return false;
1365 }
1366
1367 // If we got here we successfully opened the vdex files.
1368 return true;
1369}
1370
1371// Opens the output oat file for the given apk.
1372// If successful it stores the output path into out_oat_path and returns true.
1373Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001374 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1375 char* out_oat_path) {
1376 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001377 return Dex2oatFileWrapper();
1378 }
1379 const std::string out_oat_path_str(out_oat_path);
1380 Dex2oatFileWrapper wrapper_fd(
1381 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1382 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1383 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001384 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001385 } else if (!set_permissions_and_ownership(
1386 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001387 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1388 wrapper_fd.reset(-1);
1389 }
1390 return wrapper_fd;
1391}
1392
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001393// Creates RDONLY fds for oat and vdex files, if exist.
1394// Returns false if it fails to create oat out path for the given apk path.
1395// Note that the method returns true even if the files could not be opened.
1396bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1397 const std::string& oat_dir,
1398 const std::string& instruction_set,
1399 bool is_secondary_dex,
1400 unique_fd* oat_file_fd,
1401 unique_fd* vdex_file_fd) {
1402 char oat_path[PKG_PATH_MAX];
1403 if (!create_oat_out_path(apk_path.c_str(),
1404 instruction_set.c_str(),
1405 oat_dir.c_str(),
1406 is_secondary_dex,
1407 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001408 LOG(ERROR) << "Could not create oat out path for "
1409 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001410 return false;
1411 }
1412 oat_file_fd->reset(open(oat_path, O_RDONLY));
1413 if (oat_file_fd->get() < 0) {
1414 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1415 }
1416
1417 std::string vdex_filename = create_vdex_filename(oat_path);
1418 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1419 if (vdex_file_fd->get() < 0) {
1420 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1421 }
1422
1423 return true;
1424}
1425
Calin Juravle7a570e82017-01-14 16:23:30 -08001426// Updates the access times of out_oat_path based on those from apk_path.
1427void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1428 struct stat input_stat;
1429 memset(&input_stat, 0, sizeof(input_stat));
1430 if (stat(apk_path, &input_stat) != 0) {
1431 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1432 return;
1433 }
1434
1435 struct utimbuf ut;
1436 ut.actime = input_stat.st_atime;
1437 ut.modtime = input_stat.st_mtime;
1438 if (utime(out_oat_path, &ut) != 0) {
1439 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1440 }
1441}
1442
Calin Juravle80a21252017-01-17 14:43:25 -08001443// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001444// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1445// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1446// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001447class RunDexoptAnalyzer : public ExecVHelper {
1448 public:
1449 RunDexoptAnalyzer(const std::string& dex_file,
1450 int vdex_fd,
1451 int oat_fd,
1452 int zip_fd,
1453 const std::string& instruction_set,
1454 const std::string& compiler_filter,
1455 bool profile_was_updated,
1456 bool downgrade,
1457 const char* class_loader_context) {
1458 CHECK_GE(zip_fd, 0);
1459 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001460 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001461
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001462 std::string dex_file_arg = "--dex-file=" + dex_file;
1463 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1464 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1465 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1466 std::string isa_arg = "--isa=" + instruction_set;
1467 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1468 const char* assume_profile_changed = "--assume-profile-changed";
1469 const char* downgrade_flag = "--downgrade";
1470 std::string class_loader_context_arg = "--class-loader-context=";
1471 if (class_loader_context != nullptr) {
1472 class_loader_context_arg += class_loader_context;
1473 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001474
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001475 // program name, dex file, isa, filter
1476 AddArg(dex_file_arg);
1477 AddArg(isa_arg);
1478 AddArg(compiler_filter_arg);
1479 if (oat_fd >= 0) {
1480 AddArg(oat_fd_arg);
1481 }
1482 if (vdex_fd >= 0) {
1483 AddArg(vdex_fd_arg);
1484 }
1485 AddArg(zip_fd_arg.c_str());
1486 if (profile_was_updated) {
1487 AddArg(assume_profile_changed);
1488 }
1489 if (downgrade) {
1490 AddArg(downgrade_flag);
1491 }
1492 if (class_loader_context != nullptr) {
1493 AddArg(class_loader_context_arg.c_str());
1494 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001495
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001496 PrepareArgs(dexoptanalyzer_bin);
1497 }
1498};
Calin Juravle80a21252017-01-17 14:43:25 -08001499
1500// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001501static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001502 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001503 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001504 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001505 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001506 return false;
1507 }
Calin Juravle114f0812017-03-08 19:05:07 -08001508 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001509
Calin Juravle80a21252017-01-17 14:43:25 -08001510 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001511 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1512 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001513 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001514 return false;
1515 }
1516
1517 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001518 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001519
Calin Juravle7d765462017-09-04 15:57:10 -07001520 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001521 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001522 return false;
1523 }
1524
1525 return true;
1526}
1527
Calin Juravle7d765462017-09-04 15:57:10 -07001528// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1529// secondary dex files. This return codes are returned by the child process created for
1530// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001531
Andreas Gampe194fe422018-02-28 20:16:19 -08001532enum DexoptAnalyzerSkipCodes {
1533 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001534 // Specific errors are encoded in the name.
1535 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1536 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1537 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1538 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1539 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001540 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001541 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001542};
Calin Juravle7d765462017-09-04 15:57:10 -07001543
1544// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001545// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1546// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001547// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1548// of dexoptanalyzer.
1549static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001550 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001551 // The result values are defined in dexoptanalyzer.
1552 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001553 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001554 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001555 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001556 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001557 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001558 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001559 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001560 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001561 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1562 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001563 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1564 " Expected odex file status for secondary dex %s"
1565 " : dexoptanalyzer result=%d",
1566 dex_path.c_str(),
1567 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001568 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001569 }
1570
1571 // Use a second switch for enum switch-case analysis.
1572 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001573 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001574 // If the file does not exist there's no need for dexopt.
1575 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1576 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001577
1578 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1579 *error_msg = "Dexoptanalyzer path validation failed";
1580 return false;
1581 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1582 *error_msg = "Dexoptanalyzer open zip failed";
1583 return false;
1584 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1585 *error_msg = "Dexoptanalyzer dir preparation failed";
1586 return false;
1587 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1588 *error_msg = "Dexoptanalyzer open output failed";
1589 return false;
1590 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1591 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001592 return false;
1593 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001594
1595 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1596 dex_path.c_str(),
1597 result);
1598 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001599}
1600
Calin Juravle7d765462017-09-04 15:57:10 -07001601enum SecondaryDexAccess {
1602 kSecondaryDexAccessReadOk = 0,
1603 kSecondaryDexAccessDoesNotExist = 1,
1604 kSecondaryDexAccessPermissionError = 2,
1605 kSecondaryDexAccessIOError = 3
1606};
1607
1608static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1609 // Check if the path exists and can be read. If not, there's nothing to do.
1610 if (access(dex_path.c_str(), R_OK) == 0) {
1611 return kSecondaryDexAccessReadOk;
1612 } else {
1613 if (errno == ENOENT) {
1614 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1615 return kSecondaryDexAccessDoesNotExist;
1616 } else {
1617 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1618 return errno == EACCES
1619 ? kSecondaryDexAccessPermissionError
1620 : kSecondaryDexAccessIOError;
1621 }
1622 }
1623}
1624
1625static bool is_file_public(const std::string& filename) {
1626 struct stat file_stat;
1627 if (stat(filename.c_str(), &file_stat) == 0) {
1628 return (file_stat.st_mode & S_IROTH) != 0;
1629 }
1630 return false;
1631}
1632
1633// Create the oat file structure for the secondary dex 'dex_path' and assign
1634// the individual path component to the 'out_' parameters.
1635static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001636 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001637 size_t dirIndex = dex_path.rfind('/');
1638 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001639 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001640 return false;
1641 }
1642 // TODO(calin): we have similar computations in at lest 3 other places
1643 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1644 // using string append.
1645 std::string apk_dir = dex_path.substr(0, dirIndex);
1646 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1647 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1648
1649 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1650 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001651 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001652 return false;
1653 }
1654 return true;
1655}
1656
1657// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1658// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001659static bool validate_dexopt_storage_flags(int dexopt_flags,
1660 int* out_storage_flag,
1661 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001662 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1663 *out_storage_flag = FLAG_STORAGE_CE;
1664 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001665 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001666 return false;
1667 }
1668 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1669 *out_storage_flag = FLAG_STORAGE_DE;
1670 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001671 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001672 return false;
1673 }
1674 return true;
1675}
1676
Calin Juravlec9eab382017-01-25 01:17:17 -08001677// 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 -08001678// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1679// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001680// When returning true, the output parameters will be:
1681// - is_public_out: whether or not the oat file should not be made public
1682// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1683// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001684static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001685 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001686 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001687 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1688 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001689 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001690 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001691 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1692 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001693 return false;
1694 }
Calin Juravle7d765462017-09-04 15:57:10 -07001695 // Compute the oat dir as it's not easy to extract it from the child computation.
1696 char oat_path[PKG_PATH_MAX];
1697 char oat_dir[PKG_PATH_MAX];
1698 char oat_isa_dir[PKG_PATH_MAX];
1699 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001700 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1701 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001702 return false;
1703 }
Calin Juravle7d765462017-09-04 15:57:10 -07001704 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001705
Calin Juravle80a21252017-01-17 14:43:25 -08001706 pid_t pid = fork();
1707 if (pid == 0) {
1708 // child -- drop privileges before continuing.
1709 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001710
1711 // Validate the path structure.
1712 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1713 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001714 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001715 }
1716
1717 // Open the dex file.
1718 unique_fd zip_fd;
1719 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1720 if (zip_fd.get() < 0) {
1721 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001722 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001723 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001724 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001725 }
1726 }
1727
1728 // Prepare the oat directories.
1729 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001730 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001731 }
1732
1733 // Open the vdex/oat files if any.
1734 unique_fd oat_file_fd;
1735 unique_fd vdex_file_fd;
1736 if (!maybe_open_oat_and_vdex_file(dex_path,
1737 *oat_dir_out,
1738 instruction_set,
1739 true /* is_secondary_dex */,
1740 &oat_file_fd,
1741 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001742 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001743 }
1744
1745 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001746 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1747 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001748
1749 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001750 // Note that we do not do it before the fork since opening the files is required to happen
1751 // after forking.
1752 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1753 vdex_file_fd.get(),
1754 oat_file_fd.get(),
1755 zip_fd.get(),
1756 instruction_set,
1757 compiler_filter, profile_was_updated,
1758 downgrade,
1759 class_loader_context);
1760 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001761 }
1762
1763 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001764 int result = wait_child(pid);
1765 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001766 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1767 dex_path.c_str(),
1768 result);
1769 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001770 return false;
1771 }
1772 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001773 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001774 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1775 result,
1776 dexopt_needed_out,
1777 error_msg);
1778 if (!success) {
1779 LOG(ERROR) << *error_msg;
1780 }
Calin Juravle7d765462017-09-04 15:57:10 -07001781
1782 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1783
Calin Juravle80a21252017-01-17 14:43:25 -08001784 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001785 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1786 // makes the code simpler; force compilation is only needed during tests).
1787 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001788 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001789 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001790 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1791 }
1792
Calin Juravle7d765462017-09-04 15:57:10 -07001793 // Check if we should make the oat file public.
1794 // Note that if the dex file is not public the compiled code cannot be made public.
1795 // It is ok to check this flag outside in the parent process.
1796 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1797
Calin Juravle80a21252017-01-17 14:43:25 -08001798 return success;
1799}
1800
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001801static std::string format_dexopt_error(int status, const char* dex_path) {
1802 if (WIFEXITED(status)) {
1803 int int_code = WEXITSTATUS(status);
1804 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1805 if (code_name != nullptr) {
1806 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1807 }
1808 }
1809 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001810}
1811
Calin Juravlec9eab382017-01-25 01:17:17 -08001812int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001813 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001814 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001815 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001816 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001817 CHECK(pkgname != nullptr);
1818 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001819 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001820 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1821 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001822
Calin Juravled23dee72017-07-06 16:29:11 -07001823 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001824 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001825 return -1;
1826 }
1827
1828 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001829 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1830 class_loader_context);
1831 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001832 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001833 }
1834
Calin Juravleebc8a792017-04-04 20:21:05 -07001835 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001836 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1837 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1838 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001839 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001840 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001841 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001842 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001843 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001844
1845 // Check if we're dealing with a secondary dex file and if we need to compile it.
1846 std::string oat_dir_str;
1847 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001848 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001849 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001850 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001851 oat_dir = oat_dir_str.c_str();
1852 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1853 return 0; // Nothing to do, report success.
1854 }
1855 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001856 if (error_msg->empty()) { // TODO: Make this a CHECK.
1857 *error_msg = "Failed processing secondary.";
1858 }
Calin Juravle80a21252017-01-17 14:43:25 -08001859 return -1; // We had an error, logged in the process method.
1860 }
1861 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001862 // Currently these flags are only use for secondary dex files.
1863 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001864 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1865 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1866 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001867
1868 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001869 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001870 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001871 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1872 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001873 return -1;
1874 }
1875
1876 // Create the output OAT file.
1877 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001878 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001879 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001880 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001881 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001882 return -1;
1883 }
1884
1885 // Open vdex files.
1886 Dex2oatFileWrapper in_vdex_fd;
1887 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001888 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1889 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001890 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001891 return -1;
1892 }
1893
Calin Juravlecb556e32017-04-04 20:22:50 -07001894 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1895 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1896 // fully inherit their parent context).
1897 // Note that for primary apk the oat files are created before, in a separate installd
1898 // call which also does the restorecon. TODO(calin): unify the paths.
1899 if (is_secondary_dex) {
1900 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1901 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001902 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1903 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001904 return -1;
1905 }
1906 }
1907
Jeff Sharkey90aff262016-12-12 14:28:24 -07001908 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001909 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001910
Calin Juravle7a570e82017-01-14 16:23:30 -08001911 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001912 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1913 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001914
Calin Juravle7a570e82017-01-14 16:23:30 -08001915 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001916 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001917 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001918
Calin Juravle62c5a372018-02-01 17:03:23 +00001919 unique_fd dex_metadata_fd;
1920 if (dex_metadata_path != nullptr) {
1921 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1922 if (dex_metadata_fd.get() < 0) {
1923 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1924 }
1925 }
1926
Andreas Gampe023b2242018-02-28 16:03:25 -08001927 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001928
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001929 RunDex2Oat runner(input_fd.get(),
1930 out_oat_fd.get(),
1931 in_vdex_fd.get(),
1932 out_vdex_fd.get(),
1933 image_fd.get(),
1934 dex_path,
1935 out_oat_path,
1936 swap_fd.get(),
1937 instruction_set,
1938 compiler_filter,
1939 debuggable,
1940 boot_complete,
1941 background_job_compile,
1942 reference_profile_fd.get(),
1943 class_loader_context,
1944 target_sdk_version,
1945 enable_hidden_api_checks,
1946 generate_compact_dex,
1947 dex_metadata_fd.get(),
1948 compilation_reason);
1949
Jeff Sharkey90aff262016-12-12 14:28:24 -07001950 pid_t pid = fork();
1951 if (pid == 0) {
1952 /* child -- drop privileges before continuing */
1953 drop_capabilities(uid);
1954
Richard Uhler76cc0272016-12-08 10:46:35 +00001955 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001956 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001957 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001958 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001959 }
1960
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001961 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001962 } else {
1963 int res = wait_child(pid);
1964 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001965 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001966 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001967 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1968 << std::hex << std::setw(4) << res << ", process failed";
1969 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001970 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001971 }
1972 }
1973
Calin Juravlec9eab382017-01-25 01:17:17 -08001974 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001975
1976 // We've been successful, don't delete output.
1977 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001978 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001979 image_fd.SetCleanup(false);
1980 reference_profile_fd.SetCleanup(false);
1981
1982 return 0;
1983}
1984
Calin Juravlec9eab382017-01-25 01:17:17 -08001985// Try to remove the given directory. Log an error if the directory exists
1986// and is empty but could not be removed.
1987static bool rmdir_if_empty(const char* dir) {
1988 if (rmdir(dir) == 0) {
1989 return true;
1990 }
1991 if (errno == ENOENT || errno == ENOTEMPTY) {
1992 return true;
1993 }
1994 PLOG(ERROR) << "Failed to remove dir: " << dir;
1995 return false;
1996}
1997
1998// Try to unlink the given file. Log an error if the file exists and could not
1999// be unlinked.
2000static bool unlink_if_exists(const std::string& file) {
2001 if (unlink(file.c_str()) == 0) {
2002 return true;
2003 }
2004 if (errno == ENOENT) {
2005 return true;
2006
2007 }
2008 PLOG(ERROR) << "Could not unlink: " << file;
2009 return false;
2010}
2011
Calin Juravle7d765462017-09-04 15:57:10 -07002012enum ReconcileSecondaryDexResult {
2013 kReconcileSecondaryDexExists = 0,
2014 kReconcileSecondaryDexCleanedUp = 1,
2015 kReconcileSecondaryDexValidationError = 2,
2016 kReconcileSecondaryDexCleanUpError = 3,
2017 kReconcileSecondaryDexAccessIOError = 4,
2018};
Calin Juravlec9eab382017-01-25 01:17:17 -08002019
2020// Reconcile the secondary dex 'dex_path' and its generated oat files.
2021// Return true if all the parameters are valid and the secondary dex file was
2022// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2023// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2024// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2025// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2026// Return false if there were errors during processing. In this case
2027// out_secondary_dex_exists will be set to false.
2028bool reconcile_secondary_dex_file(const std::string& dex_path,
2029 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2030 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2031 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002032 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002033 if (isas.size() == 0) {
2034 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2035 return false;
2036 }
2037
Calin Juravle7d765462017-09-04 15:57:10 -07002038 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2039 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2040 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002041 return false;
2042 }
2043
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002044 // As a security measure we want to unlink art artifacts with the reduced capabilities
2045 // of the package user id. So we fork and drop capabilities in the child.
2046 pid_t pid = fork();
2047 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002048 /* child -- drop privileges before continuing */
2049 drop_capabilities(uid);
2050
2051 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2052 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2053 uid, storage_flag)) {
2054 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2055 _exit(kReconcileSecondaryDexValidationError);
2056 }
2057
2058 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2059 switch (access_check) {
2060 case kSecondaryDexAccessDoesNotExist:
2061 // File does not exist. Proceed with cleaning.
2062 break;
2063 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2064 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2065 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2066 default:
2067 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2068 _exit(kReconcileSecondaryDexValidationError);
2069 }
2070
2071 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002072 char oat_path[PKG_PATH_MAX];
2073 char oat_dir[PKG_PATH_MAX];
2074 char oat_isa_dir[PKG_PATH_MAX];
2075 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002076 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002077 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002078 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002079 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2080 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002081 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002082 }
Calin Juravle51314092017-05-18 15:33:05 -07002083
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002084 // Delete oat/vdex/art files.
2085 result = unlink_if_exists(oat_path) && result;
2086 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2087 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002088
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002089 // Delete profiles.
2090 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002091 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002092 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002093 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002094 result = unlink_if_exists(current_profile) && result;
2095 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002096
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002097 // We upgraded once the location of current profile for secondary dex files.
2098 // Check for any previous left-overs and remove them as well.
2099 std::string old_current_profile = dex_path + ".prof";
2100 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002101
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002102 // Try removing the directories as well, they might be empty.
2103 result = rmdir_if_empty(oat_isa_dir) && result;
2104 result = rmdir_if_empty(oat_dir) && result;
2105 }
Calin Juravle7d765462017-09-04 15:57:10 -07002106 if (!result) {
2107 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2108 }
2109 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002110 }
2111
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002112 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002113 if (!WIFEXITED(return_code)) {
2114 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2115 } else {
2116 return_code = WEXITSTATUS(return_code);
2117 }
2118
2119 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2120
2121 switch (return_code) {
2122 case kReconcileSecondaryDexCleanedUp:
2123 case kReconcileSecondaryDexValidationError:
2124 // If we couldn't validate assume the dex file does not exist.
2125 // This will purge the entry from the PM records.
2126 *out_secondary_dex_exists = false;
2127 return true;
2128 case kReconcileSecondaryDexExists:
2129 *out_secondary_dex_exists = true;
2130 return true;
2131 case kReconcileSecondaryDexAccessIOError:
2132 // We had an access IO error.
2133 // Return false so that we can try again.
2134 // The value of out_secondary_dex_exists does not matter in this case and by convention
2135 // is set to false.
2136 *out_secondary_dex_exists = false;
2137 return false;
2138 default:
2139 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2140 *out_secondary_dex_exists = false;
2141 return false;
2142 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002143}
2144
Alan Stokesa25d90c2017-10-16 10:56:00 +01002145// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2146// Returns true if all parameters are valid and the hash successfully computed and stored in
2147// out_secondary_dex_hash.
2148// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2149// the app.
2150// For any other errors (e.g. if any of the parameters are invalid) returns false.
2151bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2152 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2153 std::vector<uint8_t>* out_secondary_dex_hash) {
2154 out_secondary_dex_hash->clear();
2155
2156 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2157
2158 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2159 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2160 << storage_flag;
2161 return false;
2162 }
2163
2164 // Pipe to get the hash result back from our child process.
2165 unique_fd pipe_read, pipe_write;
2166 if (!Pipe(&pipe_read, &pipe_write)) {
2167 PLOG(ERROR) << "Failed to create pipe";
2168 return false;
2169 }
2170
2171 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2172 // access data the app itself can access.
2173 pid_t pid = fork();
2174 if (pid == 0) {
2175 // child -- drop privileges before continuing
2176 drop_capabilities(uid);
2177 pipe_read.reset();
2178
2179 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2180 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002181 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002182 }
2183
2184 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2185 if (fd == -1) {
2186 if (errno == EACCES || errno == ENOENT) {
2187 // Not treated as an error.
2188 _exit(0);
2189 }
2190 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002191 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002192 }
2193
2194 SHA256_CTX ctx;
2195 SHA256_Init(&ctx);
2196
2197 std::vector<uint8_t> buffer(65536);
2198 while (true) {
2199 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2200 if (bytes_read == 0) {
2201 break;
2202 } else if (bytes_read == -1) {
2203 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002204 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002205 }
2206
2207 SHA256_Update(&ctx, buffer.data(), bytes_read);
2208 }
2209
2210 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2211 SHA256_Final(hash.data(), &ctx);
2212 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002213 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002214 }
2215
2216 _exit(0);
2217 }
2218
2219 // parent
2220 pipe_write.reset();
2221
2222 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2223 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2224 out_secondary_dex_hash->clear();
2225 }
2226 return wait_child(pid) == 0;
2227}
2228
Jeff Sharkey90aff262016-12-12 14:28:24 -07002229// Helper for move_ab, so that we can have common failure-case cleanup.
2230static bool unlink_and_rename(const char* from, const char* to) {
2231 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2232 // return a failure.
2233 struct stat s;
2234 if (stat(to, &s) == 0) {
2235 if (!S_ISREG(s.st_mode)) {
2236 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2237 return false;
2238 }
2239 if (unlink(to) != 0) {
2240 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2241 return false;
2242 }
2243 } else {
2244 // This may be a permission problem. We could investigate the error code, but we'll just
2245 // let the rename failure do the work for us.
2246 }
2247
2248 // Try to rename "to" to "from."
2249 if (rename(from, to) != 0) {
2250 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2251 return false;
2252 }
2253 return true;
2254}
2255
2256// Move/rename a B artifact (from) to an A artifact (to).
2257static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2258 // Check whether B exists.
2259 {
2260 struct stat s;
2261 if (stat(b_path.c_str(), &s) != 0) {
2262 // Silently ignore for now. The service calling this isn't smart enough to understand
2263 // lack of artifacts at the moment.
2264 return false;
2265 }
2266 if (!S_ISREG(s.st_mode)) {
2267 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2268 // Try to unlink, but swallow errors.
2269 unlink(b_path.c_str());
2270 return false;
2271 }
2272 }
2273
2274 // Rename B to A.
2275 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2276 // Delete the b_path so we don't try again (or fail earlier).
2277 if (unlink(b_path.c_str()) != 0) {
2278 PLOG(ERROR) << "Could not unlink " << b_path;
2279 }
2280
2281 return false;
2282 }
2283
2284 return true;
2285}
2286
2287bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2288 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002289 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2290 if (slot_suffix.empty()) {
2291 return false;
2292 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002293
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002294 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2295 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2296 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002297 }
2298
2299 // Validate other inputs.
2300 if (validate_apk_path(apk_path) != 0) {
2301 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2302 return false;
2303 }
2304 if (validate_apk_path(oat_dir) != 0) {
2305 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2306 return false;
2307 }
2308
2309 char a_path[PKG_PATH_MAX];
2310 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2311 return false;
2312 }
2313 const std::string a_vdex_path = create_vdex_filename(a_path);
2314 const std::string a_image_path = create_image_filename(a_path);
2315
2316 // B path = A path + slot suffix.
2317 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2318 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2319 const std::string b_image_path = StringPrintf("%s.%s",
2320 a_image_path.c_str(),
2321 slot_suffix.c_str());
2322
2323 bool success = true;
2324 if (move_ab_path(b_path, a_path)) {
2325 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2326 // Note: we can live without an app image. As such, ignore failure to move the image file.
2327 // If we decide to require the app image, or the app image being moved correctly,
2328 // then change accordingly.
2329 constexpr bool kIgnoreAppImageFailure = true;
2330
2331 if (!a_image_path.empty()) {
2332 if (!move_ab_path(b_image_path, a_image_path)) {
2333 unlink(a_image_path.c_str());
2334 if (!kIgnoreAppImageFailure) {
2335 success = false;
2336 }
2337 }
2338 }
2339 } else {
2340 // Cleanup: delete B image, ignore errors.
2341 unlink(b_image_path.c_str());
2342 success = false;
2343 }
2344 } else {
2345 // Cleanup: delete B image, ignore errors.
2346 unlink(b_vdex_path.c_str());
2347 unlink(b_image_path.c_str());
2348 success = false;
2349 }
2350 return success;
2351}
2352
2353bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2354 // Delete the oat/odex file.
2355 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002356 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002357 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002358 return false;
2359 }
2360
2361 // In case of a permission failure report the issue. Otherwise just print a warning.
2362 auto unlink_and_check = [](const char* path) -> bool {
2363 int result = unlink(path);
2364 if (result != 0) {
2365 if (errno == EACCES || errno == EPERM) {
2366 PLOG(ERROR) << "Could not unlink " << path;
2367 return false;
2368 }
2369 PLOG(WARNING) << "Could not unlink " << path;
2370 }
2371 return true;
2372 };
2373
2374 // Delete the oat/odex file.
2375 bool return_value_oat = unlink_and_check(out_path);
2376
2377 // Derive and delete the app image.
2378 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2379
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002380 // Derive and delete the vdex file.
2381 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2382
Jeff Sharkey90aff262016-12-12 14:28:24 -07002383 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002384 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002385}
2386
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002387static bool is_absolute_path(const std::string& path) {
2388 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2389 LOG(ERROR) << "Invalid absolute path " << path;
2390 return false;
2391 } else {
2392 return true;
2393 }
2394}
2395
2396static bool is_valid_instruction_set(const std::string& instruction_set) {
2397 // TODO: add explicit whitelisting of instruction sets
2398 if (instruction_set.find('/') != std::string::npos) {
2399 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2400 return false;
2401 } else {
2402 return true;
2403 }
2404}
2405
2406bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2407 const char *apk_path, const char *instruction_set) {
2408 std::string oat_dir_ = oat_dir;
2409 std::string apk_path_ = apk_path;
2410 std::string instruction_set_ = instruction_set;
2411
2412 if (!is_absolute_path(oat_dir_)) return false;
2413 if (!is_absolute_path(apk_path_)) return false;
2414 if (!is_valid_instruction_set(instruction_set_)) return false;
2415
2416 std::string::size_type end = apk_path_.rfind('.');
2417 std::string::size_type start = apk_path_.rfind('/', end);
2418 if (end == std::string::npos || start == std::string::npos) {
2419 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2420 return false;
2421 }
2422
2423 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2424 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2425 const char* res = res_.c_str();
2426 if (strlen(res) >= PKG_PATH_MAX) {
2427 LOG(ERROR) << "Result too large";
2428 return false;
2429 } else {
2430 strlcpy(path, res, PKG_PATH_MAX);
2431 return true;
2432 }
2433}
2434
2435bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2436 const char *instruction_set) {
2437 std::string apk_path_ = apk_path;
2438 std::string instruction_set_ = instruction_set;
2439
2440 if (!is_absolute_path(apk_path_)) return false;
2441 if (!is_valid_instruction_set(instruction_set_)) return false;
2442
2443 std::string::size_type end = apk_path_.rfind('.');
2444 std::string::size_type start = apk_path_.rfind('/', end);
2445 if (end == std::string::npos || start == std::string::npos) {
2446 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2447 return false;
2448 }
2449
2450 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2451 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2452}
2453
2454bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2455 const char *instruction_set) {
2456 std::string src_ = src;
2457 std::string instruction_set_ = instruction_set;
2458
2459 if (!is_absolute_path(src_)) return false;
2460 if (!is_valid_instruction_set(instruction_set_)) return false;
2461
2462 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2463 if (*it == '/') {
2464 *it = '@';
2465 }
2466 }
2467
2468 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2469 + DALVIK_CACHE_POSTFIX;
2470 const char* res = res_.c_str();
2471 if (strlen(res) >= PKG_PATH_MAX) {
2472 LOG(ERROR) << "Result too large";
2473 return false;
2474 } else {
2475 strlcpy(path, res, PKG_PATH_MAX);
2476 return true;
2477 }
2478}
2479
Calin Juravle59f7ab82018-04-27 17:50:23 -07002480bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2481 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002482 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2483 for (const std::string& elem : classpaths_elems) {
2484 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2485 if (fd < 0) {
2486 PLOG(ERROR) << "Could not open classpath elem " << elem;
2487 return false;
2488 } else {
2489 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002490 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002491 }
2492 }
2493 return true;
2494}
2495
2496static bool create_app_profile_snapshot(int32_t app_id,
2497 const std::string& package_name,
2498 const std::string& profile_name,
2499 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002500 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2501
Calin Juravle824a64d2018-01-18 20:23:17 -08002502 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002503 if (snapshot_fd < 0) {
2504 return false;
2505 }
2506
2507 std::vector<unique_fd> profiles_fd;
2508 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002509 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2510 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002511 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2512 return false;
2513 }
2514
2515 profiles_fd.push_back(std::move(reference_profile_fd));
2516
Calin Juravle0d0a4922018-01-23 19:54:11 -08002517 // Open the class paths elements. These will be used to filter out profile data that does
2518 // not belong to the classpath during merge.
2519 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002520 std::vector<std::string> dex_locations;
2521 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002522 return false;
2523 }
2524
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002525 RunProfman args;
2526 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002527 pid_t pid = fork();
2528 if (pid == 0) {
2529 /* child -- drop privileges before continuing */
2530 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002531 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002532 }
2533
2534 /* parent */
2535 int return_code = wait_child(pid);
2536 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002537 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002538 return false;
2539 }
2540
2541 return true;
2542}
2543
Calin Juravle0d0a4922018-01-23 19:54:11 -08002544static bool create_boot_image_profile_snapshot(const std::string& package_name,
2545 const std::string& profile_name,
2546 const std::string& classpath) {
2547 // The reference profile directory for the android package might not be prepared. Do it now.
2548 const std::string ref_profile_dir =
2549 create_primary_reference_profile_package_dir_path(package_name);
2550 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2551 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2552 return false;
2553 }
2554
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002555 // Return false for empty class path since it may otherwise return true below if profiles is
2556 // empty.
2557 if (classpath.empty()) {
2558 PLOG(ERROR) << "Class path is empty";
2559 return false;
2560 }
2561
Calin Juravle0d0a4922018-01-23 19:54:11 -08002562 // Open and create the snapshot profile.
2563 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2564
2565 // Collect all non empty profiles.
2566 // The collection will traverse all applications profiles and find the non empty files.
2567 // This has the potential of inspecting a large number of files and directories (depending
2568 // on the number of applications and users). So there is a slight increase in the chance
2569 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2570 // fail the snapshot and aggregate whatever profile we could open.
2571 //
2572 // The profile snapshot is a best effort based on available data it's ok if some data
2573 // from some apps is missing. It will be counter productive for the snapshot to fail
2574 // because we could not open or read some of the files.
2575 std::vector<std::string> profiles;
2576 if (!collect_profiles(&profiles)) {
2577 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2578 }
2579
2580 // If we have no profiles return early.
2581 if (profiles.empty()) {
2582 return true;
2583 }
2584
2585 // Open the classpath elements. These will be used to filter out profile data that does
2586 // not belong to the classpath during merge.
2587 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002588 std::vector<std::string> dex_locations;
2589 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002590 return false;
2591 }
2592
2593 // If we could not open any files from the classpath return an error.
2594 if (apk_fds.empty()) {
2595 LOG(ERROR) << "Could not open any of the classpath elements.";
2596 return false;
2597 }
2598
2599 // Aggregate the profiles in batches of kAggregationBatchSize.
2600 // We do this to avoid opening a huge a amount of files.
2601 static constexpr size_t kAggregationBatchSize = 10;
2602
2603 std::vector<unique_fd> profiles_fd;
2604 for (size_t i = 0; i < profiles.size(); ) {
2605 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2606 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2607 if (fd.get() >= 0) {
2608 profiles_fd.push_back(std::move(fd));
2609 }
2610 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002611 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002612 args.SetupMerge(profiles_fd,
2613 snapshot_fd,
2614 apk_fds,
2615 dex_locations,
2616 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002617 pid_t pid = fork();
2618 if (pid == 0) {
2619 /* child -- drop privileges before continuing */
2620 drop_capabilities(AID_SYSTEM);
2621
Calin Juravle59f7ab82018-04-27 17:50:23 -07002622 // The introduction of new access flags into boot jars causes them to
2623 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002624 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002625 }
2626
2627 /* parent */
2628 int return_code = wait_child(pid);
2629 if (!WIFEXITED(return_code)) {
2630 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2631 return false;
2632 }
2633 return true;
2634 }
2635 return true;
2636}
2637
2638bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2639 const std::string& profile_name, const std::string& classpath) {
2640 if (app_id == -1) {
2641 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2642 } else {
2643 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2644 }
2645}
2646
Calin Juravlec3b049e2018-01-18 22:32:58 -08002647bool prepare_app_profile(const std::string& package_name,
2648 userid_t user_id,
2649 appid_t app_id,
2650 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002651 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002652 const std::unique_ptr<std::string>& dex_metadata) {
2653 // Prepare the current profile.
2654 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2655 /*is_secondary_dex*/ false);
2656 uid_t uid = multiuser_get_uid(user_id, app_id);
2657 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2658 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2659 return false;
2660 }
2661
2662 // Check if we need to install the profile from the dex metadata.
2663 if (dex_metadata == nullptr) {
2664 return true;
2665 }
2666
2667 // We have a dex metdata. Merge the profile into the reference profile.
2668 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2669 /*read_write*/ true, /*is_secondary_dex*/ false);
2670 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2671 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002672 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2673 if (apk_fd < 0) {
2674 PLOG(ERROR) << "Could not open code path " << code_path;
2675 return false;
2676 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002677
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002678 RunProfman args;
2679 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2680 std::move(ref_profile_fd),
2681 std::move(apk_fd),
2682 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002683 pid_t pid = fork();
2684 if (pid == 0) {
2685 /* child -- drop privileges before continuing */
2686 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2687 drop_capabilities(app_shared_gid);
2688
Calin Juravlef63d4792018-01-30 17:43:34 +00002689 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002690 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002691 }
2692
2693 /* parent */
2694 int return_code = wait_child(pid);
2695 if (!WIFEXITED(return_code)) {
2696 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2697 return false;
2698 }
2699 return true;
2700}
2701
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002702} // namespace installd
2703} // namespace android