blob: 07ea77b20523bf1bc4f00402cc919ebdb9b56ee0 [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 Baghdasaryancd829052018-11-02 19:15:37 -070046#include <processgroup/sched_policy.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070047#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
50#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080051#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060052#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070053#include "installd_deps.h"
54#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070055#include "utils.h"
56
Jeff Sharkey90aff262016-12-12 14:28:24 -070057using android::base::EndsWith;
Mathieu Chartier9b2da082018-10-26 13:23:11 -070058using android::base::GetBoolProperty;
59using android::base::GetProperty;
Alan Stokesa25d90c2017-10-16 10:56:00 +010060using android::base::ReadFully;
61using android::base::StringPrintf;
62using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080063using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070064
65namespace android {
66namespace installd {
67
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070068// Should minidebug info be included in compiled artifacts? Even if this value is
69// "true," usage might still be conditional to other constraints, e.g., system
70// property overrides.
71static constexpr bool kEnableMinidebugInfo = true;
72
73static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
74static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
75static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080076static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070077
Andreas Gampefa2dadd2018-02-28 19:52:47 -080078
Calin Juravle114f0812017-03-08 19:05:07 -080079// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
80struct FreeDelete {
81 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
82 void operator()(const void* ptr) const {
83 free(const_cast<void*>(ptr));
84 }
85};
86
87// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
88template <typename T>
89using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
90
Calin Juravle1a0af3b2017-03-09 14:33:33 -080091static unique_fd invalid_unique_fd() {
92 return unique_fd(-1);
93}
94
Andreas Gampe6a9cf722017-07-24 16:49:10 -070095static bool is_debug_runtime() {
96 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
97}
98
David Sehra3b5ab62017-10-25 14:27:29 -070099static bool is_debuggable_build() {
100 return android::base::GetBoolProperty("ro.debuggable", false);
101}
102
Jeff Sharkey90aff262016-12-12 14:28:24 -0700103static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800104 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700105 if (ufd.get() < 0) {
106 if (errno != ENOENT) {
107 PLOG(WARNING) << "Could not open profile " << profile;
108 return false;
109 } else {
110 // Nothing to clear. That's ok.
111 return true;
112 }
113 }
114
115 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
116 if (errno != EWOULDBLOCK) {
117 PLOG(WARNING) << "Error locking profile " << profile;
118 }
119 // This implies that the app owning this profile is running
120 // (and has acquired the lock).
121 //
122 // If we can't acquire the lock bail out since clearing is useless anyway
123 // (the app will write again to the profile).
124 //
125 // Note:
126 // This does not impact the this is not an issue for the profiling correctness.
127 // In case this is needed because of an app upgrade, profiles will still be
128 // eventually cleared by the app itself due to checksum mismatch.
129 // If this is needed because profman advised, then keeping the data around
130 // until the next run is again not an issue.
131 //
132 // If the app attempts to acquire a lock while we've held one here,
133 // it will simply skip the current write cycle.
134 return false;
135 }
136
137 bool truncated = ftruncate(ufd.get(), 0) == 0;
138 if (!truncated) {
139 PLOG(WARNING) << "Could not truncate " << profile;
140 }
141 if (flock(ufd.get(), LOCK_UN) != 0) {
142 PLOG(WARNING) << "Error unlocking profile " << profile;
143 }
144 return truncated;
145}
146
Calin Juravle114f0812017-03-08 19:05:07 -0800147// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800148// The location is the profile name for primary apks or the dex path for secondary dex files.
149static bool clear_reference_profile(const std::string& package_name, const std::string& location,
150 bool is_secondary_dex) {
151 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700152}
153
Calin Juravle114f0812017-03-08 19:05:07 -0800154// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800155// The location is the profile name for primary apks or the dex path for secondary dex files.
156static bool clear_current_profile(const std::string& package_name, const std::string& location,
157 userid_t user, bool is_secondary_dex) {
158 return clear_profile(create_current_profile_path(user, package_name, location,
159 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700160}
161
Calin Juravle114f0812017-03-08 19:05:07 -0800162// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800163// The location is the profile name for primary apks or the dex path for secondary dex files.
164bool clear_primary_reference_profile(const std::string& package_name,
165 const std::string& location) {
166 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800167}
168
169// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800170// The location is the profile name for primary apks or the dex path for secondary dex files.
171bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700172 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800173 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
175 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800176 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700177 }
178 return success;
179}
180
Calin Juravle114f0812017-03-08 19:05:07 -0800181// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800182bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
183 userid_t user) {
184 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800185}
186
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700187static std::vector<std::string> SplitBySpaces(const std::string& str) {
188 if (str.empty()) {
189 return {};
190 }
191 return android::base::Split(str, " ");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700192}
193
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700194static const char* get_location_from_path(const char* path) {
195 static constexpr char kLocationSeparator = '/';
196 const char *location = strrchr(path, kLocationSeparator);
Yi Kong954cf642018-07-17 16:16:24 -0700197 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700198 return path;
199 } else {
200 // Skip the separator character.
201 return location + 1;
202 }
203}
204
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800205// ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
206// need to be performed between the fork and exec.
207class ExecVHelper {
208 public:
209 // Store a placeholder for the binary name.
210 ExecVHelper() : args_(1u, std::string()) {}
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800211
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800212 void PrepareArgs(const std::string& bin) {
213 CHECK(!args_.empty());
214 CHECK(args_[0].empty());
215 args_[0] = bin;
216 // Write char* into array.
217 for (const std::string& arg : args_) {
218 argv_.push_back(arg.c_str());
219 }
220 argv_.push_back(nullptr); // Add null terminator.
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800221 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800222
223 [[ noreturn ]]
224 void Exec(int exit_code) {
225 execv(argv_[0], (char * const *)&argv_[0]);
226 PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
227 exit(exit_code);
228 }
229
230 // Add an arg if it's not empty.
231 void AddArg(const std::string& arg) {
232 if (!arg.empty()) {
233 args_.push_back(arg);
234 }
235 }
236
237 // Add a runtime arg if it's not empty.
238 void AddRuntimeArg(const std::string& arg) {
239 if (!arg.empty()) {
240 args_.push_back("--runtime-arg");
241 args_.push_back(arg);
242 }
243 }
244
245 protected:
246 // Holder arrays for backing arg storage.
247 std::vector<std::string> args_;
248
249 // Argument poiners.
250 std::vector<const char*> argv_;
251};
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700252
253static std::string MapPropertyToArg(const std::string& property,
254 const std::string& format,
255 const std::string& default_value = "") {
256 std::string prop = GetProperty(property, default_value);
257 if (!prop.empty()) {
258 return StringPrintf(format.c_str(), prop.c_str());
259 }
260 return "";
261}
262
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800263class RunDex2Oat : public ExecVHelper {
264 public:
265 RunDex2Oat(int zip_fd,
266 int oat_fd,
267 int input_vdex_fd,
268 int output_vdex_fd,
269 int image_fd,
270 const char* input_file_name,
271 const char* output_file_name,
272 int swap_fd,
273 const char* instruction_set,
274 const char* compiler_filter,
275 bool debuggable,
276 bool post_bootcomplete,
277 bool background_job_compile,
278 int profile_fd,
279 const char* class_loader_context,
280 int target_sdk_version,
281 bool enable_hidden_api_checks,
282 bool generate_compact_dex,
283 int dex_metadata_fd,
284 const char* compilation_reason) {
285 // Get the relative path to the input file.
286 const char* relative_input_file_name = get_location_from_path(input_file_name);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700287
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800288 std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
289 std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700290
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800291 const char* threads_property = post_bootcomplete
292 ? "dalvik.vm.dex2oat-threads"
293 : "dalvik.vm.boot-dex2oat-threads";
294 std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700295
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800296 const std::string dex2oat_isa_features_key =
297 StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
298 std::string instruction_set_features_arg =
299 MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700300
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800301 const std::string dex2oat_isa_variant_key =
302 StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
303 std::string instruction_set_variant_arg =
304 MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700305
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800306 const char* dex2oat_norelocation = "-Xnorelocate";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700307
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800308 const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
309 std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
310 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700311
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800312 // If we are booting without the real /data, don't spend time compiling.
313 std::string vold_decrypt = GetProperty("vold.decrypt", "");
314 bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
315 vold_decrypt == "1";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700316
Mathieu Chartier5880c032018-11-28 19:15:41 -0800317 const std::string resolve_startup_string_arg =
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800318 MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
319 "--resolve-startup-const-strings=%s");
Mathieu Chartier5880c032018-11-28 19:15:41 -0800320
321 const std::string image_block_size_arg =
322 MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
323 "--max-image-block-size=%s");
324
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800325 const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700326
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800327 std::string image_format_arg;
328 if (image_fd >= 0) {
329 image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000330 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000331
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800332 std::string dex2oat_large_app_threshold_arg =
333 MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
Mathieu Chartier31636522018-11-09 23:53:07 +0000334
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800335 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
Andreas Gampe3a77feb2018-12-10 23:13:49 +0000336 const char* dex2oat_bin = "/system/bin/dex2oat";
337 constexpr const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800338 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
339 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
340 if (is_debug_runtime() ||
341 (background_job_compile && is_debuggable_build() && !is_release)) {
342 if (access(kDex2oatDebugPath, X_OK) == 0) {
343 dex2oat_bin = kDex2oatDebugPath;
344 }
345 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000346
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800347 bool generate_minidebug_info = kEnableMinidebugInfo &&
348 GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
Mathieu Chartier31636522018-11-09 23:53:07 +0000349
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800350 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
351 // use arraysize instead.
352 std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
353 std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
354 std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
355 std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
356 std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
357 std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
358 std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
359 std::string dex2oat_compiler_filter_arg;
360 std::string dex2oat_swap_fd;
361 std::string dex2oat_image_fd;
362 std::string target_sdk_version_arg;
363 if (target_sdk_version != 0) {
364 StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
365 }
366 std::string class_loader_context_arg;
367 if (class_loader_context != nullptr) {
368 class_loader_context_arg = StringPrintf("--class-loader-context=%s",
369 class_loader_context);
370 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000371
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800372 if (swap_fd >= 0) {
373 dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
374 }
375 if (image_fd >= 0) {
376 dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
377 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000378
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800379 // Compute compiler filter.
380 bool have_dex2oat_relocation_skip_flag = false;
381 if (skip_compilation) {
382 dex2oat_compiler_filter_arg = "--compiler-filter=extract";
383 have_dex2oat_relocation_skip_flag = true;
384 } else if (compiler_filter != nullptr) {
385 dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
386 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000387
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800388 if (dex2oat_compiler_filter_arg.empty()) {
389 dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
390 "--compiler-filter=%s");
391 }
392
393 // Check whether all apps should be compiled debuggable.
394 if (!debuggable) {
395 debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
396 }
397 std::string profile_arg;
398 if (profile_fd != -1) {
399 profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
400 }
401
402 // Get the directory of the apk to pass as a base classpath directory.
403 std::string base_dir;
404 std::string apk_dir(input_file_name);
405 unsigned long dir_index = apk_dir.rfind('/');
406 bool has_base_dir = dir_index != std::string::npos;
407 if (has_base_dir) {
408 apk_dir = apk_dir.substr(0, dir_index);
409 base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
410 }
411
412 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
413
414 std::string compilation_reason_arg = compilation_reason == nullptr
415 ? ""
416 : std::string("--compilation-reason=") + compilation_reason;
417
418 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
419
420 // Disable cdex if update input vdex is true since this combination of options is not
421 // supported.
422 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
423
424 AddArg(zip_fd_arg);
425 AddArg(zip_location_arg);
426 AddArg(input_vdex_fd_arg);
427 AddArg(output_vdex_fd_arg);
428 AddArg(oat_fd_arg);
429 AddArg(oat_location_arg);
430 AddArg(instruction_set_arg);
431
432 AddArg(instruction_set_variant_arg);
433 AddArg(instruction_set_features_arg);
434
435 AddRuntimeArg(dex2oat_Xms_arg);
436 AddRuntimeArg(dex2oat_Xmx_arg);
437
438 AddArg(resolve_startup_string_arg);
Mathieu Chartier5880c032018-11-28 19:15:41 -0800439 AddArg(image_block_size_arg);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800440 AddArg(dex2oat_compiler_filter_arg);
441 AddArg(dex2oat_threads_arg);
442 AddArg(dex2oat_swap_fd);
443 AddArg(dex2oat_image_fd);
444
445 if (generate_debug_info) {
446 AddArg("--generate-debug-info");
447 }
448 if (debuggable) {
449 AddArg("--debuggable");
450 }
451 AddArg(image_format_arg);
452 AddArg(dex2oat_large_app_threshold_arg);
453
454 if (have_dex2oat_relocation_skip_flag) {
455 AddRuntimeArg(dex2oat_norelocation);
456 }
457 AddArg(profile_arg);
458 AddArg(base_dir);
459 AddArg(class_loader_context_arg);
460 if (generate_minidebug_info) {
461 AddArg(kMinidebugDex2oatFlag);
462 }
463 if (disable_cdex) {
464 AddArg(kDisableCompactDexFlag);
465 }
466 AddArg(target_sdk_version_arg);
467 if (enable_hidden_api_checks) {
468 AddRuntimeArg("-Xhidden-api-checks");
469 }
470
471 if (dex_metadata_fd > -1) {
472 AddArg(dex_metadata_fd_arg);
473 }
474
475 AddArg(compilation_reason_arg);
476
477 // Do not add args after dex2oat_flags, they should override others for debugging.
478 args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
479
480 PrepareArgs(dex2oat_bin);
Mathieu Chartier31636522018-11-09 23:53:07 +0000481 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800482};
Jeff Sharkey90aff262016-12-12 14:28:24 -0700483
484/*
485 * Whether dexopt should use a swap file when compiling an APK.
486 *
487 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
488 * itself, anyways).
489 *
490 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
491 *
492 * Otherwise, return true if this is a low-mem device.
493 *
494 * Otherwise, return default value.
495 */
496static bool kAlwaysProvideSwapFile = false;
497static bool kDefaultProvideSwapFile = true;
498
499static bool ShouldUseSwapFileForDexopt() {
500 if (kAlwaysProvideSwapFile) {
501 return true;
502 }
503
504 // Check the "override" property. If it exists, return value == "true".
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700505 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
506 if (!dex2oat_prop_buf.empty()) {
507 return dex2oat_prop_buf == "true";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700508 }
509
510 // Shortcut for default value. This is an implementation optimization for the process sketched
511 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
512 // as low-mem is never returning false. The compiler will optimize this away if it can.
513 if (kDefaultProvideSwapFile) {
514 return true;
515 }
516
Mathieu Chartier9b2da082018-10-26 13:23:11 -0700517 if (GetBoolProperty("ro.config.low_ram", false)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700518 return true;
519 }
520
521 // Default value must be false here.
522 return kDefaultProvideSwapFile;
523}
524
Richard Uhler76cc0272016-12-08 10:46:35 +0000525static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700526 if (set_to_bg) {
527 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800528 PLOG(ERROR) << "set_sched_policy failed";
529 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700530 }
531 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800532 PLOG(ERROR) << "setpriority failed";
533 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700534 }
535 }
536}
537
Calin Juravle29591732017-11-20 17:46:19 -0800538static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
539 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800540 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800541 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800542 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800543 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800544 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700545 }
Calin Juravle114f0812017-03-08 19:05:07 -0800546 // Profiles should belong to the app; make sure of that by giving ownership to
547 // the app uid. If we cannot do that, there's no point in returning the fd
548 // since dex2oat/profman will fail with SElinux denials.
549 if (fchown(fd.get(), uid, uid) < 0) {
550 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800551 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800552 }
Calin Juravle29591732017-11-20 17:46:19 -0800553 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800554}
555
Calin Juravle29591732017-11-20 17:46:19 -0800556static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800557 // Do not follow symlinks when opening a profile:
558 // - primary profiles should not contain symlinks in their paths
559 // - secondary dex paths should have been already resolved and validated
560 flags |= O_NOFOLLOW;
561
Calin Juravle29591732017-11-20 17:46:19 -0800562 // Check if we need to create the profile
563 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
564 unique_fd fd;
565 if ((flags & O_CREAT) != 0) {
566 fd = create_profile(uid, profile, flags);
567 } else {
568 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
569 }
570
Calin Juravle114f0812017-03-08 19:05:07 -0800571 if (fd.get() < 0) {
572 if (errno != ENOENT) {
573 // Profiles might be missing for various reasons. For example, in a
574 // multi-user environment, the profile directory for one user can be created
575 // after we start a merge. In this case the current profile for that user
576 // will not be found.
577 // Also, the secondary dex profiles might be deleted by the app at any time,
578 // so we can't we need to prepare if they are missing.
579 PLOG(ERROR) << "Failed to open profile " << profile;
580 }
581 return invalid_unique_fd();
582 }
583
Jeff Sharkey90aff262016-12-12 14:28:24 -0700584 return fd;
585}
586
Calin Juravle824a64d2018-01-18 20:23:17 -0800587static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
588 const std::string& location, bool is_secondary_dex) {
589 std::string profile = create_current_profile_path(user, package_name, location,
590 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800591 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800592}
593
Calin Juravle824a64d2018-01-18 20:23:17 -0800594static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
595 const std::string& location, bool read_write, bool is_secondary_dex) {
596 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800597 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
598}
599
600static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800601 const std::string& location) {
602 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800603 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800604}
605
Calin Juravle824a64d2018-01-18 20:23:17 -0800606static void open_profile_files(uid_t uid, const std::string& package_name,
607 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800608 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700609 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800610 *reference_profile_fd = open_reference_profile(uid, package_name, location,
611 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700612
Calin Juravle114f0812017-03-08 19:05:07 -0800613 // For secondary dex files, we don't really need the user but we use it for sanity checks.
614 // Note: the user owning the dex file should be the current user.
615 std::vector<userid_t> users;
616 if (is_secondary_dex){
617 users.push_back(multiuser_get_user_id(uid));
618 } else {
619 users = get_known_users(/*volume_uuid*/ nullptr);
620 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700621 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800622 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
623 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700624 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800625 if (profile_fd.get() >= 0) {
626 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700627 }
628 }
629}
630
631static void drop_capabilities(uid_t uid) {
632 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800633 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
634 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700635 }
636 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800637 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
638 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700639 }
640 // drop capabilities
641 struct __user_cap_header_struct capheader;
642 struct __user_cap_data_struct capdata[2];
643 memset(&capheader, 0, sizeof(capheader));
644 memset(&capdata, 0, sizeof(capdata));
645 capheader.version = _LINUX_CAPABILITY_VERSION_3;
646 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800647 PLOG(ERROR) << "capset failed";
648 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700649 }
650}
651
652static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
653static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
654static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
655static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
656static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
657
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800658class RunProfman : public ExecVHelper {
659 public:
660 void SetupArgs(const std::vector<unique_fd>& profile_fds,
661 const unique_fd& reference_profile_fd,
662 const std::vector<unique_fd>& apk_fds,
663 const std::vector<std::string>& dex_locations,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800664 bool copy_and_update,
665 bool store_aggregation_counters) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800666 const char* profman_bin =
Andreas Gampe3a77feb2018-12-10 23:13:49 +0000667 is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700668
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800669 if (copy_and_update) {
670 CHECK_EQ(1u, profile_fds.size());
671 CHECK_EQ(1u, apk_fds.size());
Mathieu Chartier31636522018-11-09 23:53:07 +0000672 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800673 if (reference_profile_fd != -1) {
674 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
Mathieu Chartier31636522018-11-09 23:53:07 +0000675 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800676
677 for (const unique_fd& fd : profile_fds) {
678 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
679 }
680
681 for (const unique_fd& fd : apk_fds) {
682 AddArg("--apk-fd=" + std::to_string(fd.get()));
683 }
684
685 for (const std::string& dex_location : dex_locations) {
686 AddArg("--dex-location=" + dex_location);
687 }
688
689 if (copy_and_update) {
690 AddArg("--copy-and-update-profile-key");
691 }
692
Calin Juravleb3a929d2018-12-11 14:40:00 -0800693 if (store_aggregation_counters) {
694 AddArg("--store-aggregation-counters");
695 }
696
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800697 // Do not add after dex2oat_flags, they should override others for debugging.
698 PrepareArgs(profman_bin);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800699 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700700
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800701 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
702 const unique_fd& reference_profile_fd,
703 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
Calin Juravleb3a929d2018-12-11 14:40:00 -0800704 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
705 bool store_aggregation_counters = false) {
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800706 SetupArgs(profiles_fd,
Calin Juravleb3a929d2018-12-11 14:40:00 -0800707 reference_profile_fd,
708 apk_fds,
709 dex_locations,
710 /*copy_and_update=*/false,
711 store_aggregation_counters);
Mathieu Chartier62d218d2018-11-05 09:34:24 -0800712 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700713
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800714 void SetupCopyAndUpdate(unique_fd&& profile_fd,
715 unique_fd&& reference_profile_fd,
716 unique_fd&& apk_fd,
717 const std::string& dex_location) {
718 // The fds need to stay open longer than the scope of the function, so put them into a local
719 // variable vector.
720 profiles_fd_.push_back(std::move(profile_fd));
721 apk_fds_.push_back(std::move(apk_fd));
722 reference_profile_fd_ = std::move(reference_profile_fd);
723 std::vector<std::string> dex_locations = {dex_location};
Calin Juravleb3a929d2018-12-11 14:40:00 -0800724 SetupArgs(profiles_fd_,
725 reference_profile_fd_,
726 apk_fds_,
727 dex_locations,
728 /*copy_and_update=*/true,
729 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800730 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000731
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800732 void SetupDump(const std::vector<unique_fd>& profiles_fd,
733 const unique_fd& reference_profile_fd,
734 const std::vector<std::string>& dex_locations,
735 const std::vector<unique_fd>& apk_fds,
736 const unique_fd& output_fd) {
737 AddArg("--dump-only");
738 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Calin Juravleb3a929d2018-12-11 14:40:00 -0800739 SetupArgs(profiles_fd,
740 reference_profile_fd,
741 apk_fds,
742 dex_locations,
743 /*copy_and_update=*/false,
744 /*store_aggregation_counters=*/false);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800745 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000746
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800747 void Exec() {
748 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
749 }
Mathieu Chartier31636522018-11-09 23:53:07 +0000750
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800751 private:
752 unique_fd reference_profile_fd_;
753 std::vector<unique_fd> profiles_fd_;
754 std::vector<unique_fd> apk_fds_;
755};
Mathieu Chartier31636522018-11-09 23:53:07 +0000756
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800757
Calin Juravlef63d4792018-01-30 17:43:34 +0000758
Jeff Sharkey90aff262016-12-12 14:28:24 -0700759// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800760// The location is the package name for primary apks or the dex path for secondary dex files.
761// Returns true if there is enough information in the current profiles that makes it
762// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763// If the return value is true all the current profiles would have been merged into
764// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800765static bool analyze_profiles(uid_t uid, const std::string& package_name,
766 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800767 std::vector<unique_fd> profiles_fd;
768 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800769 open_profile_files(uid, package_name, location, is_secondary_dex,
770 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800771 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700772 // Skip profile guided compilation because no profiles were found.
773 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774 return false;
775 }
776
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800777 RunProfman profman_merge;
778 profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 pid_t pid = fork();
780 if (pid == 0) {
781 /* child -- drop privileges before continuing */
782 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800783 profman_merge.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 }
785 /* parent */
786 int return_code = wait_child(pid);
787 bool need_to_compile = false;
788 bool should_clear_current_profiles = false;
789 bool should_clear_reference_profile = false;
790 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800791 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792 } else {
793 return_code = WEXITSTATUS(return_code);
794 switch (return_code) {
795 case PROFMAN_BIN_RETURN_CODE_COMPILE:
796 need_to_compile = true;
797 should_clear_current_profiles = true;
798 should_clear_reference_profile = false;
799 break;
800 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
801 need_to_compile = false;
802 should_clear_current_profiles = false;
803 should_clear_reference_profile = false;
804 break;
805 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800806 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807 need_to_compile = false;
808 should_clear_current_profiles = true;
809 should_clear_reference_profile = true;
810 break;
811 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
812 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
813 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800814 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700815 need_to_compile = false;
816 should_clear_current_profiles = false;
817 should_clear_reference_profile = false;
818 break;
819 default:
820 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800821 LOG(WARNING) << "Unknown error code while processing profiles for location "
822 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700823 need_to_compile = false;
824 should_clear_current_profiles = true;
825 should_clear_reference_profile = true;
826 break;
827 }
828 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800829
Jeff Sharkey90aff262016-12-12 14:28:24 -0700830 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800831 if (is_secondary_dex) {
832 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800833 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
834 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800835 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800836 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800837 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700838 }
839 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800840 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841 }
842 return need_to_compile;
843}
844
Calin Juravle114f0812017-03-08 19:05:07 -0800845// Decides if profile guided compilation is needed or not based on existing profiles.
846// The analysis is done for the primary apks of the given package.
847// Returns true if there is enough information in the current profiles that makes it
848// worth to recompile the package.
849// If the return value is true all the current profiles would have been merged into
850// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800851bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
852 const std::string& profile_name) {
853 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800854}
855
Calin Juravle408cd4a2018-01-20 23:34:18 -0800856bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
857 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800858 std::vector<unique_fd> profile_fds;
859 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800860 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
861 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862
Calin Juravle408cd4a2018-01-20 23:34:18 -0800863 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800864 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800866 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867 const bool has_profiles = !profile_fds.empty();
868
869 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800870 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 return false;
872 }
873
Calin Juravle114f0812017-03-08 19:05:07 -0800874 unique_fd output_fd(open(out_file_name.c_str(),
875 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700876 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800877 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700878 return false;
879 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800880
Jeff Sharkey90aff262016-12-12 14:28:24 -0700881 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800882 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800883 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
884 if (apk_fd == -1) {
885 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
886 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700887 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800888 dex_locations.push_back(get_location_from_path(code_path.c_str()));
889 apk_fds.push_back(std::move(apk_fd));
890
Jeff Sharkey90aff262016-12-12 14:28:24 -0700891
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800892 RunProfman profman_dump;
893 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 pid_t pid = fork();
895 if (pid == 0) {
896 /* child -- drop privileges before continuing */
897 drop_capabilities(uid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -0800898 profman_dump.Exec();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700899 }
900 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700901 int return_code = wait_child(pid);
902 if (!WIFEXITED(return_code)) {
903 LOG(WARNING) << "profman failed for package " << pkgname << ": "
904 << return_code;
905 return false;
906 }
907 return true;
908}
909
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700910bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800911 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700912 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
913 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800914 package_name,
915 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700916 /*read_write*/ true,
917 /*secondary*/ false));
918 if (in_fd.get() < 0) {
919 PLOG(WARNING) << "Could not open profile " << system_profile;
920 return false;
921 }
922 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800923 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700924 return false;
925 }
926
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700927 // As a security measure we want to write the profile information with the reduced capabilities
928 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700929 pid_t pid = fork();
930 if (pid == 0) {
931 /* child -- drop privileges before continuing */
932 drop_capabilities(packageUid);
933
934 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
935 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800936 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700937 }
938 // This implies that the app owning this profile is running
939 // (and has acquired the lock).
940 //
941 // The app never acquires the lock for the reference profiles of primary apks.
942 // Only dex2oat from installd will do that. Since installd is single threaded
943 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -0800944 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700945 return false;
946 }
947
948 bool truncated = ftruncate(out_fd.get(), 0) == 0;
949 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800950 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700951 }
952
953 // Copy over data.
954 static constexpr size_t kBufferSize = 4 * 1024;
955 char buffer[kBufferSize];
956 while (true) {
957 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
958 if (bytes == 0) {
959 break;
960 }
961 write(out_fd.get(), buffer, bytes);
962 }
963 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800964 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700965 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700966 // Use _exit since we don't want to run the global destructors in the child.
967 // b/62597429
968 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700969 }
970 /* parent */
971 int return_code = wait_child(pid);
972 return return_code == 0;
973}
974
Jeff Sharkey90aff262016-12-12 14:28:24 -0700975static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
976 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
977 if (EndsWith(oat_path, ".dex")) {
978 std::string new_path = oat_path;
979 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800980 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700981 return new_path;
982 }
983
984 // An odex entry. Not that this may not be an extension, e.g., in the OTA
985 // case (where the base name will have an extension for the B artifact).
986 size_t odex_pos = oat_path.rfind(".odex");
987 if (odex_pos != std::string::npos) {
988 std::string new_path = oat_path;
989 new_path.replace(odex_pos, strlen(".odex"), new_ext);
990 CHECK_NE(new_path.find(new_ext), std::string::npos);
991 return new_path;
992 }
993
994 // Don't know how to handle this.
995 return "";
996}
997
998// Translate the given oat path to an art (app image) path. An empty string
999// denotes an error.
1000static std::string create_image_filename(const std::string& oat_path) {
1001 return replace_file_extension(oat_path, ".art");
1002}
1003
1004// Translate the given oat path to a vdex path. An empty string denotes an error.
1005static std::string create_vdex_filename(const std::string& oat_path) {
1006 return replace_file_extension(oat_path, ".vdex");
1007}
1008
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009static int open_output_file(const char* file_name, bool recreate, int permissions) {
1010 int flags = O_RDWR | O_CREAT;
1011 if (recreate) {
1012 if (unlink(file_name) < 0) {
1013 if (errno != ENOENT) {
1014 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1015 }
1016 }
1017 flags |= O_EXCL;
1018 }
1019 return open(file_name, flags, permissions);
1020}
1021
Calin Juravle2289c0a2017-02-15 12:44:14 -08001022static bool set_permissions_and_ownership(
1023 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1024 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1025 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001026 if (fchmod(fd,
1027 S_IRUSR|S_IWUSR|S_IRGRP |
1028 (is_public ? S_IROTH : 0)) < 0) {
1029 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1030 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001031 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001032 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1033 return false;
1034 }
1035 return true;
1036}
1037
1038static bool IsOutputDalvikCache(const char* oat_dir) {
1039 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1040 // into '!'. Play it safe by handling it both.
1041 // TODO: ensure we never get null.
1042 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1043 return oat_dir == nullptr || oat_dir[0] == '!';
1044}
1045
Calin Juravled23dee72017-07-06 16:29:11 -07001046// Best-effort check whether we can fit the the path into our buffers.
1047// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1048// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1049// extension to the cache path (5 bytes).
1050// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1051static bool validate_dex_path_size(const std::string& dex_path) {
1052 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1053 LOG(ERROR) << "dex_path too long: " << dex_path;
1054 return false;
1055 }
1056 return true;
1057}
1058
Jeff Sharkey90aff262016-12-12 14:28:24 -07001059static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001060 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001061 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001062 return false;
1063 }
1064
1065 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001066 // Oat dirs for secondary dex files are already validated.
1067 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001068 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1069 return false;
1070 }
1071 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1072 return false;
1073 }
1074 } else {
1075 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1076 return false;
1077 }
1078 }
1079 return true;
1080}
1081
1082// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1083// on destruction. It will also run the given cleanup (unless told not to) after closing.
1084//
1085// Usage example:
1086//
Calin Juravle7a570e82017-01-14 16:23:30 -08001087// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001088// [name]() {
1089// unlink(name.c_str());
1090// });
1091// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1092// wrapper if captured as a reference.
1093//
1094// if (file.get() == -1) {
1095// // Error opening...
1096// }
1097//
1098// ...
1099// if (error) {
1100// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1101// // and delete the file (after the fd is closed).
1102// return -1;
1103// }
1104//
1105// (Success case)
1106// file.SetCleanup(false);
1107// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1108// // (leaving the file around; after the fd is closed).
1109//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001110class Dex2oatFileWrapper {
1111 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001112 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001113 }
1114
Calin Juravle7a570e82017-01-14 16:23:30 -08001115 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1116 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1117
1118 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1119 value_ = other.value_;
1120 cleanup_ = other.cleanup_;
1121 do_cleanup_ = other.do_cleanup_;
1122 auto_close_ = other.auto_close_;
1123 other.release();
1124 }
1125
1126 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1127 value_ = other.value_;
1128 cleanup_ = other.cleanup_;
1129 do_cleanup_ = other.do_cleanup_;
1130 auto_close_ = other.auto_close_;
1131 other.release();
1132 return *this;
1133 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001134
1135 ~Dex2oatFileWrapper() {
1136 reset(-1);
1137 }
1138
1139 int get() {
1140 return value_;
1141 }
1142
1143 void SetCleanup(bool cleanup) {
1144 do_cleanup_ = cleanup;
1145 }
1146
1147 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001148 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001149 close(value_);
1150 }
1151 if (do_cleanup_ && cleanup_ != nullptr) {
1152 cleanup_();
1153 }
1154
1155 value_ = new_value;
1156 }
1157
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 void reset(int new_value, std::function<void ()> new_cleanup) {
1159 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001160 close(value_);
1161 }
1162 if (do_cleanup_ && cleanup_ != nullptr) {
1163 cleanup_();
1164 }
1165
1166 value_ = new_value;
1167 cleanup_ = new_cleanup;
1168 }
1169
Calin Juravle7a570e82017-01-14 16:23:30 -08001170 void DisableAutoClose() {
1171 auto_close_ = false;
1172 }
1173
Jeff Sharkey90aff262016-12-12 14:28:24 -07001174 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001175 void release() {
1176 value_ = -1;
1177 do_cleanup_ = false;
1178 cleanup_ = nullptr;
1179 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001180 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001181 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001182 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001183 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001184};
1185
Calin Juravle7a570e82017-01-14 16:23:30 -08001186// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001187Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1188 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001189
1190 // We don't create an image for secondary dex files.
1191 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 return Dex2oatFileWrapper();
1193 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001194
Calin Juravle7a570e82017-01-14 16:23:30 -08001195 const std::string image_path = create_image_filename(out_oat_path);
1196 if (image_path.empty()) {
1197 // Happens when the out_oat_path has an unknown extension.
1198 return Dex2oatFileWrapper();
1199 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001200
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001201 // In case there is a stale image, remove it now. Ignore any error.
1202 unlink(image_path.c_str());
1203
1204 // Not enabled, exit.
1205 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001206 return Dex2oatFileWrapper();
1207 }
Mathieu Chartier9b2da082018-10-26 13:23:11 -07001208 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
1209 if (app_image_format.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001210 return Dex2oatFileWrapper();
1211 }
1212 // Recreate is true since we do not want to modify a mapped image. If the app is
1213 // already running and we modify the image file, it can cause crashes (b/27493510).
1214 Dex2oatFileWrapper wrapper_fd(
1215 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1216 [image_path]() { unlink(image_path.c_str()); });
1217 if (wrapper_fd.get() < 0) {
1218 // Could not create application image file. Go on since we can compile without it.
1219 LOG(ERROR) << "installd could not create '" << image_path
1220 << "' for image file during dexopt";
1221 // If we have a valid image file path but no image fd, explicitly erase the image file.
1222 if (unlink(image_path.c_str()) < 0) {
1223 if (errno != ENOENT) {
1224 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1225 }
1226 }
1227 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001228 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001229 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1230 wrapper_fd.reset(-1);
1231 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001232
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 return wrapper_fd;
1234}
1235
1236// Creates the dexopt swap file if necessary and return its fd.
1237// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001238unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001239 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001240 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001241 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001242 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001243 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001244 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001245 if (swap_fd.get() < 0) {
1246 // Could not create swap file. Optimistically go on and hope that we can compile
1247 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001248 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 } else {
1250 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001251 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001252 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1253 }
1254 }
1255 return swap_fd;
1256}
1257
1258// Opens the reference profiles if needed.
1259// 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 -08001260Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001261 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001262 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001263 // If we are not profile guided compilation, or we are compiling system server
1264 // do not bother to open the profiles; we won't be using them.
1265 if (!profile_guided || (pkgname[0] == '*')) {
1266 return Dex2oatFileWrapper();
1267 }
1268
1269 // If this is a secondary dex path which is public do not open the profile.
1270 // We cannot compile public secondary dex paths with profiles. That's because
1271 // it will expose how the dex files are used by their owner.
1272 //
1273 // Note that the PackageManager is responsible to set the is_public flag for
1274 // primary apks and we do not check it here. In some cases, e.g. when
1275 // compiling with a public profile from the .dm file the PackageManager will
1276 // set is_public toghether with the profile guided compilation.
1277 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001278 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001279 }
Calin Juravle114f0812017-03-08 19:05:07 -08001280
1281 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001282 std::string location;
1283 if (is_secondary_dex) {
1284 location = dex_path;
1285 } else {
1286 if (profile_name == nullptr) {
1287 // This path is taken for system server re-compilation lunched from ZygoteInit.
1288 return Dex2oatFileWrapper();
1289 } else {
1290 location = profile_name;
1291 }
1292 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001293 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1294 is_secondary_dex);
1295 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1296 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001297 };
1298 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001299}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001300
Calin Juravle7a570e82017-01-14 16:23:30 -08001301// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1302// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001303bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001304 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001305 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001306 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1307 CHECK(in_vdex_wrapper_fd != nullptr);
1308 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001309 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1310 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001311 char in_odex_path[PKG_PATH_MAX];
1312 int dexopt_action = abs(dexopt_needed);
1313 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001314 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001315
1316 // Infer the name of the output VDEX.
1317 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1318 if (out_vdex_path_str.empty()) {
1319 return false;
1320 }
1321
1322 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001323 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001324 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1325 const char* path = nullptr;
1326 if (is_odex_location) {
1327 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1328 path = in_odex_path;
1329 } else {
1330 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001331 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001332 }
1333 } else {
1334 path = out_oat_path;
1335 }
1336 in_vdex_path_str = create_vdex_filename(path);
1337 if (in_vdex_path_str.empty()) {
1338 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001339 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001340 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001341 // We can update in place when all these conditions are met:
1342 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1343 // on /system typically cannot be updated in place).
1344 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1345 // cannot be currently used by a running process.
1346 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1347 // different vdex files to operate.
1348 update_vdex_in_place =
1349 (in_vdex_path_str == out_vdex_path_str) &&
1350 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1351 !profile_guided;
1352 if (update_vdex_in_place) {
1353 // Open the file read-write to be able to update it.
1354 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1355 if (in_vdex_wrapper_fd->get() == -1) {
1356 // If we failed to open the file, we cannot update it in place.
1357 update_vdex_in_place = false;
1358 }
1359 } else {
1360 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1361 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001362 }
1363
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001364 // If we are updating the vdex in place, we do not need to recreate a vdex,
1365 // and can use the same existing one.
1366 if (update_vdex_in_place) {
1367 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1368 // have bogus stale vdex files.
1369 out_vdex_wrapper_fd->reset(
1370 in_vdex_wrapper_fd->get(),
1371 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1372 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1373 // wrapper).
1374 in_vdex_wrapper_fd->DisableAutoClose();
1375 } else {
1376 out_vdex_wrapper_fd->reset(
1377 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1378 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1379 if (out_vdex_wrapper_fd->get() < 0) {
1380 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1381 return false;
1382 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001383 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001384 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001385 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001386 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1387 return false;
1388 }
1389
1390 // If we got here we successfully opened the vdex files.
1391 return true;
1392}
1393
1394// Opens the output oat file for the given apk.
1395// If successful it stores the output path into out_oat_path and returns true.
1396Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001397 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1398 char* out_oat_path) {
1399 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001400 return Dex2oatFileWrapper();
1401 }
1402 const std::string out_oat_path_str(out_oat_path);
1403 Dex2oatFileWrapper wrapper_fd(
1404 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1405 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1406 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001407 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001408 } else if (!set_permissions_and_ownership(
1409 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001410 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1411 wrapper_fd.reset(-1);
1412 }
1413 return wrapper_fd;
1414}
1415
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001416// Creates RDONLY fds for oat and vdex files, if exist.
1417// Returns false if it fails to create oat out path for the given apk path.
1418// Note that the method returns true even if the files could not be opened.
1419bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1420 const std::string& oat_dir,
1421 const std::string& instruction_set,
1422 bool is_secondary_dex,
1423 unique_fd* oat_file_fd,
1424 unique_fd* vdex_file_fd) {
1425 char oat_path[PKG_PATH_MAX];
1426 if (!create_oat_out_path(apk_path.c_str(),
1427 instruction_set.c_str(),
1428 oat_dir.c_str(),
1429 is_secondary_dex,
1430 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001431 LOG(ERROR) << "Could not create oat out path for "
1432 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001433 return false;
1434 }
1435 oat_file_fd->reset(open(oat_path, O_RDONLY));
1436 if (oat_file_fd->get() < 0) {
1437 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1438 }
1439
1440 std::string vdex_filename = create_vdex_filename(oat_path);
1441 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1442 if (vdex_file_fd->get() < 0) {
1443 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1444 }
1445
1446 return true;
1447}
1448
Calin Juravle7a570e82017-01-14 16:23:30 -08001449// Updates the access times of out_oat_path based on those from apk_path.
1450void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1451 struct stat input_stat;
1452 memset(&input_stat, 0, sizeof(input_stat));
1453 if (stat(apk_path, &input_stat) != 0) {
1454 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1455 return;
1456 }
1457
1458 struct utimbuf ut;
1459 ut.actime = input_stat.st_atime;
1460 ut.modtime = input_stat.st_mtime;
1461 if (utime(out_oat_path, &ut) != 0) {
1462 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1463 }
1464}
1465
Calin Juravle80a21252017-01-17 14:43:25 -08001466// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001467// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1468// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1469// the profile has changed.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001470class RunDexoptAnalyzer : public ExecVHelper {
1471 public:
1472 RunDexoptAnalyzer(const std::string& dex_file,
1473 int vdex_fd,
1474 int oat_fd,
1475 int zip_fd,
1476 const std::string& instruction_set,
1477 const std::string& compiler_filter,
1478 bool profile_was_updated,
1479 bool downgrade,
1480 const char* class_loader_context) {
1481 CHECK_GE(zip_fd, 0);
1482 const char* dexoptanalyzer_bin =
Andreas Gampe3a77feb2018-12-10 23:13:49 +00001483 is_debug_runtime()
1484 ? "/system/bin/dexoptanalyzerd"
1485 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001486
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001487 std::string dex_file_arg = "--dex-file=" + dex_file;
1488 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1489 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1490 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1491 std::string isa_arg = "--isa=" + instruction_set;
1492 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1493 const char* assume_profile_changed = "--assume-profile-changed";
1494 const char* downgrade_flag = "--downgrade";
1495 std::string class_loader_context_arg = "--class-loader-context=";
1496 if (class_loader_context != nullptr) {
1497 class_loader_context_arg += class_loader_context;
1498 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001499
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001500 // program name, dex file, isa, filter
1501 AddArg(dex_file_arg);
1502 AddArg(isa_arg);
1503 AddArg(compiler_filter_arg);
1504 if (oat_fd >= 0) {
1505 AddArg(oat_fd_arg);
1506 }
1507 if (vdex_fd >= 0) {
1508 AddArg(vdex_fd_arg);
1509 }
1510 AddArg(zip_fd_arg.c_str());
1511 if (profile_was_updated) {
1512 AddArg(assume_profile_changed);
1513 }
1514 if (downgrade) {
1515 AddArg(downgrade_flag);
1516 }
1517 if (class_loader_context != nullptr) {
1518 AddArg(class_loader_context_arg.c_str());
1519 }
Mathieu Chartier31636522018-11-09 23:53:07 +00001520
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001521 PrepareArgs(dexoptanalyzer_bin);
1522 }
1523};
Calin Juravle80a21252017-01-17 14:43:25 -08001524
1525// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001526static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001527 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001528 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001529 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001530 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001531 return false;
1532 }
Calin Juravle114f0812017-03-08 19:05:07 -08001533 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001534
Calin Juravle80a21252017-01-17 14:43:25 -08001535 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001536 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1537 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001538 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001539 return false;
1540 }
1541
1542 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001543 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001544
Calin Juravle7d765462017-09-04 15:57:10 -07001545 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001546 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001547 return false;
1548 }
1549
1550 return true;
1551}
1552
Calin Juravle7d765462017-09-04 15:57:10 -07001553// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1554// secondary dex files. This return codes are returned by the child process created for
1555// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001556
Andreas Gampe194fe422018-02-28 20:16:19 -08001557enum DexoptAnalyzerSkipCodes {
1558 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001559 // Specific errors are encoded in the name.
1560 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1561 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1562 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1563 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1564 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001565 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001566 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001567};
Calin Juravle7d765462017-09-04 15:57:10 -07001568
1569// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001570// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1571// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001572// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1573// of dexoptanalyzer.
1574static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001575 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001576 // The result values are defined in dexoptanalyzer.
1577 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001578 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001579 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001580 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001581 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001582 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001583 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001584 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001585 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001586 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1587 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001588 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1589 " Expected odex file status for secondary dex %s"
1590 " : dexoptanalyzer result=%d",
1591 dex_path.c_str(),
1592 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001593 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001594 }
1595
1596 // Use a second switch for enum switch-case analysis.
1597 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001598 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001599 // If the file does not exist there's no need for dexopt.
1600 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1601 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001602
1603 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1604 *error_msg = "Dexoptanalyzer path validation failed";
1605 return false;
1606 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1607 *error_msg = "Dexoptanalyzer open zip failed";
1608 return false;
1609 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1610 *error_msg = "Dexoptanalyzer dir preparation failed";
1611 return false;
1612 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1613 *error_msg = "Dexoptanalyzer open output failed";
1614 return false;
1615 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1616 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001617 return false;
1618 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001619
1620 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1621 dex_path.c_str(),
1622 result);
1623 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001624}
1625
Calin Juravle7d765462017-09-04 15:57:10 -07001626enum SecondaryDexAccess {
1627 kSecondaryDexAccessReadOk = 0,
1628 kSecondaryDexAccessDoesNotExist = 1,
1629 kSecondaryDexAccessPermissionError = 2,
1630 kSecondaryDexAccessIOError = 3
1631};
1632
1633static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1634 // Check if the path exists and can be read. If not, there's nothing to do.
1635 if (access(dex_path.c_str(), R_OK) == 0) {
1636 return kSecondaryDexAccessReadOk;
1637 } else {
1638 if (errno == ENOENT) {
1639 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1640 return kSecondaryDexAccessDoesNotExist;
1641 } else {
1642 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1643 return errno == EACCES
1644 ? kSecondaryDexAccessPermissionError
1645 : kSecondaryDexAccessIOError;
1646 }
1647 }
1648}
1649
1650static bool is_file_public(const std::string& filename) {
1651 struct stat file_stat;
1652 if (stat(filename.c_str(), &file_stat) == 0) {
1653 return (file_stat.st_mode & S_IROTH) != 0;
1654 }
1655 return false;
1656}
1657
1658// Create the oat file structure for the secondary dex 'dex_path' and assign
1659// the individual path component to the 'out_' parameters.
1660static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001661 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001662 size_t dirIndex = dex_path.rfind('/');
1663 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001664 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001665 return false;
1666 }
1667 // TODO(calin): we have similar computations in at lest 3 other places
1668 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1669 // using string append.
1670 std::string apk_dir = dex_path.substr(0, dirIndex);
1671 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1672 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1673
1674 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1675 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001676 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001677 return false;
1678 }
1679 return true;
1680}
1681
1682// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1683// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001684static bool validate_dexopt_storage_flags(int dexopt_flags,
1685 int* out_storage_flag,
1686 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001687 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1688 *out_storage_flag = FLAG_STORAGE_CE;
1689 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001690 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001691 return false;
1692 }
1693 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1694 *out_storage_flag = FLAG_STORAGE_DE;
1695 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001696 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001697 return false;
1698 }
1699 return true;
1700}
1701
Calin Juravlec9eab382017-01-25 01:17:17 -08001702// 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 -08001703// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1704// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001705// When returning true, the output parameters will be:
1706// - is_public_out: whether or not the oat file should not be made public
1707// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1708// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001709static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001710 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001711 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001712 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1713 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001714 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001715 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001716 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1717 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001718 return false;
1719 }
Calin Juravle7d765462017-09-04 15:57:10 -07001720 // Compute the oat dir as it's not easy to extract it from the child computation.
1721 char oat_path[PKG_PATH_MAX];
1722 char oat_dir[PKG_PATH_MAX];
1723 char oat_isa_dir[PKG_PATH_MAX];
1724 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001725 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1726 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001727 return false;
1728 }
Calin Juravle7d765462017-09-04 15:57:10 -07001729 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001730
Calin Juravle80a21252017-01-17 14:43:25 -08001731 pid_t pid = fork();
1732 if (pid == 0) {
1733 // child -- drop privileges before continuing.
1734 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001735
1736 // Validate the path structure.
1737 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1738 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001739 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001740 }
1741
1742 // Open the dex file.
1743 unique_fd zip_fd;
1744 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1745 if (zip_fd.get() < 0) {
1746 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001747 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001748 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001749 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001750 }
1751 }
1752
1753 // Prepare the oat directories.
1754 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001755 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001756 }
1757
1758 // Open the vdex/oat files if any.
1759 unique_fd oat_file_fd;
1760 unique_fd vdex_file_fd;
1761 if (!maybe_open_oat_and_vdex_file(dex_path,
1762 *oat_dir_out,
1763 instruction_set,
1764 true /* is_secondary_dex */,
1765 &oat_file_fd,
1766 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001767 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001768 }
1769
1770 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001771 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1772 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001773
1774 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001775 // Note that we do not do it before the fork since opening the files is required to happen
1776 // after forking.
1777 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1778 vdex_file_fd.get(),
1779 oat_file_fd.get(),
1780 zip_fd.get(),
1781 instruction_set,
1782 compiler_filter, profile_was_updated,
1783 downgrade,
1784 class_loader_context);
1785 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001786 }
1787
1788 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001789 int result = wait_child(pid);
1790 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001791 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1792 dex_path.c_str(),
1793 result);
1794 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001795 return false;
1796 }
1797 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001798 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001799 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1800 result,
1801 dexopt_needed_out,
1802 error_msg);
1803 if (!success) {
1804 LOG(ERROR) << *error_msg;
1805 }
Calin Juravle7d765462017-09-04 15:57:10 -07001806
1807 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1808
Calin Juravle80a21252017-01-17 14:43:25 -08001809 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001810 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1811 // makes the code simpler; force compilation is only needed during tests).
1812 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001813 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001814 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001815 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1816 }
1817
Calin Juravle7d765462017-09-04 15:57:10 -07001818 // Check if we should make the oat file public.
1819 // Note that if the dex file is not public the compiled code cannot be made public.
1820 // It is ok to check this flag outside in the parent process.
1821 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1822
Calin Juravle80a21252017-01-17 14:43:25 -08001823 return success;
1824}
1825
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001826static std::string format_dexopt_error(int status, const char* dex_path) {
1827 if (WIFEXITED(status)) {
1828 int int_code = WEXITSTATUS(status);
1829 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1830 if (code_name != nullptr) {
1831 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1832 }
1833 }
1834 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001835}
1836
Calin Juravlec9eab382017-01-25 01:17:17 -08001837int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001838 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001839 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001840 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001841 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001842 CHECK(pkgname != nullptr);
1843 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001844 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001845 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1846 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001847
Calin Juravled23dee72017-07-06 16:29:11 -07001848 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001849 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001850 return -1;
1851 }
1852
1853 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001854 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1855 class_loader_context);
1856 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001857 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001858 }
1859
Calin Juravleebc8a792017-04-04 20:21:05 -07001860 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001861 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1862 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1863 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001864 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001865 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001866 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001867 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001868 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001869
1870 // Check if we're dealing with a secondary dex file and if we need to compile it.
1871 std::string oat_dir_str;
1872 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001873 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001874 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001875 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001876 oat_dir = oat_dir_str.c_str();
1877 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1878 return 0; // Nothing to do, report success.
1879 }
1880 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001881 if (error_msg->empty()) { // TODO: Make this a CHECK.
1882 *error_msg = "Failed processing secondary.";
1883 }
Calin Juravle80a21252017-01-17 14:43:25 -08001884 return -1; // We had an error, logged in the process method.
1885 }
1886 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001887 // Currently these flags are only use for secondary dex files.
1888 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001889 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1890 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1891 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001892
1893 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001894 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001895 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001896 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1897 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001898 return -1;
1899 }
1900
1901 // Create the output OAT file.
1902 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001903 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001904 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001905 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001906 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001907 return -1;
1908 }
1909
1910 // Open vdex files.
1911 Dex2oatFileWrapper in_vdex_fd;
1912 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001913 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1914 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001915 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001916 return -1;
1917 }
1918
Calin Juravlecb556e32017-04-04 20:22:50 -07001919 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1920 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1921 // fully inherit their parent context).
1922 // Note that for primary apk the oat files are created before, in a separate installd
1923 // call which also does the restorecon. TODO(calin): unify the paths.
1924 if (is_secondary_dex) {
1925 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1926 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001927 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1928 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001929 return -1;
1930 }
1931 }
1932
Jeff Sharkey90aff262016-12-12 14:28:24 -07001933 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001934 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001935
Calin Juravle7a570e82017-01-14 16:23:30 -08001936 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001937 Dex2oatFileWrapper image_fd = maybe_open_app_image(
1938 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001939
Calin Juravle7a570e82017-01-14 16:23:30 -08001940 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001941 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001942 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001943
Calin Juravle62c5a372018-02-01 17:03:23 +00001944 unique_fd dex_metadata_fd;
1945 if (dex_metadata_path != nullptr) {
1946 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1947 if (dex_metadata_fd.get() < 0) {
1948 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1949 }
1950 }
1951
Andreas Gampe023b2242018-02-28 16:03:25 -08001952 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001953
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001954 RunDex2Oat runner(input_fd.get(),
1955 out_oat_fd.get(),
1956 in_vdex_fd.get(),
1957 out_vdex_fd.get(),
1958 image_fd.get(),
1959 dex_path,
1960 out_oat_path,
1961 swap_fd.get(),
1962 instruction_set,
1963 compiler_filter,
1964 debuggable,
1965 boot_complete,
1966 background_job_compile,
1967 reference_profile_fd.get(),
1968 class_loader_context,
1969 target_sdk_version,
1970 enable_hidden_api_checks,
1971 generate_compact_dex,
1972 dex_metadata_fd.get(),
1973 compilation_reason);
1974
Jeff Sharkey90aff262016-12-12 14:28:24 -07001975 pid_t pid = fork();
1976 if (pid == 0) {
1977 /* child -- drop privileges before continuing */
1978 drop_capabilities(uid);
1979
Richard Uhler76cc0272016-12-08 10:46:35 +00001980 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001981 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001982 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001983 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001984 }
1985
Mathieu Chartiercc66c442018-11-09 15:57:21 -08001986 runner.Exec(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001987 } else {
1988 int res = wait_child(pid);
1989 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001990 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001991 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001992 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1993 << std::hex << std::setw(4) << res << ", process failed";
1994 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001995 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001996 }
1997 }
1998
Calin Juravlec9eab382017-01-25 01:17:17 -08001999 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002000
2001 // We've been successful, don't delete output.
2002 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002003 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002004 image_fd.SetCleanup(false);
2005 reference_profile_fd.SetCleanup(false);
2006
2007 return 0;
2008}
2009
Calin Juravlec9eab382017-01-25 01:17:17 -08002010// Try to remove the given directory. Log an error if the directory exists
2011// and is empty but could not be removed.
2012static bool rmdir_if_empty(const char* dir) {
2013 if (rmdir(dir) == 0) {
2014 return true;
2015 }
2016 if (errno == ENOENT || errno == ENOTEMPTY) {
2017 return true;
2018 }
2019 PLOG(ERROR) << "Failed to remove dir: " << dir;
2020 return false;
2021}
2022
2023// Try to unlink the given file. Log an error if the file exists and could not
2024// be unlinked.
2025static bool unlink_if_exists(const std::string& file) {
2026 if (unlink(file.c_str()) == 0) {
2027 return true;
2028 }
2029 if (errno == ENOENT) {
2030 return true;
2031
2032 }
2033 PLOG(ERROR) << "Could not unlink: " << file;
2034 return false;
2035}
2036
Calin Juravle7d765462017-09-04 15:57:10 -07002037enum ReconcileSecondaryDexResult {
2038 kReconcileSecondaryDexExists = 0,
2039 kReconcileSecondaryDexCleanedUp = 1,
2040 kReconcileSecondaryDexValidationError = 2,
2041 kReconcileSecondaryDexCleanUpError = 3,
2042 kReconcileSecondaryDexAccessIOError = 4,
2043};
Calin Juravlec9eab382017-01-25 01:17:17 -08002044
2045// Reconcile the secondary dex 'dex_path' and its generated oat files.
2046// Return true if all the parameters are valid and the secondary dex file was
2047// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2048// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2049// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2050// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2051// Return false if there were errors during processing. In this case
2052// out_secondary_dex_exists will be set to false.
2053bool reconcile_secondary_dex_file(const std::string& dex_path,
2054 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2055 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2056 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002057 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002058 if (isas.size() == 0) {
2059 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2060 return false;
2061 }
2062
Calin Juravle7d765462017-09-04 15:57:10 -07002063 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2064 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2065 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002066 return false;
2067 }
2068
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002069 // As a security measure we want to unlink art artifacts with the reduced capabilities
2070 // of the package user id. So we fork and drop capabilities in the child.
2071 pid_t pid = fork();
2072 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002073 /* child -- drop privileges before continuing */
2074 drop_capabilities(uid);
2075
2076 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2077 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2078 uid, storage_flag)) {
2079 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2080 _exit(kReconcileSecondaryDexValidationError);
2081 }
2082
2083 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2084 switch (access_check) {
2085 case kSecondaryDexAccessDoesNotExist:
2086 // File does not exist. Proceed with cleaning.
2087 break;
2088 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2089 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2090 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2091 default:
2092 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2093 _exit(kReconcileSecondaryDexValidationError);
2094 }
2095
2096 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002097 char oat_path[PKG_PATH_MAX];
2098 char oat_dir[PKG_PATH_MAX];
2099 char oat_isa_dir[PKG_PATH_MAX];
2100 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002101 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002102 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002103 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002104 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2105 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002106 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002107 }
Calin Juravle51314092017-05-18 15:33:05 -07002108
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002109 // Delete oat/vdex/art files.
2110 result = unlink_if_exists(oat_path) && result;
2111 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2112 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002113
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002114 // Delete profiles.
2115 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002116 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002117 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002118 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002119 result = unlink_if_exists(current_profile) && result;
2120 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002121
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002122 // We upgraded once the location of current profile for secondary dex files.
2123 // Check for any previous left-overs and remove them as well.
2124 std::string old_current_profile = dex_path + ".prof";
2125 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002126
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002127 // Try removing the directories as well, they might be empty.
2128 result = rmdir_if_empty(oat_isa_dir) && result;
2129 result = rmdir_if_empty(oat_dir) && result;
2130 }
Calin Juravle7d765462017-09-04 15:57:10 -07002131 if (!result) {
2132 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2133 }
2134 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002135 }
2136
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002137 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002138 if (!WIFEXITED(return_code)) {
2139 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2140 } else {
2141 return_code = WEXITSTATUS(return_code);
2142 }
2143
2144 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2145
2146 switch (return_code) {
2147 case kReconcileSecondaryDexCleanedUp:
2148 case kReconcileSecondaryDexValidationError:
2149 // If we couldn't validate assume the dex file does not exist.
2150 // This will purge the entry from the PM records.
2151 *out_secondary_dex_exists = false;
2152 return true;
2153 case kReconcileSecondaryDexExists:
2154 *out_secondary_dex_exists = true;
2155 return true;
2156 case kReconcileSecondaryDexAccessIOError:
2157 // We had an access IO error.
2158 // Return false so that we can try again.
2159 // The value of out_secondary_dex_exists does not matter in this case and by convention
2160 // is set to false.
2161 *out_secondary_dex_exists = false;
2162 return false;
2163 default:
2164 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2165 *out_secondary_dex_exists = false;
2166 return false;
2167 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002168}
2169
Alan Stokesa25d90c2017-10-16 10:56:00 +01002170// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2171// Returns true if all parameters are valid and the hash successfully computed and stored in
2172// out_secondary_dex_hash.
2173// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2174// the app.
2175// For any other errors (e.g. if any of the parameters are invalid) returns false.
2176bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2177 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2178 std::vector<uint8_t>* out_secondary_dex_hash) {
2179 out_secondary_dex_hash->clear();
2180
2181 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2182
2183 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2184 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2185 << storage_flag;
2186 return false;
2187 }
2188
2189 // Pipe to get the hash result back from our child process.
2190 unique_fd pipe_read, pipe_write;
2191 if (!Pipe(&pipe_read, &pipe_write)) {
2192 PLOG(ERROR) << "Failed to create pipe";
2193 return false;
2194 }
2195
2196 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2197 // access data the app itself can access.
2198 pid_t pid = fork();
2199 if (pid == 0) {
2200 // child -- drop privileges before continuing
2201 drop_capabilities(uid);
2202 pipe_read.reset();
2203
2204 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2205 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002206 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002207 }
2208
2209 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2210 if (fd == -1) {
2211 if (errno == EACCES || errno == ENOENT) {
2212 // Not treated as an error.
2213 _exit(0);
2214 }
2215 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002216 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002217 }
2218
2219 SHA256_CTX ctx;
2220 SHA256_Init(&ctx);
2221
2222 std::vector<uint8_t> buffer(65536);
2223 while (true) {
2224 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2225 if (bytes_read == 0) {
2226 break;
2227 } else if (bytes_read == -1) {
2228 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002229 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002230 }
2231
2232 SHA256_Update(&ctx, buffer.data(), bytes_read);
2233 }
2234
2235 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2236 SHA256_Final(hash.data(), &ctx);
2237 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002238 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002239 }
2240
2241 _exit(0);
2242 }
2243
2244 // parent
2245 pipe_write.reset();
2246
2247 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2248 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2249 out_secondary_dex_hash->clear();
2250 }
2251 return wait_child(pid) == 0;
2252}
2253
Jeff Sharkey90aff262016-12-12 14:28:24 -07002254// Helper for move_ab, so that we can have common failure-case cleanup.
2255static bool unlink_and_rename(const char* from, const char* to) {
2256 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2257 // return a failure.
2258 struct stat s;
2259 if (stat(to, &s) == 0) {
2260 if (!S_ISREG(s.st_mode)) {
2261 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2262 return false;
2263 }
2264 if (unlink(to) != 0) {
2265 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2266 return false;
2267 }
2268 } else {
2269 // This may be a permission problem. We could investigate the error code, but we'll just
2270 // let the rename failure do the work for us.
2271 }
2272
2273 // Try to rename "to" to "from."
2274 if (rename(from, to) != 0) {
2275 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2276 return false;
2277 }
2278 return true;
2279}
2280
2281// Move/rename a B artifact (from) to an A artifact (to).
2282static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2283 // Check whether B exists.
2284 {
2285 struct stat s;
2286 if (stat(b_path.c_str(), &s) != 0) {
2287 // Silently ignore for now. The service calling this isn't smart enough to understand
2288 // lack of artifacts at the moment.
2289 return false;
2290 }
2291 if (!S_ISREG(s.st_mode)) {
2292 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2293 // Try to unlink, but swallow errors.
2294 unlink(b_path.c_str());
2295 return false;
2296 }
2297 }
2298
2299 // Rename B to A.
2300 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2301 // Delete the b_path so we don't try again (or fail earlier).
2302 if (unlink(b_path.c_str()) != 0) {
2303 PLOG(ERROR) << "Could not unlink " << b_path;
2304 }
2305
2306 return false;
2307 }
2308
2309 return true;
2310}
2311
2312bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2313 // Get the current slot suffix. No suffix, no A/B.
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002314 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2315 if (slot_suffix.empty()) {
2316 return false;
2317 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07002318
Mathieu Chartier9b2da082018-10-26 13:23:11 -07002319 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2320 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2321 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002322 }
2323
2324 // Validate other inputs.
2325 if (validate_apk_path(apk_path) != 0) {
2326 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2327 return false;
2328 }
2329 if (validate_apk_path(oat_dir) != 0) {
2330 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2331 return false;
2332 }
2333
2334 char a_path[PKG_PATH_MAX];
2335 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2336 return false;
2337 }
2338 const std::string a_vdex_path = create_vdex_filename(a_path);
2339 const std::string a_image_path = create_image_filename(a_path);
2340
2341 // B path = A path + slot suffix.
2342 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2343 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2344 const std::string b_image_path = StringPrintf("%s.%s",
2345 a_image_path.c_str(),
2346 slot_suffix.c_str());
2347
2348 bool success = true;
2349 if (move_ab_path(b_path, a_path)) {
2350 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2351 // Note: we can live without an app image. As such, ignore failure to move the image file.
2352 // If we decide to require the app image, or the app image being moved correctly,
2353 // then change accordingly.
2354 constexpr bool kIgnoreAppImageFailure = true;
2355
2356 if (!a_image_path.empty()) {
2357 if (!move_ab_path(b_image_path, a_image_path)) {
2358 unlink(a_image_path.c_str());
2359 if (!kIgnoreAppImageFailure) {
2360 success = false;
2361 }
2362 }
2363 }
2364 } else {
2365 // Cleanup: delete B image, ignore errors.
2366 unlink(b_image_path.c_str());
2367 success = false;
2368 }
2369 } else {
2370 // Cleanup: delete B image, ignore errors.
2371 unlink(b_vdex_path.c_str());
2372 unlink(b_image_path.c_str());
2373 success = false;
2374 }
2375 return success;
2376}
2377
2378bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2379 // Delete the oat/odex file.
2380 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002381 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002382 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002383 return false;
2384 }
2385
2386 // In case of a permission failure report the issue. Otherwise just print a warning.
2387 auto unlink_and_check = [](const char* path) -> bool {
2388 int result = unlink(path);
2389 if (result != 0) {
2390 if (errno == EACCES || errno == EPERM) {
2391 PLOG(ERROR) << "Could not unlink " << path;
2392 return false;
2393 }
2394 PLOG(WARNING) << "Could not unlink " << path;
2395 }
2396 return true;
2397 };
2398
2399 // Delete the oat/odex file.
2400 bool return_value_oat = unlink_and_check(out_path);
2401
2402 // Derive and delete the app image.
2403 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2404
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002405 // Derive and delete the vdex file.
2406 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2407
Jeff Sharkey90aff262016-12-12 14:28:24 -07002408 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002409 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002410}
2411
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002412static bool is_absolute_path(const std::string& path) {
2413 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2414 LOG(ERROR) << "Invalid absolute path " << path;
2415 return false;
2416 } else {
2417 return true;
2418 }
2419}
2420
2421static bool is_valid_instruction_set(const std::string& instruction_set) {
2422 // TODO: add explicit whitelisting of instruction sets
2423 if (instruction_set.find('/') != std::string::npos) {
2424 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2425 return false;
2426 } else {
2427 return true;
2428 }
2429}
2430
2431bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2432 const char *apk_path, const char *instruction_set) {
2433 std::string oat_dir_ = oat_dir;
2434 std::string apk_path_ = apk_path;
2435 std::string instruction_set_ = instruction_set;
2436
2437 if (!is_absolute_path(oat_dir_)) return false;
2438 if (!is_absolute_path(apk_path_)) return false;
2439 if (!is_valid_instruction_set(instruction_set_)) return false;
2440
2441 std::string::size_type end = apk_path_.rfind('.');
2442 std::string::size_type start = apk_path_.rfind('/', end);
2443 if (end == std::string::npos || start == std::string::npos) {
2444 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2445 return false;
2446 }
2447
2448 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2449 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2450 const char* res = res_.c_str();
2451 if (strlen(res) >= PKG_PATH_MAX) {
2452 LOG(ERROR) << "Result too large";
2453 return false;
2454 } else {
2455 strlcpy(path, res, PKG_PATH_MAX);
2456 return true;
2457 }
2458}
2459
2460bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2461 const char *instruction_set) {
2462 std::string apk_path_ = apk_path;
2463 std::string instruction_set_ = instruction_set;
2464
2465 if (!is_absolute_path(apk_path_)) return false;
2466 if (!is_valid_instruction_set(instruction_set_)) return false;
2467
2468 std::string::size_type end = apk_path_.rfind('.');
2469 std::string::size_type start = apk_path_.rfind('/', end);
2470 if (end == std::string::npos || start == std::string::npos) {
2471 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2472 return false;
2473 }
2474
2475 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2476 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2477}
2478
2479bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2480 const char *instruction_set) {
2481 std::string src_ = src;
2482 std::string instruction_set_ = instruction_set;
2483
2484 if (!is_absolute_path(src_)) return false;
2485 if (!is_valid_instruction_set(instruction_set_)) return false;
2486
2487 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2488 if (*it == '/') {
2489 *it = '@';
2490 }
2491 }
2492
2493 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2494 + DALVIK_CACHE_POSTFIX;
2495 const char* res = res_.c_str();
2496 if (strlen(res) >= PKG_PATH_MAX) {
2497 LOG(ERROR) << "Result too large";
2498 return false;
2499 } else {
2500 strlcpy(path, res, PKG_PATH_MAX);
2501 return true;
2502 }
2503}
2504
Calin Juravle59f7ab82018-04-27 17:50:23 -07002505bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2506 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002507 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2508 for (const std::string& elem : classpaths_elems) {
2509 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2510 if (fd < 0) {
2511 PLOG(ERROR) << "Could not open classpath elem " << elem;
2512 return false;
2513 } else {
2514 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002515 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002516 }
2517 }
2518 return true;
2519}
2520
2521static bool create_app_profile_snapshot(int32_t app_id,
2522 const std::string& package_name,
2523 const std::string& profile_name,
2524 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002525 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2526
Calin Juravle824a64d2018-01-18 20:23:17 -08002527 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002528 if (snapshot_fd < 0) {
2529 return false;
2530 }
2531
2532 std::vector<unique_fd> profiles_fd;
2533 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002534 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2535 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002536 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2537 return false;
2538 }
2539
2540 profiles_fd.push_back(std::move(reference_profile_fd));
2541
Calin Juravle0d0a4922018-01-23 19:54:11 -08002542 // Open the class paths elements. These will be used to filter out profile data that does
2543 // not belong to the classpath during merge.
2544 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002545 std::vector<std::string> dex_locations;
2546 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002547 return false;
2548 }
2549
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002550 RunProfman args;
2551 args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002552 pid_t pid = fork();
2553 if (pid == 0) {
2554 /* child -- drop privileges before continuing */
2555 drop_capabilities(app_shared_gid);
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002556 args.Exec();
Calin Juravle29591732017-11-20 17:46:19 -08002557 }
2558
2559 /* parent */
2560 int return_code = wait_child(pid);
2561 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002562 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002563 return false;
2564 }
2565
2566 return true;
2567}
2568
Calin Juravle0d0a4922018-01-23 19:54:11 -08002569static bool create_boot_image_profile_snapshot(const std::string& package_name,
2570 const std::string& profile_name,
2571 const std::string& classpath) {
2572 // The reference profile directory for the android package might not be prepared. Do it now.
2573 const std::string ref_profile_dir =
2574 create_primary_reference_profile_package_dir_path(package_name);
2575 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2576 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2577 return false;
2578 }
2579
Mathieu Chartiere0d64a12018-11-01 12:07:26 -07002580 // Return false for empty class path since it may otherwise return true below if profiles is
2581 // empty.
2582 if (classpath.empty()) {
2583 PLOG(ERROR) << "Class path is empty";
2584 return false;
2585 }
2586
Calin Juravle0d0a4922018-01-23 19:54:11 -08002587 // Open and create the snapshot profile.
2588 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2589
2590 // Collect all non empty profiles.
2591 // The collection will traverse all applications profiles and find the non empty files.
2592 // This has the potential of inspecting a large number of files and directories (depending
2593 // on the number of applications and users). So there is a slight increase in the chance
2594 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2595 // fail the snapshot and aggregate whatever profile we could open.
2596 //
2597 // The profile snapshot is a best effort based on available data it's ok if some data
2598 // from some apps is missing. It will be counter productive for the snapshot to fail
2599 // because we could not open or read some of the files.
2600 std::vector<std::string> profiles;
2601 if (!collect_profiles(&profiles)) {
2602 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2603 }
2604
2605 // If we have no profiles return early.
2606 if (profiles.empty()) {
2607 return true;
2608 }
2609
2610 // Open the classpath elements. These will be used to filter out profile data that does
2611 // not belong to the classpath during merge.
2612 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002613 std::vector<std::string> dex_locations;
2614 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002615 return false;
2616 }
2617
2618 // If we could not open any files from the classpath return an error.
2619 if (apk_fds.empty()) {
2620 LOG(ERROR) << "Could not open any of the classpath elements.";
2621 return false;
2622 }
2623
2624 // Aggregate the profiles in batches of kAggregationBatchSize.
2625 // We do this to avoid opening a huge a amount of files.
2626 static constexpr size_t kAggregationBatchSize = 10;
2627
2628 std::vector<unique_fd> profiles_fd;
2629 for (size_t i = 0; i < profiles.size(); ) {
2630 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2631 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2632 if (fd.get() >= 0) {
2633 profiles_fd.push_back(std::move(fd));
2634 }
2635 }
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002636 RunProfman args;
Calin Juravleb3a929d2018-12-11 14:40:00 -08002637 args.SetupMerge(profiles_fd,
2638 snapshot_fd,
2639 apk_fds,
2640 dex_locations,
2641 /*store_aggregation_counters=*/true);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002642 pid_t pid = fork();
2643 if (pid == 0) {
2644 /* child -- drop privileges before continuing */
2645 drop_capabilities(AID_SYSTEM);
2646
Calin Juravle59f7ab82018-04-27 17:50:23 -07002647 // The introduction of new access flags into boot jars causes them to
2648 // fail dex file verification.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002649 args.Exec();
Calin Juravle0d0a4922018-01-23 19:54:11 -08002650 }
2651
2652 /* parent */
2653 int return_code = wait_child(pid);
2654 if (!WIFEXITED(return_code)) {
2655 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2656 return false;
2657 }
2658 return true;
2659 }
2660 return true;
2661}
2662
2663bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2664 const std::string& profile_name, const std::string& classpath) {
2665 if (app_id == -1) {
2666 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2667 } else {
2668 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2669 }
2670}
2671
Calin Juravlec3b049e2018-01-18 22:32:58 -08002672bool prepare_app_profile(const std::string& package_name,
2673 userid_t user_id,
2674 appid_t app_id,
2675 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002676 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002677 const std::unique_ptr<std::string>& dex_metadata) {
2678 // Prepare the current profile.
2679 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2680 /*is_secondary_dex*/ false);
2681 uid_t uid = multiuser_get_uid(user_id, app_id);
2682 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2683 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2684 return false;
2685 }
2686
2687 // Check if we need to install the profile from the dex metadata.
2688 if (dex_metadata == nullptr) {
2689 return true;
2690 }
2691
2692 // We have a dex metdata. Merge the profile into the reference profile.
2693 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2694 /*read_write*/ true, /*is_secondary_dex*/ false);
2695 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2696 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002697 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2698 if (apk_fd < 0) {
2699 PLOG(ERROR) << "Could not open code path " << code_path;
2700 return false;
2701 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002702
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002703 RunProfman args;
2704 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2705 std::move(ref_profile_fd),
2706 std::move(apk_fd),
2707 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002708 pid_t pid = fork();
2709 if (pid == 0) {
2710 /* child -- drop privileges before continuing */
2711 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2712 drop_capabilities(app_shared_gid);
2713
Calin Juravlef63d4792018-01-30 17:43:34 +00002714 // The copy and update takes ownership over the fds.
Mathieu Chartiercc66c442018-11-09 15:57:21 -08002715 args.Exec();
Calin Juravlec3b049e2018-01-18 22:32:58 -08002716 }
2717
2718 /* parent */
2719 int return_code = wait_child(pid);
2720 if (!WIFEXITED(return_code)) {
2721 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2722 return false;
2723 }
2724 return true;
2725}
2726
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002727} // namespace installd
2728} // namespace android