blob: 852aa799fbf3c869f0000d685293d19d9521be8d [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 Chartierd41622c2019-01-31 12:59:39 -0800317 std::string resolve_startup_string_arg =
318 MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
319 "--resolve-startup-const-strings=%s");
320 if (resolve_startup_string_arg.empty()) {
321 // If empty, fall back to system property.
322 resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800323 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
324 "--resolve-startup-const-strings=%s");
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800325 }
Mathieu Chartier5880c032018-11-28 19:15:41 -0800326
327 const std::string image_block_size_arg =
328 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
329 "--max-image-block-size=%s");
330
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800331 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700332
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800333 std::string image_format_arg;
334 if (image_fd >= 0) {
335 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000336 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000337
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800338 std::string dex2oat_large_app_threshold_arg =
339 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000340
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800341 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
Roland Levillain67a14f62019-01-23 15:59:50 +0000342 const char* dex2oat_bin = kDex2oatPath;
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800343 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
344 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
345 if (is_debug_runtime() ||
346 (background_job_compile && is_debuggable_build() && !is_release)) {
347 if (access(kDex2oatDebugPath, X_OK) == 0) {
348 dex2oat_bin = kDex2oatDebugPath;
349 }
350 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000351
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800352 bool generate_minidebug_info = kEnableMinidebugInfo &&
353 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000354
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800355 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
356 // use arraysize instead.
357 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
358 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
359 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
360 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
361 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
362 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
363 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
364 std::string dex2oat_compiler_filter_arg;
365 std::string dex2oat_swap_fd;
366 std::string dex2oat_image_fd;
367 std::string target_sdk_version_arg;
368 if (target_sdk_version != 0) {
369 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
370 }
371 std::string class_loader_context_arg;
372 if (class_loader_context != nullptr) {
373 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
374 class_loader_context);
375 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000376
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800377 if (swap_fd >= 0) {
378 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
379 }
380 if (image_fd >= 0) {
381 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
382 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000383
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800384 // Compute compiler filter.
385 bool have_dex2oat_relocation_skip_flag = false;
386 if (skip_compilation) {
387 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
388 have_dex2oat_relocation_skip_flag = true;
389 } else if (compiler_filter != nullptr) {
390 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
391 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000392
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800393 if (dex2oat_compiler_filter_arg.empty()) {
394 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
395 "--compiler-filter=%s");
396 }
397
398 // Check whether all apps should be compiled debuggable.
399 if (!debuggable) {
400 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
401 }
402 std::string profile_arg;
403 if (profile_fd != -1) {
404 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
405 }
406
407 // Get the directory of the apk to pass as a base classpath directory.
408 std::string base_dir;
409 std::string apk_dir(input_file_name);
410 unsigned long dir_index = apk_dir.rfind('/');
411 bool has_base_dir = dir_index != std::string::npos;
412 if (has_base_dir) {
413 apk_dir = apk_dir.substr(0, dir_index);
414 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
415 }
416
417 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
418
419 std::string compilation_reason_arg = compilation_reason == nullptr
420 ? ""
421 : std::string("--compilation-reason=") + compilation_reason;
422
423 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
424
425 // Disable cdex if update input vdex is true since this combination of options is not
426 // supported.
427 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
428
429 AddArg(zip_fd_arg);
430 AddArg(zip_location_arg);
431 AddArg(input_vdex_fd_arg);
432 AddArg(output_vdex_fd_arg);
433 AddArg(oat_fd_arg);
434 AddArg(oat_location_arg);
435 AddArg(instruction_set_arg);
436
437 AddArg(instruction_set_variant_arg);
438 AddArg(instruction_set_features_arg);
439
440 AddRuntimeArg(dex2oat_Xms_arg);
441 AddRuntimeArg(dex2oat_Xmx_arg);
442
443 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800444 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800445 AddArg(dex2oat_compiler_filter_arg);
446 AddArg(dex2oat_threads_arg);
447 AddArg(dex2oat_swap_fd);
448 AddArg(dex2oat_image_fd);
449
450 if (generate_debug_info) {
451 AddArg("--generate-debug-info");
452 }
453 if (debuggable) {
454 AddArg("--debuggable");
455 }
456 AddArg(image_format_arg);
457 AddArg(dex2oat_large_app_threshold_arg);
458
459 if (have_dex2oat_relocation_skip_flag) {
460 AddRuntimeArg(dex2oat_norelocation);
461 }
462 AddArg(profile_arg);
463 AddArg(base_dir);
464 AddArg(class_loader_context_arg);
465 if (generate_minidebug_info) {
466 AddArg(kMinidebugDex2oatFlag);
467 }
468 if (disable_cdex) {
469 AddArg(kDisableCompactDexFlag);
470 }
471 AddArg(target_sdk_version_arg);
472 if (enable_hidden_api_checks) {
473 AddRuntimeArg("-Xhidden-api-checks");
474 }
475
476 if (dex_metadata_fd > -1) {
477 AddArg(dex_metadata_fd_arg);
478 }
479
480 AddArg(compilation_reason_arg);
481
482 // Do not add args after dex2oat_flags, they should override others for debugging.
483 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
484
485 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000486 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800487};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700488
489/*
490 * Whether dexopt should use a swap file when compiling an APK.
491 *
492 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
493 * itself, anyways).
494 *
495 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
496 *
497 * Otherwise, return true if this is a low-mem device.
498 *
499 * Otherwise, return default value.
500 */
501static bool kAlwaysProvideSwapFile = false;
502static bool kDefaultProvideSwapFile = true;
503
504static bool ShouldUseSwapFileForDexopt() {
505 if (kAlwaysProvideSwapFile) {
506 return true;
507 }
508
509 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700510 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
511 if (!dex2oat_prop_buf.empty()) {
512 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700513 }
514
515 // Shortcut for default value. This is an implementation optimization for the process sketched
516 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
517 // as low-mem is never returning false. The compiler will optimize this away if it can.
518 if (kDefaultProvideSwapFile) {
519 return true;
520 }
521
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700522 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700523 return true;
524 }
525
526 // Default value must be false here.
527 return kDefaultProvideSwapFile;
528}
529
Richard Uhler76cc0272016-12-08 10:46:35 +0000530static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700531 if (set_to_bg) {
532 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800533 PLOG(ERROR) << "set_sched_policy failed";
534 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700535 }
536 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800537 PLOG(ERROR) << "setpriority failed";
538 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700539 }
540 }
541}
542
Calin Juravle29591732017-11-20 17:46:19 -0800543static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
544 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800545 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800546 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800547 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800548 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800549 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700550 }
Calin Juravle114f0812017-03-08 19:05:07 -0800551 // Profiles should belong to the app; make sure of that by giving ownership to
552 // the app uid. If we cannot do that, there's no point in returning the fd
553 // since dex2oat/profman will fail with SElinux denials.
554 if (fchown(fd.get(), uid, uid) < 0) {
555 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800556 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800557 }
Calin Juravle29591732017-11-20 17:46:19 -0800558 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800559}
560
Calin Juravle29591732017-11-20 17:46:19 -0800561static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800562 // Do not follow symlinks when opening a profile:
563 // - primary profiles should not contain symlinks in their paths
564 // - secondary dex paths should have been already resolved and validated
565 flags |= O_NOFOLLOW;
566
Calin Juravle29591732017-11-20 17:46:19 -0800567 // Check if we need to create the profile
568 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
569 unique_fd fd;
570 if ((flags & O_CREAT) != 0) {
571 fd = create_profile(uid, profile, flags);
572 } else {
573 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
574 }
575
Calin Juravle114f0812017-03-08 19:05:07 -0800576 if (fd.get() < 0) {
577 if (errno != ENOENT) {
578 // Profiles might be missing for various reasons. For example, in a
579 // multi-user environment, the profile directory for one user can be created
580 // after we start a merge. In this case the current profile for that user
581 // will not be found.
582 // Also, the secondary dex profiles might be deleted by the app at any time,
583 // so we can't we need to prepare if they are missing.
584 PLOG(ERROR) << "Failed to open profile " << profile;
585 }
586 return invalid_unique_fd();
587 }
588
Jeff Sharkey90aff262016-12-12 14:28:24 -0700589 return fd;
590}
591
Calin Juravle824a64d2018-01-18 20:23:17 -0800592static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
593 const std::string& location, bool is_secondary_dex) {
594 std::string profile = create_current_profile_path(user, package_name, location,
595 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800596 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800597}
598
Calin Juravle824a64d2018-01-18 20:23:17 -0800599static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
600 const std::string& location, bool read_write, bool is_secondary_dex) {
601 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800602 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
603}
604
605static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800606 const std::string& location) {
607 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800608 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800609}
610
Calin Juravle824a64d2018-01-18 20:23:17 -0800611static void open_profile_files(uid_t uid, const std::string& package_name,
612 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800613 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700614 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800615 *reference_profile_fd = open_reference_profile(uid, package_name, location,
616 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617
Calin Juravle114f0812017-03-08 19:05:07 -0800618 // For secondary dex files, we don't really need the user but we use it for sanity checks.
619 // Note: the user owning the dex file should be the current user.
620 std::vector<userid_t> users;
621 if (is_secondary_dex){
622 users.push_back(multiuser_get_user_id(uid));
623 } else {
624 users = get_known_users(/*volume_uuid*/ nullptr);
625 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800627 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
628 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700629 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800630 if (profile_fd.get() >= 0) {
631 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700632 }
633 }
634}
635
Jeff Sharkey90aff262016-12-12 14:28:24 -0700636static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
637static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
638static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
639static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
640static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
641
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800642class RunProfman : public ExecVHelper {
643 public:
644 void SetupArgs(const std::vector<unique_fd>& profile_fds,
645 const unique_fd& reference_profile_fd,
646 const std::vector<unique_fd>& apk_fds,
647 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800648 bool copy_and_update,
649 bool store_aggregation_counters) {
Roland Levillain67a14f62019-01-23 15:59:50 +0000650 const char* profman_bin = is_debug_runtime() ? kProfmanDebugPath: kProfmanPath;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700651
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800652 if (copy_and_update) {
653 CHECK_EQ(1u, profile_fds.size());
654 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000655 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800656 if (reference_profile_fd != -1) {
657 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000658 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800659
660 for (const unique_fd& fd : profile_fds) {
661 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
662 }
663
664 for (const unique_fd& fd : apk_fds) {
665 AddArg("--apk-fd=" + std::to_string(fd.get()));
666 }
667
668 for (const std::string& dex_location : dex_locations) {
669 AddArg("--dex-location=" + dex_location);
670 }
671
672 if (copy_and_update) {
673 AddArg("--copy-and-update-profile-key");
674 }
675
Calin Juravleb3a929d2018-12-11 14:40:00 -0800676 if (store_aggregation_counters) {
677 AddArg("--store-aggregation-counters");
678 }
679
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800680 // Do not add after dex2oat_flags, they should override others for debugging.
681 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800682 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700683
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800684 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
685 const unique_fd& reference_profile_fd,
686 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800687 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
688 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800689 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800690 reference_profile_fd,
691 apk_fds,
692 dex_locations,
693 /*copy_and_update=*/false,
694 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800695 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700696
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800697 void SetupCopyAndUpdate(unique_fd&& profile_fd,
698 unique_fd&& reference_profile_fd,
699 unique_fd&& apk_fd,
700 const std::string& dex_location) {
701 // The fds need to stay open longer than the scope of the function, so put them into a local
702 // variable vector.
703 profiles_fd_.push_back(std::move(profile_fd));
704 apk_fds_.push_back(std::move(apk_fd));
705 reference_profile_fd_ = std::move(reference_profile_fd);
706 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800707 SetupArgs(profiles_fd_,
708 reference_profile_fd_,
709 apk_fds_,
710 dex_locations,
711 /*copy_and_update=*/true,
712 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800713 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000714
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800715 void SetupDump(const std::vector<unique_fd>& profiles_fd,
716 const unique_fd& reference_profile_fd,
717 const std::vector<std::string>& dex_locations,
718 const std::vector<unique_fd>& apk_fds,
719 const unique_fd& output_fd) {
720 AddArg("--dump-only");
721 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800722 SetupArgs(profiles_fd,
723 reference_profile_fd,
724 apk_fds,
725 dex_locations,
726 /*copy_and_update=*/false,
727 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800728 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000729
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800730 void Exec() {
731 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
732 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000733
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800734 private:
735 unique_fd reference_profile_fd_;
736 std::vector<unique_fd> profiles_fd_;
737 std::vector<unique_fd> apk_fds_;
738};
Mathieu Chartier31636522018-11-09 23:53:07 +0000739
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800740
Calin Juravlef63d4792018-01-30 17:43:34 +0000741
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800743// The location is the package name for primary apks or the dex path for secondary dex files.
744// Returns true if there is enough information in the current profiles that makes it
745// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700746// If the return value is true all the current profiles would have been merged into
747// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800748static bool analyze_profiles(uid_t uid, const std::string& package_name,
749 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800750 std::vector<unique_fd> profiles_fd;
751 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800752 open_profile_files(uid, package_name, location, is_secondary_dex,
753 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800754 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700755 // Skip profile guided compilation because no profiles were found.
756 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700757 return false;
758 }
759
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800760 RunProfman profman_merge;
761 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700762 pid_t pid = fork();
763 if (pid == 0) {
764 /* child -- drop privileges before continuing */
765 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800766 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700767 }
768 /* parent */
769 int return_code = wait_child(pid);
770 bool need_to_compile = false;
771 bool should_clear_current_profiles = false;
772 bool should_clear_reference_profile = false;
773 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800774 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 } else {
776 return_code = WEXITSTATUS(return_code);
777 switch (return_code) {
778 case PROFMAN_BIN_RETURN_CODE_COMPILE:
779 need_to_compile = true;
780 should_clear_current_profiles = true;
781 should_clear_reference_profile = false;
782 break;
783 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
784 need_to_compile = false;
785 should_clear_current_profiles = false;
786 should_clear_reference_profile = false;
787 break;
788 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800789 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700790 need_to_compile = false;
791 should_clear_current_profiles = true;
792 should_clear_reference_profile = true;
793 break;
794 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
795 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
796 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800797 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700798 need_to_compile = false;
799 should_clear_current_profiles = false;
800 should_clear_reference_profile = false;
801 break;
802 default:
803 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800804 LOG(WARNING) << "Unknown error code while processing profiles for location "
805 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806 need_to_compile = false;
807 should_clear_current_profiles = true;
808 should_clear_reference_profile = true;
809 break;
810 }
811 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800812
Jeff Sharkey90aff262016-12-12 14:28:24 -0700813 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800814 if (is_secondary_dex) {
815 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800816 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
817 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800818 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800819 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800820 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821 }
822 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800823 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700824 }
825 return need_to_compile;
826}
827
Calin Juravle114f0812017-03-08 19:05:07 -0800828// Decides if profile guided compilation is needed or not based on existing profiles.
829// The analysis is done for the primary apks of the given package.
830// Returns true if there is enough information in the current profiles that makes it
831// worth to recompile the package.
832// If the return value is true all the current profiles would have been merged into
833// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800834bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
835 const std::string& profile_name) {
836 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800837}
838
Calin Juravle408cd4a2018-01-20 23:34:18 -0800839bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
840 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800841 std::vector<unique_fd> profile_fds;
842 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800843 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
844 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700845
Calin Juravle408cd4a2018-01-20 23:34:18 -0800846 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800847 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700848
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800849 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 const bool has_profiles = !profile_fds.empty();
851
852 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800853 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700854 return false;
855 }
856
Calin Juravle114f0812017-03-08 19:05:07 -0800857 unique_fd output_fd(open(out_file_name.c_str(),
858 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700859 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800860 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700861 return false;
862 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800863
Jeff Sharkey90aff262016-12-12 14:28:24 -0700864 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800865 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800866 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
867 if (apk_fd == -1) {
868 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
869 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800871 dex_locations.push_back(get_location_from_path(code_path.c_str()));
872 apk_fds.push_back(std::move(apk_fd));
873
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800875 RunProfman profman_dump;
876 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877 pid_t pid = fork();
878 if (pid == 0) {
879 /* child -- drop privileges before continuing */
880 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800881 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 }
883 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 int return_code = wait_child(pid);
885 if (!WIFEXITED(return_code)) {
886 LOG(WARNING) << "profman failed for package " << pkgname << ": "
887 << return_code;
888 return false;
889 }
890 return true;
891}
892
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700893bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800894 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700895 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
896 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800897 package_name,
898 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700899 /*read_write*/ true,
900 /*secondary*/ false));
901 if (in_fd.get() < 0) {
902 PLOG(WARNING) << "Could not open profile " << system_profile;
903 return false;
904 }
905 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800906 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700907 return false;
908 }
909
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700910 // As a security measure we want to write the profile information with the reduced capabilities
911 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700912 pid_t pid = fork();
913 if (pid == 0) {
914 /* child -- drop privileges before continuing */
915 drop_capabilities(packageUid);
916
917 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
918 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800919 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700920 }
921 // This implies that the app owning this profile is running
922 // (and has acquired the lock).
923 //
924 // The app never acquires the lock for the reference profiles of primary apks.
925 // Only dex2oat from installd will do that. Since installd is single threaded
926 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800927 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700928 return false;
929 }
930
931 bool truncated = ftruncate(out_fd.get(), 0) == 0;
932 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800933 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700934 }
935
936 // Copy over data.
937 static constexpr size_t kBufferSize = 4 * 1024;
938 char buffer[kBufferSize];
939 while (true) {
940 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
941 if (bytes == 0) {
942 break;
943 }
944 write(out_fd.get(), buffer, bytes);
945 }
946 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800947 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700948 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700949 // Use _exit since we don't want to run the global destructors in the child.
950 // b/62597429
951 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700952 }
953 /* parent */
954 int return_code = wait_child(pid);
955 return return_code == 0;
956}
957
Jeff Sharkey90aff262016-12-12 14:28:24 -0700958static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
959 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
960 if (EndsWith(oat_path, ".dex")) {
961 std::string new_path = oat_path;
962 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800963 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964 return new_path;
965 }
966
967 // An odex entry. Not that this may not be an extension, e.g., in the OTA
968 // case (where the base name will have an extension for the B artifact).
969 size_t odex_pos = oat_path.rfind(".odex");
970 if (odex_pos != std::string::npos) {
971 std::string new_path = oat_path;
972 new_path.replace(odex_pos, strlen(".odex"), new_ext);
973 CHECK_NE(new_path.find(new_ext), std::string::npos);
974 return new_path;
975 }
976
977 // Don't know how to handle this.
978 return "";
979}
980
981// Translate the given oat path to an art (app image) path. An empty string
982// denotes an error.
983static std::string create_image_filename(const std::string& oat_path) {
984 return replace_file_extension(oat_path, ".art");
985}
986
987// Translate the given oat path to a vdex path. An empty string denotes an error.
988static std::string create_vdex_filename(const std::string& oat_path) {
989 return replace_file_extension(oat_path, ".vdex");
990}
991
Jeff Sharkey90aff262016-12-12 14:28:24 -0700992static int open_output_file(const char* file_name, bool recreate, int permissions) {
993 int flags = O_RDWR | O_CREAT;
994 if (recreate) {
995 if (unlink(file_name) < 0) {
996 if (errno != ENOENT) {
997 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
998 }
999 }
1000 flags |= O_EXCL;
1001 }
1002 return open(file_name, flags, permissions);
1003}
1004
Calin Juravle2289c0a2017-02-15 12:44:14 -08001005static bool set_permissions_and_ownership(
1006 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1007 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1008 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 if (fchmod(fd,
1010 S_IRUSR|S_IWUSR|S_IRGRP |
1011 (is_public ? S_IROTH : 0)) < 0) {
1012 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1013 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001014 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001015 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1016 return false;
1017 }
1018 return true;
1019}
1020
1021static bool IsOutputDalvikCache(const char* oat_dir) {
1022 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1023 // into '!'. Play it safe by handling it both.
1024 // TODO: ensure we never get null.
1025 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1026 return oat_dir == nullptr || oat_dir[0] == '!';
1027}
1028
Calin Juravled23dee72017-07-06 16:29:11 -07001029// Best-effort check whether we can fit the the path into our buffers.
1030// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1031// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1032// extension to the cache path (5 bytes).
1033// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1034static bool validate_dex_path_size(const std::string& dex_path) {
1035 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1036 LOG(ERROR) << "dex_path too long: " << dex_path;
1037 return false;
1038 }
1039 return true;
1040}
1041
Jeff Sharkey90aff262016-12-12 14:28:24 -07001042static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001043 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001044 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001045 return false;
1046 }
1047
1048 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001049 // Oat dirs for secondary dex files are already validated.
1050 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001051 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1052 return false;
1053 }
1054 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1055 return false;
1056 }
1057 } else {
1058 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1059 return false;
1060 }
1061 }
1062 return true;
1063}
1064
1065// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1066// on destruction. It will also run the given cleanup (unless told not to) after closing.
1067//
1068// Usage example:
1069//
Calin Juravle7a570e82017-01-14 16:23:30 -08001070// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001071// [name]() {
1072// unlink(name.c_str());
1073// });
1074// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1075// wrapper if captured as a reference.
1076//
1077// if (file.get() == -1) {
1078// // Error opening...
1079// }
1080//
1081// ...
1082// if (error) {
1083// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1084// // and delete the file (after the fd is closed).
1085// return -1;
1086// }
1087//
1088// (Success case)
1089// file.SetCleanup(false);
1090// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1091// // (leaving the file around; after the fd is closed).
1092//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001093class Dex2oatFileWrapper {
1094 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001095 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001096 }
1097
Calin Juravle7a570e82017-01-14 16:23:30 -08001098 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1099 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1100
1101 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1102 value_ = other.value_;
1103 cleanup_ = other.cleanup_;
1104 do_cleanup_ = other.do_cleanup_;
1105 auto_close_ = other.auto_close_;
1106 other.release();
1107 }
1108
1109 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1110 value_ = other.value_;
1111 cleanup_ = other.cleanup_;
1112 do_cleanup_ = other.do_cleanup_;
1113 auto_close_ = other.auto_close_;
1114 other.release();
1115 return *this;
1116 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001117
1118 ~Dex2oatFileWrapper() {
1119 reset(-1);
1120 }
1121
1122 int get() {
1123 return value_;
1124 }
1125
1126 void SetCleanup(bool cleanup) {
1127 do_cleanup_ = cleanup;
1128 }
1129
1130 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001131 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132 close(value_);
1133 }
1134 if (do_cleanup_ && cleanup_ != nullptr) {
1135 cleanup_();
1136 }
1137
1138 value_ = new_value;
1139 }
1140
Calin Juravle7a570e82017-01-14 16:23:30 -08001141 void reset(int new_value, std::function<void ()> new_cleanup) {
1142 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001143 close(value_);
1144 }
1145 if (do_cleanup_ && cleanup_ != nullptr) {
1146 cleanup_();
1147 }
1148
1149 value_ = new_value;
1150 cleanup_ = new_cleanup;
1151 }
1152
Calin Juravle7a570e82017-01-14 16:23:30 -08001153 void DisableAutoClose() {
1154 auto_close_ = false;
1155 }
1156
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 void release() {
1159 value_ = -1;
1160 do_cleanup_ = false;
1161 cleanup_ = nullptr;
1162 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001163 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001166 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001167};
1168
Calin Juravle7a570e82017-01-14 16:23:30 -08001169// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001170Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1171 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001172
1173 // We don't create an image for secondary dex files.
1174 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001175 return Dex2oatFileWrapper();
1176 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 const std::string image_path = create_image_filename(out_oat_path);
1179 if (image_path.empty()) {
1180 // Happens when the out_oat_path has an unknown extension.
1181 return Dex2oatFileWrapper();
1182 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001183
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001184 // In case there is a stale image, remove it now. Ignore any error.
1185 unlink(image_path.c_str());
1186
1187 // Not enabled, exit.
1188 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001189 return Dex2oatFileWrapper();
1190 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001191 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1192 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001193 return Dex2oatFileWrapper();
1194 }
1195 // Recreate is true since we do not want to modify a mapped image. If the app is
1196 // already running and we modify the image file, it can cause crashes (b/27493510).
1197 Dex2oatFileWrapper wrapper_fd(
1198 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1199 [image_path]() { unlink(image_path.c_str()); });
1200 if (wrapper_fd.get() < 0) {
1201 // Could not create application image file. Go on since we can compile without it.
1202 LOG(ERROR) << "installd could not create '" << image_path
1203 << "' for image file during dexopt";
1204 // If we have a valid image file path but no image fd, explicitly erase the image file.
1205 if (unlink(image_path.c_str()) < 0) {
1206 if (errno != ENOENT) {
1207 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1208 }
1209 }
1210 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001211 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001212 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1213 wrapper_fd.reset(-1);
1214 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001215
Calin Juravle7a570e82017-01-14 16:23:30 -08001216 return wrapper_fd;
1217}
1218
1219// Creates the dexopt swap file if necessary and return its fd.
1220// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001221unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001222 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001223 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001224 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001225 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001226 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001227 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001228 if (swap_fd.get() < 0) {
1229 // Could not create swap file. Optimistically go on and hope that we can compile
1230 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001231 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001232 } else {
1233 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001234 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001235 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1236 }
1237 }
1238 return swap_fd;
1239}
1240
1241// Opens the reference profiles if needed.
1242// 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 -08001243Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001244 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001245 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001246 // If we are not profile guided compilation, or we are compiling system server
1247 // do not bother to open the profiles; we won't be using them.
1248 if (!profile_guided || (pkgname[0] == '*')) {
1249 return Dex2oatFileWrapper();
1250 }
1251
1252 // If this is a secondary dex path which is public do not open the profile.
1253 // We cannot compile public secondary dex paths with profiles. That's because
1254 // it will expose how the dex files are used by their owner.
1255 //
1256 // Note that the PackageManager is responsible to set the is_public flag for
1257 // primary apks and we do not check it here. In some cases, e.g. when
1258 // compiling with a public profile from the .dm file the PackageManager will
1259 // set is_public toghether with the profile guided compilation.
1260 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001261 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001262 }
Calin Juravle114f0812017-03-08 19:05:07 -08001263
1264 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001265 std::string location;
1266 if (is_secondary_dex) {
1267 location = dex_path;
1268 } else {
1269 if (profile_name == nullptr) {
1270 // This path is taken for system server re-compilation lunched from ZygoteInit.
1271 return Dex2oatFileWrapper();
1272 } else {
1273 location = profile_name;
1274 }
1275 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001276 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1277 is_secondary_dex);
1278 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1279 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001280 };
1281 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001282}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001283
Calin Juravle7a570e82017-01-14 16:23:30 -08001284// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1285// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001286bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001287 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001288 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001289 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1290 CHECK(in_vdex_wrapper_fd != nullptr);
1291 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1293 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001294 char in_odex_path[PKG_PATH_MAX];
1295 int dexopt_action = abs(dexopt_needed);
1296 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001297 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001298
1299 // Infer the name of the output VDEX.
1300 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1301 if (out_vdex_path_str.empty()) {
1302 return false;
1303 }
1304
1305 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001306 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001307 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1308 const char* path = nullptr;
1309 if (is_odex_location) {
1310 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1311 path = in_odex_path;
1312 } else {
1313 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001314 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001315 }
1316 } else {
1317 path = out_oat_path;
1318 }
1319 in_vdex_path_str = create_vdex_filename(path);
1320 if (in_vdex_path_str.empty()) {
1321 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001322 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001323 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001324 // We can update in place when all these conditions are met:
1325 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1326 // on /system typically cannot be updated in place).
1327 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1328 // cannot be currently used by a running process.
1329 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1330 // different vdex files to operate.
1331 update_vdex_in_place =
1332 (in_vdex_path_str == out_vdex_path_str) &&
1333 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1334 !profile_guided;
1335 if (update_vdex_in_place) {
1336 // Open the file read-write to be able to update it.
1337 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1338 if (in_vdex_wrapper_fd->get() == -1) {
1339 // If we failed to open the file, we cannot update it in place.
1340 update_vdex_in_place = false;
1341 }
1342 } else {
1343 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1344 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001345 }
1346
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001347 // If we are updating the vdex in place, we do not need to recreate a vdex,
1348 // and can use the same existing one.
1349 if (update_vdex_in_place) {
1350 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1351 // have bogus stale vdex files.
1352 out_vdex_wrapper_fd->reset(
1353 in_vdex_wrapper_fd->get(),
1354 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1355 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1356 // wrapper).
1357 in_vdex_wrapper_fd->DisableAutoClose();
1358 } else {
1359 out_vdex_wrapper_fd->reset(
1360 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1361 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1362 if (out_vdex_wrapper_fd->get() < 0) {
1363 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1364 return false;
1365 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001366 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001367 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001368 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001369 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1370 return false;
1371 }
1372
1373 // If we got here we successfully opened the vdex files.
1374 return true;
1375}
1376
1377// Opens the output oat file for the given apk.
1378// If successful it stores the output path into out_oat_path and returns true.
1379Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001380 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1381 char* out_oat_path) {
1382 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001383 return Dex2oatFileWrapper();
1384 }
1385 const std::string out_oat_path_str(out_oat_path);
1386 Dex2oatFileWrapper wrapper_fd(
1387 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1388 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1389 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001390 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001391 } else if (!set_permissions_and_ownership(
1392 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001393 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1394 wrapper_fd.reset(-1);
1395 }
1396 return wrapper_fd;
1397}
1398
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001399// Creates RDONLY fds for oat and vdex files, if exist.
1400// Returns false if it fails to create oat out path for the given apk path.
1401// Note that the method returns true even if the files could not be opened.
1402bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1403 const std::string& oat_dir,
1404 const std::string& instruction_set,
1405 bool is_secondary_dex,
1406 unique_fd* oat_file_fd,
1407 unique_fd* vdex_file_fd) {
1408 char oat_path[PKG_PATH_MAX];
1409 if (!create_oat_out_path(apk_path.c_str(),
1410 instruction_set.c_str(),
1411 oat_dir.c_str(),
1412 is_secondary_dex,
1413 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001414 LOG(ERROR) << "Could not create oat out path for "
1415 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001416 return false;
1417 }
1418 oat_file_fd->reset(open(oat_path, O_RDONLY));
1419 if (oat_file_fd->get() < 0) {
1420 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1421 }
1422
1423 std::string vdex_filename = create_vdex_filename(oat_path);
1424 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1425 if (vdex_file_fd->get() < 0) {
1426 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1427 }
1428
1429 return true;
1430}
1431
Calin Juravle7a570e82017-01-14 16:23:30 -08001432// Updates the access times of out_oat_path based on those from apk_path.
1433void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1434 struct stat input_stat;
1435 memset(&input_stat, 0, sizeof(input_stat));
1436 if (stat(apk_path, &input_stat) != 0) {
1437 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1438 return;
1439 }
1440
1441 struct utimbuf ut;
1442 ut.actime = input_stat.st_atime;
1443 ut.modtime = input_stat.st_mtime;
1444 if (utime(out_oat_path, &ut) != 0) {
1445 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1446 }
1447}
1448
Calin Juravle80a21252017-01-17 14:43:25 -08001449// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001450// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1451// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1452// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001453class RunDexoptAnalyzer : public ExecVHelper {
1454 public:
1455 RunDexoptAnalyzer(const std::string& dex_file,
1456 int vdex_fd,
1457 int oat_fd,
1458 int zip_fd,
1459 const std::string& instruction_set,
1460 const std::string& compiler_filter,
1461 bool profile_was_updated,
1462 bool downgrade,
1463 const char* class_loader_context) {
1464 CHECK_GE(zip_fd, 0);
1465 const char* dexoptanalyzer_bin =
Roland Levillain67a14f62019-01-23 15:59:50 +00001466 is_debug_runtime() ? kDexoptanalyzerDebugPath : kDexoptanalyzerPath;
Calin Juravle80a21252017-01-17 14:43:25 -08001467
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001468 std::string dex_file_arg = "--dex-file=" + dex_file;
1469 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1470 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1471 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1472 std::string isa_arg = "--isa=" + instruction_set;
1473 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1474 const char* assume_profile_changed = "--assume-profile-changed";
1475 const char* downgrade_flag = "--downgrade";
1476 std::string class_loader_context_arg = "--class-loader-context=";
1477 if (class_loader_context != nullptr) {
1478 class_loader_context_arg += class_loader_context;
1479 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001480
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001481 // program name, dex file, isa, filter
1482 AddArg(dex_file_arg);
1483 AddArg(isa_arg);
1484 AddArg(compiler_filter_arg);
1485 if (oat_fd >= 0) {
1486 AddArg(oat_fd_arg);
1487 }
1488 if (vdex_fd >= 0) {
1489 AddArg(vdex_fd_arg);
1490 }
1491 AddArg(zip_fd_arg.c_str());
1492 if (profile_was_updated) {
1493 AddArg(assume_profile_changed);
1494 }
1495 if (downgrade) {
1496 AddArg(downgrade_flag);
1497 }
1498 if (class_loader_context != nullptr) {
1499 AddArg(class_loader_context_arg.c_str());
1500 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001501
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001502 PrepareArgs(dexoptanalyzer_bin);
1503 }
1504};
Calin Juravle80a21252017-01-17 14:43:25 -08001505
1506// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001507static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001508 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001509 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001510 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001511 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001512 return false;
1513 }
Calin Juravle114f0812017-03-08 19:05:07 -08001514 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001515
Calin Juravle80a21252017-01-17 14:43:25 -08001516 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001517 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1518 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001519 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001520 return false;
1521 }
1522
1523 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001524 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001525
Calin Juravle7d765462017-09-04 15:57:10 -07001526 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001527 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001528 return false;
1529 }
1530
1531 return true;
1532}
1533
Calin Juravle7d765462017-09-04 15:57:10 -07001534// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1535// secondary dex files. This return codes are returned by the child process created for
1536// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001537
Andreas Gampe194fe422018-02-28 20:16:19 -08001538enum DexoptAnalyzerSkipCodes {
1539 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001540 // Specific errors are encoded in the name.
1541 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1542 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1543 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1544 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1545 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001546 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001547 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001548};
Calin Juravle7d765462017-09-04 15:57:10 -07001549
1550// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001551// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1552// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001553// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1554// of dexoptanalyzer.
1555static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001556 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001557 // The result values are defined in dexoptanalyzer.
1558 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001559 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001560 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001561 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001562 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001563 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001564 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001565 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001566 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001567 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1568 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001569 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1570 " Expected odex file status for secondary dex %s"
1571 " : dexoptanalyzer result=%d",
1572 dex_path.c_str(),
1573 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001574 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001575 }
1576
1577 // Use a second switch for enum switch-case analysis.
1578 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001579 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001580 // If the file does not exist there's no need for dexopt.
1581 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1582 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001583
1584 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1585 *error_msg = "Dexoptanalyzer path validation failed";
1586 return false;
1587 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1588 *error_msg = "Dexoptanalyzer open zip failed";
1589 return false;
1590 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1591 *error_msg = "Dexoptanalyzer dir preparation failed";
1592 return false;
1593 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1594 *error_msg = "Dexoptanalyzer open output failed";
1595 return false;
1596 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1597 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001598 return false;
1599 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001600
1601 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1602 dex_path.c_str(),
1603 result);
1604 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001605}
1606
Calin Juravle7d765462017-09-04 15:57:10 -07001607enum SecondaryDexAccess {
1608 kSecondaryDexAccessReadOk = 0,
1609 kSecondaryDexAccessDoesNotExist = 1,
1610 kSecondaryDexAccessPermissionError = 2,
1611 kSecondaryDexAccessIOError = 3
1612};
1613
1614static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1615 // Check if the path exists and can be read. If not, there's nothing to do.
1616 if (access(dex_path.c_str(), R_OK) == 0) {
1617 return kSecondaryDexAccessReadOk;
1618 } else {
1619 if (errno == ENOENT) {
1620 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1621 return kSecondaryDexAccessDoesNotExist;
1622 } else {
1623 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1624 return errno == EACCES
1625 ? kSecondaryDexAccessPermissionError
1626 : kSecondaryDexAccessIOError;
1627 }
1628 }
1629}
1630
1631static bool is_file_public(const std::string& filename) {
1632 struct stat file_stat;
1633 if (stat(filename.c_str(), &file_stat) == 0) {
1634 return (file_stat.st_mode & S_IROTH) != 0;
1635 }
1636 return false;
1637}
1638
1639// Create the oat file structure for the secondary dex 'dex_path' and assign
1640// the individual path component to the 'out_' parameters.
1641static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001642 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001643 size_t dirIndex = dex_path.rfind('/');
1644 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001645 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001646 return false;
1647 }
1648 // TODO(calin): we have similar computations in at lest 3 other places
1649 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1650 // using string append.
1651 std::string apk_dir = dex_path.substr(0, dirIndex);
1652 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1653 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1654
1655 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1656 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001657 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001658 return false;
1659 }
1660 return true;
1661}
1662
1663// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1664// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001665static bool validate_dexopt_storage_flags(int dexopt_flags,
1666 int* out_storage_flag,
1667 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001668 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1669 *out_storage_flag = FLAG_STORAGE_CE;
1670 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001671 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001672 return false;
1673 }
1674 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1675 *out_storage_flag = FLAG_STORAGE_DE;
1676 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001677 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001678 return false;
1679 }
1680 return true;
1681}
1682
Calin Juravlec9eab382017-01-25 01:17:17 -08001683// 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 -08001684// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1685// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001686// When returning true, the output parameters will be:
1687// - is_public_out: whether or not the oat file should not be made public
1688// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1689// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001690static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001691 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001692 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001693 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1694 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001695 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001696 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001697 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1698 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001699 return false;
1700 }
Calin Juravle7d765462017-09-04 15:57:10 -07001701 // Compute the oat dir as it's not easy to extract it from the child computation.
1702 char oat_path[PKG_PATH_MAX];
1703 char oat_dir[PKG_PATH_MAX];
1704 char oat_isa_dir[PKG_PATH_MAX];
1705 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001706 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1707 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001708 return false;
1709 }
Calin Juravle7d765462017-09-04 15:57:10 -07001710 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001711
Calin Juravle80a21252017-01-17 14:43:25 -08001712 pid_t pid = fork();
1713 if (pid == 0) {
1714 // child -- drop privileges before continuing.
1715 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001716
1717 // Validate the path structure.
1718 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1719 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001720 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001721 }
1722
1723 // Open the dex file.
1724 unique_fd zip_fd;
1725 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1726 if (zip_fd.get() < 0) {
1727 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001728 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001729 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001730 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001731 }
1732 }
1733
1734 // Prepare the oat directories.
1735 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001736 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001737 }
1738
1739 // Open the vdex/oat files if any.
1740 unique_fd oat_file_fd;
1741 unique_fd vdex_file_fd;
1742 if (!maybe_open_oat_and_vdex_file(dex_path,
1743 *oat_dir_out,
1744 instruction_set,
1745 true /* is_secondary_dex */,
1746 &oat_file_fd,
1747 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001748 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001749 }
1750
1751 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001752 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1753 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001754
1755 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001756 // Note that we do not do it before the fork since opening the files is required to happen
1757 // after forking.
1758 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1759 vdex_file_fd.get(),
1760 oat_file_fd.get(),
1761 zip_fd.get(),
1762 instruction_set,
1763 compiler_filter, profile_was_updated,
1764 downgrade,
1765 class_loader_context);
1766 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001767 }
1768
1769 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001770 int result = wait_child(pid);
1771 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001772 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1773 dex_path.c_str(),
1774 result);
1775 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001776 return false;
1777 }
1778 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001779 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001780 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1781 result,
1782 dexopt_needed_out,
1783 error_msg);
1784 if (!success) {
1785 LOG(ERROR) << *error_msg;
1786 }
Calin Juravle7d765462017-09-04 15:57:10 -07001787
1788 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1789
Calin Juravle80a21252017-01-17 14:43:25 -08001790 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001791 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1792 // makes the code simpler; force compilation is only needed during tests).
1793 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001794 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001795 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001796 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1797 }
1798
Calin Juravle7d765462017-09-04 15:57:10 -07001799 // Check if we should make the oat file public.
1800 // Note that if the dex file is not public the compiled code cannot be made public.
1801 // It is ok to check this flag outside in the parent process.
1802 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1803
Calin Juravle80a21252017-01-17 14:43:25 -08001804 return success;
1805}
1806
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001807static std::string format_dexopt_error(int status, const char* dex_path) {
1808 if (WIFEXITED(status)) {
1809 int int_code = WEXITSTATUS(status);
1810 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1811 if (code_name != nullptr) {
1812 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1813 }
1814 }
1815 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001816}
1817
Calin Juravlec9eab382017-01-25 01:17:17 -08001818int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001819 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001820 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001821 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001822 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001823 CHECK(pkgname != nullptr);
1824 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001825 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001826 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1827 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001828
Calin Juravled23dee72017-07-06 16:29:11 -07001829 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001830 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001831 return -1;
1832 }
1833
1834 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001835 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1836 class_loader_context);
1837 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001838 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001839 }
1840
Calin Juravleebc8a792017-04-04 20:21:05 -07001841 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001842 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1843 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1844 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001845 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001846 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001847 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001848 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001849 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001850
1851 // Check if we're dealing with a secondary dex file and if we need to compile it.
1852 std::string oat_dir_str;
1853 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001854 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001855 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001856 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001857 oat_dir = oat_dir_str.c_str();
1858 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1859 return 0; // Nothing to do, report success.
1860 }
1861 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001862 if (error_msg->empty()) { // TODO: Make this a CHECK.
1863 *error_msg = "Failed processing secondary.";
1864 }
Calin Juravle80a21252017-01-17 14:43:25 -08001865 return -1; // We had an error, logged in the process method.
1866 }
1867 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001868 // Currently these flags are only use for secondary dex files.
1869 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001870 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1871 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1872 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001873
1874 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001875 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001876 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001877 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1878 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001879 return -1;
1880 }
1881
1882 // Create the output OAT file.
1883 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001884 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001885 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001886 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001887 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001888 return -1;
1889 }
1890
1891 // Open vdex files.
1892 Dex2oatFileWrapper in_vdex_fd;
1893 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001894 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1895 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001896 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001897 return -1;
1898 }
1899
Calin Juravlecb556e32017-04-04 20:22:50 -07001900 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1901 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1902 // fully inherit their parent context).
1903 // Note that for primary apk the oat files are created before, in a separate installd
1904 // call which also does the restorecon. TODO(calin): unify the paths.
1905 if (is_secondary_dex) {
1906 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1907 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001908 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1909 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001910 return -1;
1911 }
1912 }
1913
Jeff Sharkey90aff262016-12-12 14:28:24 -07001914 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001915 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001916
Calin Juravle7a570e82017-01-14 16:23:30 -08001917 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001918 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1919 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001920
Calin Juravle7a570e82017-01-14 16:23:30 -08001921 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001922 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001923 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001924
Calin Juravle62c5a372018-02-01 17:03:23 +00001925 unique_fd dex_metadata_fd;
1926 if (dex_metadata_path != nullptr) {
1927 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1928 if (dex_metadata_fd.get() < 0) {
1929 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1930 }
1931 }
1932
Andreas Gampe023b2242018-02-28 16:03:25 -08001933 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001934
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001935 RunDex2Oat runner(input_fd.get(),
1936 out_oat_fd.get(),
1937 in_vdex_fd.get(),
1938 out_vdex_fd.get(),
1939 image_fd.get(),
1940 dex_path,
1941 out_oat_path,
1942 swap_fd.get(),
1943 instruction_set,
1944 compiler_filter,
1945 debuggable,
1946 boot_complete,
1947 background_job_compile,
1948 reference_profile_fd.get(),
1949 class_loader_context,
1950 target_sdk_version,
1951 enable_hidden_api_checks,
1952 generate_compact_dex,
1953 dex_metadata_fd.get(),
1954 compilation_reason);
1955
Jeff Sharkey90aff262016-12-12 14:28:24 -07001956 pid_t pid = fork();
1957 if (pid == 0) {
1958 /* child -- drop privileges before continuing */
1959 drop_capabilities(uid);
1960
Vladimir Marko1fea89a2019-02-08 15:11:59 +00001961 // Clear BOOTCLASSPATH.
1962 // Let dex2oat use the BCP from boot image, excluding updatable BCP
1963 // modules for AOT to avoid app recompilation after their upgrades.
1964 unsetenv("BOOTCLASSPATH");
1965
Richard Uhler76cc0272016-12-08 10:46:35 +00001966 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001967 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001968 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001969 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001970 }
1971
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001972 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001973 } else {
1974 int res = wait_child(pid);
1975 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001976 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001977 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001978 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1979 << std::hex << std::setw(4) << res << ", process failed";
1980 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001981 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982 }
1983 }
1984
Calin Juravlec9eab382017-01-25 01:17:17 -08001985 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001986
1987 // We've been successful, don't delete output.
1988 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001989 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001990 image_fd.SetCleanup(false);
1991 reference_profile_fd.SetCleanup(false);
1992
1993 return 0;
1994}
1995
Calin Juravlec9eab382017-01-25 01:17:17 -08001996// Try to remove the given directory. Log an error if the directory exists
1997// and is empty but could not be removed.
1998static bool rmdir_if_empty(const char* dir) {
1999 if (rmdir(dir) == 0) {
2000 return true;
2001 }
2002 if (errno == ENOENT || errno == ENOTEMPTY) {
2003 return true;
2004 }
2005 PLOG(ERROR) << "Failed to remove dir: " << dir;
2006 return false;
2007}
2008
2009// Try to unlink the given file. Log an error if the file exists and could not
2010// be unlinked.
2011static bool unlink_if_exists(const std::string& file) {
2012 if (unlink(file.c_str()) == 0) {
2013 return true;
2014 }
2015 if (errno == ENOENT) {
2016 return true;
2017
2018 }
2019 PLOG(ERROR) << "Could not unlink: " << file;
2020 return false;
2021}
2022
Calin Juravle7d765462017-09-04 15:57:10 -07002023enum ReconcileSecondaryDexResult {
2024 kReconcileSecondaryDexExists = 0,
2025 kReconcileSecondaryDexCleanedUp = 1,
2026 kReconcileSecondaryDexValidationError = 2,
2027 kReconcileSecondaryDexCleanUpError = 3,
2028 kReconcileSecondaryDexAccessIOError = 4,
2029};
Calin Juravlec9eab382017-01-25 01:17:17 -08002030
2031// Reconcile the secondary dex 'dex_path' and its generated oat files.
2032// Return true if all the parameters are valid and the secondary dex file was
2033// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2034// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2035// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2036// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2037// Return false if there were errors during processing. In this case
2038// out_secondary_dex_exists will be set to false.
2039bool reconcile_secondary_dex_file(const std::string& dex_path,
2040 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2041 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2042 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002043 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002044 if (isas.size() == 0) {
2045 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2046 return false;
2047 }
2048
Calin Juravle7d765462017-09-04 15:57:10 -07002049 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2050 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2051 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002052 return false;
2053 }
2054
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002055 // As a security measure we want to unlink art artifacts with the reduced capabilities
2056 // of the package user id. So we fork and drop capabilities in the child.
2057 pid_t pid = fork();
2058 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002059 /* child -- drop privileges before continuing */
2060 drop_capabilities(uid);
2061
2062 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2063 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2064 uid, storage_flag)) {
2065 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2066 _exit(kReconcileSecondaryDexValidationError);
2067 }
2068
2069 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2070 switch (access_check) {
2071 case kSecondaryDexAccessDoesNotExist:
2072 // File does not exist. Proceed with cleaning.
2073 break;
2074 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2075 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2076 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2077 default:
2078 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2079 _exit(kReconcileSecondaryDexValidationError);
2080 }
2081
2082 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002083 char oat_path[PKG_PATH_MAX];
2084 char oat_dir[PKG_PATH_MAX];
2085 char oat_isa_dir[PKG_PATH_MAX];
2086 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002087 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002088 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002089 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002090 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2091 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002092 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002093 }
Calin Juravle51314092017-05-18 15:33:05 -07002094
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002095 // Delete oat/vdex/art files.
2096 result = unlink_if_exists(oat_path) && result;
2097 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2098 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002099
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002100 // Delete profiles.
2101 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002102 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002103 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002104 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002105 result = unlink_if_exists(current_profile) && result;
2106 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002107
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002108 // We upgraded once the location of current profile for secondary dex files.
2109 // Check for any previous left-overs and remove them as well.
2110 std::string old_current_profile = dex_path + ".prof";
2111 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002112
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002113 // Try removing the directories as well, they might be empty.
2114 result = rmdir_if_empty(oat_isa_dir) && result;
2115 result = rmdir_if_empty(oat_dir) && result;
2116 }
Calin Juravle7d765462017-09-04 15:57:10 -07002117 if (!result) {
2118 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2119 }
2120 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002121 }
2122
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002123 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002124 if (!WIFEXITED(return_code)) {
2125 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2126 } else {
2127 return_code = WEXITSTATUS(return_code);
2128 }
2129
2130 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2131
2132 switch (return_code) {
2133 case kReconcileSecondaryDexCleanedUp:
2134 case kReconcileSecondaryDexValidationError:
2135 // If we couldn't validate assume the dex file does not exist.
2136 // This will purge the entry from the PM records.
2137 *out_secondary_dex_exists = false;
2138 return true;
2139 case kReconcileSecondaryDexExists:
2140 *out_secondary_dex_exists = true;
2141 return true;
2142 case kReconcileSecondaryDexAccessIOError:
2143 // We had an access IO error.
2144 // Return false so that we can try again.
2145 // The value of out_secondary_dex_exists does not matter in this case and by convention
2146 // is set to false.
2147 *out_secondary_dex_exists = false;
2148 return false;
2149 default:
2150 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2151 *out_secondary_dex_exists = false;
2152 return false;
2153 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002154}
2155
Alan Stokesa25d90c2017-10-16 10:56:00 +01002156// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2157// Returns true if all parameters are valid and the hash successfully computed and stored in
2158// out_secondary_dex_hash.
2159// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2160// the app.
2161// For any other errors (e.g. if any of the parameters are invalid) returns false.
2162bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2163 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2164 std::vector<uint8_t>* out_secondary_dex_hash) {
2165 out_secondary_dex_hash->clear();
2166
2167 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2168
2169 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2170 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2171 << storage_flag;
2172 return false;
2173 }
2174
2175 // Pipe to get the hash result back from our child process.
2176 unique_fd pipe_read, pipe_write;
2177 if (!Pipe(&pipe_read, &pipe_write)) {
2178 PLOG(ERROR) << "Failed to create pipe";
2179 return false;
2180 }
2181
2182 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2183 // access data the app itself can access.
2184 pid_t pid = fork();
2185 if (pid == 0) {
2186 // child -- drop privileges before continuing
2187 drop_capabilities(uid);
2188 pipe_read.reset();
2189
2190 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2191 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002192 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002193 }
2194
2195 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2196 if (fd == -1) {
2197 if (errno == EACCES || errno == ENOENT) {
2198 // Not treated as an error.
2199 _exit(0);
2200 }
2201 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002202 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002203 }
2204
2205 SHA256_CTX ctx;
2206 SHA256_Init(&ctx);
2207
2208 std::vector<uint8_t> buffer(65536);
2209 while (true) {
2210 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2211 if (bytes_read == 0) {
2212 break;
2213 } else if (bytes_read == -1) {
2214 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002215 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002216 }
2217
2218 SHA256_Update(&ctx, buffer.data(), bytes_read);
2219 }
2220
2221 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2222 SHA256_Final(hash.data(), &ctx);
2223 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002224 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002225 }
2226
2227 _exit(0);
2228 }
2229
2230 // parent
2231 pipe_write.reset();
2232
2233 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2234 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2235 out_secondary_dex_hash->clear();
2236 }
2237 return wait_child(pid) == 0;
2238}
2239
Jeff Sharkey90aff262016-12-12 14:28:24 -07002240// Helper for move_ab, so that we can have common failure-case cleanup.
2241static bool unlink_and_rename(const char* from, const char* to) {
2242 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2243 // return a failure.
2244 struct stat s;
2245 if (stat(to, &s) == 0) {
2246 if (!S_ISREG(s.st_mode)) {
2247 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2248 return false;
2249 }
2250 if (unlink(to) != 0) {
2251 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2252 return false;
2253 }
2254 } else {
2255 // This may be a permission problem. We could investigate the error code, but we'll just
2256 // let the rename failure do the work for us.
2257 }
2258
2259 // Try to rename "to" to "from."
2260 if (rename(from, to) != 0) {
2261 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2262 return false;
2263 }
2264 return true;
2265}
2266
2267// Move/rename a B artifact (from) to an A artifact (to).
2268static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2269 // Check whether B exists.
2270 {
2271 struct stat s;
2272 if (stat(b_path.c_str(), &s) != 0) {
2273 // Silently ignore for now. The service calling this isn't smart enough to understand
2274 // lack of artifacts at the moment.
2275 return false;
2276 }
2277 if (!S_ISREG(s.st_mode)) {
2278 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2279 // Try to unlink, but swallow errors.
2280 unlink(b_path.c_str());
2281 return false;
2282 }
2283 }
2284
2285 // Rename B to A.
2286 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2287 // Delete the b_path so we don't try again (or fail earlier).
2288 if (unlink(b_path.c_str()) != 0) {
2289 PLOG(ERROR) << "Could not unlink " << b_path;
2290 }
2291
2292 return false;
2293 }
2294
2295 return true;
2296}
2297
2298bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2299 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002300 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2301 if (slot_suffix.empty()) {
2302 return false;
2303 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002304
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002305 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2306 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2307 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002308 }
2309
2310 // Validate other inputs.
2311 if (validate_apk_path(apk_path) != 0) {
2312 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2313 return false;
2314 }
2315 if (validate_apk_path(oat_dir) != 0) {
2316 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2317 return false;
2318 }
2319
2320 char a_path[PKG_PATH_MAX];
2321 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2322 return false;
2323 }
2324 const std::string a_vdex_path = create_vdex_filename(a_path);
2325 const std::string a_image_path = create_image_filename(a_path);
2326
2327 // B path = A path + slot suffix.
2328 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2329 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2330 const std::string b_image_path = StringPrintf("%s.%s",
2331 a_image_path.c_str(),
2332 slot_suffix.c_str());
2333
2334 bool success = true;
2335 if (move_ab_path(b_path, a_path)) {
2336 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2337 // Note: we can live without an app image. As such, ignore failure to move the image file.
2338 // If we decide to require the app image, or the app image being moved correctly,
2339 // then change accordingly.
2340 constexpr bool kIgnoreAppImageFailure = true;
2341
2342 if (!a_image_path.empty()) {
2343 if (!move_ab_path(b_image_path, a_image_path)) {
2344 unlink(a_image_path.c_str());
2345 if (!kIgnoreAppImageFailure) {
2346 success = false;
2347 }
2348 }
2349 }
2350 } else {
2351 // Cleanup: delete B image, ignore errors.
2352 unlink(b_image_path.c_str());
2353 success = false;
2354 }
2355 } else {
2356 // Cleanup: delete B image, ignore errors.
2357 unlink(b_vdex_path.c_str());
2358 unlink(b_image_path.c_str());
2359 success = false;
2360 }
2361 return success;
2362}
2363
2364bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2365 // Delete the oat/odex file.
2366 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002367 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002368 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002369 return false;
2370 }
2371
2372 // In case of a permission failure report the issue. Otherwise just print a warning.
2373 auto unlink_and_check = [](const char* path) -> bool {
2374 int result = unlink(path);
2375 if (result != 0) {
2376 if (errno == EACCES || errno == EPERM) {
2377 PLOG(ERROR) << "Could not unlink " << path;
2378 return false;
2379 }
2380 PLOG(WARNING) << "Could not unlink " << path;
2381 }
2382 return true;
2383 };
2384
2385 // Delete the oat/odex file.
2386 bool return_value_oat = unlink_and_check(out_path);
2387
2388 // Derive and delete the app image.
2389 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2390
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002391 // Derive and delete the vdex file.
2392 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2393
Jeff Sharkey90aff262016-12-12 14:28:24 -07002394 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002395 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002396}
2397
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002398static bool is_absolute_path(const std::string& path) {
2399 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2400 LOG(ERROR) << "Invalid absolute path " << path;
2401 return false;
2402 } else {
2403 return true;
2404 }
2405}
2406
2407static bool is_valid_instruction_set(const std::string& instruction_set) {
2408 // TODO: add explicit whitelisting of instruction sets
2409 if (instruction_set.find('/') != std::string::npos) {
2410 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2411 return false;
2412 } else {
2413 return true;
2414 }
2415}
2416
2417bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2418 const char *apk_path, const char *instruction_set) {
2419 std::string oat_dir_ = oat_dir;
2420 std::string apk_path_ = apk_path;
2421 std::string instruction_set_ = instruction_set;
2422
2423 if (!is_absolute_path(oat_dir_)) return false;
2424 if (!is_absolute_path(apk_path_)) return false;
2425 if (!is_valid_instruction_set(instruction_set_)) return false;
2426
2427 std::string::size_type end = apk_path_.rfind('.');
2428 std::string::size_type start = apk_path_.rfind('/', end);
2429 if (end == std::string::npos || start == std::string::npos) {
2430 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2431 return false;
2432 }
2433
2434 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2435 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2436 const char* res = res_.c_str();
2437 if (strlen(res) >= PKG_PATH_MAX) {
2438 LOG(ERROR) << "Result too large";
2439 return false;
2440 } else {
2441 strlcpy(path, res, PKG_PATH_MAX);
2442 return true;
2443 }
2444}
2445
2446bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2447 const char *instruction_set) {
2448 std::string apk_path_ = apk_path;
2449 std::string instruction_set_ = instruction_set;
2450
2451 if (!is_absolute_path(apk_path_)) return false;
2452 if (!is_valid_instruction_set(instruction_set_)) return false;
2453
2454 std::string::size_type end = apk_path_.rfind('.');
2455 std::string::size_type start = apk_path_.rfind('/', end);
2456 if (end == std::string::npos || start == std::string::npos) {
2457 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2458 return false;
2459 }
2460
2461 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2462 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2463}
2464
2465bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2466 const char *instruction_set) {
2467 std::string src_ = src;
2468 std::string instruction_set_ = instruction_set;
2469
2470 if (!is_absolute_path(src_)) return false;
2471 if (!is_valid_instruction_set(instruction_set_)) return false;
2472
2473 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2474 if (*it == '/') {
2475 *it = '@';
2476 }
2477 }
2478
2479 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2480 + DALVIK_CACHE_POSTFIX;
2481 const char* res = res_.c_str();
2482 if (strlen(res) >= PKG_PATH_MAX) {
2483 LOG(ERROR) << "Result too large";
2484 return false;
2485 } else {
2486 strlcpy(path, res, PKG_PATH_MAX);
2487 return true;
2488 }
2489}
2490
Calin Juravle59f7ab82018-04-27 17:50:23 -07002491bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2492 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002493 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2494 for (const std::string& elem : classpaths_elems) {
2495 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2496 if (fd < 0) {
2497 PLOG(ERROR) << "Could not open classpath elem " << elem;
2498 return false;
2499 } else {
2500 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002501 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002502 }
2503 }
2504 return true;
2505}
2506
2507static bool create_app_profile_snapshot(int32_t app_id,
2508 const std::string& package_name,
2509 const std::string& profile_name,
2510 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002511 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2512
Calin Juravle824a64d2018-01-18 20:23:17 -08002513 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002514 if (snapshot_fd < 0) {
2515 return false;
2516 }
2517
2518 std::vector<unique_fd> profiles_fd;
2519 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002520 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2521 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002522 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2523 return false;
2524 }
2525
2526 profiles_fd.push_back(std::move(reference_profile_fd));
2527
Calin Juravle0d0a4922018-01-23 19:54:11 -08002528 // Open the class paths elements. These will be used to filter out profile data that does
2529 // not belong to the classpath during merge.
2530 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002531 std::vector<std::string> dex_locations;
2532 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002533 return false;
2534 }
2535
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002536 RunProfman args;
2537 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002538 pid_t pid = fork();
2539 if (pid == 0) {
2540 /* child -- drop privileges before continuing */
2541 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002542 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002543 }
2544
2545 /* parent */
2546 int return_code = wait_child(pid);
2547 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002548 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002549 return false;
2550 }
2551
2552 return true;
2553}
2554
Calin Juravle0d0a4922018-01-23 19:54:11 -08002555static bool create_boot_image_profile_snapshot(const std::string& package_name,
2556 const std::string& profile_name,
2557 const std::string& classpath) {
2558 // The reference profile directory for the android package might not be prepared. Do it now.
2559 const std::string ref_profile_dir =
2560 create_primary_reference_profile_package_dir_path(package_name);
2561 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2562 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2563 return false;
2564 }
2565
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002566 // Return false for empty class path since it may otherwise return true below if profiles is
2567 // empty.
2568 if (classpath.empty()) {
2569 PLOG(ERROR) << "Class path is empty";
2570 return false;
2571 }
2572
Calin Juravle0d0a4922018-01-23 19:54:11 -08002573 // Open and create the snapshot profile.
2574 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2575
2576 // Collect all non empty profiles.
2577 // The collection will traverse all applications profiles and find the non empty files.
2578 // This has the potential of inspecting a large number of files and directories (depending
2579 // on the number of applications and users). So there is a slight increase in the chance
2580 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2581 // fail the snapshot and aggregate whatever profile we could open.
2582 //
2583 // The profile snapshot is a best effort based on available data it's ok if some data
2584 // from some apps is missing. It will be counter productive for the snapshot to fail
2585 // because we could not open or read some of the files.
2586 std::vector<std::string> profiles;
2587 if (!collect_profiles(&profiles)) {
2588 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2589 }
2590
2591 // If we have no profiles return early.
2592 if (profiles.empty()) {
2593 return true;
2594 }
2595
2596 // Open the classpath elements. These will be used to filter out profile data that does
2597 // not belong to the classpath during merge.
2598 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002599 std::vector<std::string> dex_locations;
2600 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002601 return false;
2602 }
2603
2604 // If we could not open any files from the classpath return an error.
2605 if (apk_fds.empty()) {
2606 LOG(ERROR) << "Could not open any of the classpath elements.";
2607 return false;
2608 }
2609
2610 // Aggregate the profiles in batches of kAggregationBatchSize.
2611 // We do this to avoid opening a huge a amount of files.
2612 static constexpr size_t kAggregationBatchSize = 10;
2613
2614 std::vector<unique_fd> profiles_fd;
2615 for (size_t i = 0; i < profiles.size(); ) {
2616 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2617 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2618 if (fd.get() >= 0) {
2619 profiles_fd.push_back(std::move(fd));
2620 }
2621 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002622 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002623 args.SetupMerge(profiles_fd,
2624 snapshot_fd,
2625 apk_fds,
2626 dex_locations,
2627 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002628 pid_t pid = fork();
2629 if (pid == 0) {
2630 /* child -- drop privileges before continuing */
2631 drop_capabilities(AID_SYSTEM);
2632
Calin Juravle59f7ab82018-04-27 17:50:23 -07002633 // The introduction of new access flags into boot jars causes them to
2634 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002635 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002636 }
2637
2638 /* parent */
2639 int return_code = wait_child(pid);
2640 if (!WIFEXITED(return_code)) {
2641 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2642 return false;
2643 }
2644 return true;
2645 }
2646 return true;
2647}
2648
2649bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2650 const std::string& profile_name, const std::string& classpath) {
2651 if (app_id == -1) {
2652 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2653 } else {
2654 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2655 }
2656}
2657
Calin Juravlec3b049e2018-01-18 22:32:58 -08002658bool prepare_app_profile(const std::string& package_name,
2659 userid_t user_id,
2660 appid_t app_id,
2661 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002662 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002663 const std::unique_ptr<std::string>& dex_metadata) {
2664 // Prepare the current profile.
2665 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2666 /*is_secondary_dex*/ false);
2667 uid_t uid = multiuser_get_uid(user_id, app_id);
2668 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2669 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2670 return false;
2671 }
2672
2673 // Check if we need to install the profile from the dex metadata.
2674 if (dex_metadata == nullptr) {
2675 return true;
2676 }
2677
2678 // We have a dex metdata. Merge the profile into the reference profile.
2679 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2680 /*read_write*/ true, /*is_secondary_dex*/ false);
2681 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2682 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002683 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2684 if (apk_fd < 0) {
2685 PLOG(ERROR) << "Could not open code path " << code_path;
2686 return false;
2687 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002688
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002689 RunProfman args;
2690 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2691 std::move(ref_profile_fd),
2692 std::move(apk_fd),
2693 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002694 pid_t pid = fork();
2695 if (pid == 0) {
2696 /* child -- drop privileges before continuing */
2697 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2698 drop_capabilities(app_shared_gid);
2699
Calin Juravlef63d4792018-01-30 17:43:34 +00002700 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002701 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002702 }
2703
2704 /* parent */
2705 int return_code = wait_child(pid);
2706 if (!WIFEXITED(return_code)) {
2707 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2708 return false;
2709 }
2710 return true;
2711}
2712
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002713} // namespace installd
2714} // namespace android