blob: 9c9567e02191e3cecf7941a6ce23a38ab12b2092 [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 */
Mark Salyzyna5e161b2016-09-29 08:08:05 -070016#define LOG_TAG "installed"
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
Alan Stokesa25d90c2017-10-16 10:56:00 +010031#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070032#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070033#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070035#include <android-base/strings.h>
36#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080037#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070038#include <cutils/properties.h>
39#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070040#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010041#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070042#include <private/android_filesystem_config.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070043#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070045
46#include "dexopt.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060047#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include "installd_deps.h"
49#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050#include "utils.h"
51
Jeff Sharkey90aff262016-12-12 14:28:24 -070052using android::base::EndsWith;
Alan Stokesa25d90c2017-10-16 10:56:00 +010053using android::base::ReadFully;
54using android::base::StringPrintf;
55using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080056using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070057
58namespace android {
59namespace installd {
60
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070061// Should minidebug info be included in compiled artifacts? Even if this value is
62// "true," usage might still be conditional to other constraints, e.g., system
63// property overrides.
64static constexpr bool kEnableMinidebugInfo = true;
65
66static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
67static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
68static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080069static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070070
Calin Juravle114f0812017-03-08 19:05:07 -080071// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
72struct FreeDelete {
73 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
74 void operator()(const void* ptr) const {
75 free(const_cast<void*>(ptr));
76 }
77};
78
79// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
80template <typename T>
81using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
82
Calin Juravle1a0af3b2017-03-09 14:33:33 -080083static unique_fd invalid_unique_fd() {
84 return unique_fd(-1);
85}
86
Andreas Gampe6a9cf722017-07-24 16:49:10 -070087static bool is_debug_runtime() {
88 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
89}
90
David Sehra3b5ab62017-10-25 14:27:29 -070091static bool is_debuggable_build() {
92 return android::base::GetBoolProperty("ro.debuggable", false);
93}
94
Jeff Sharkey90aff262016-12-12 14:28:24 -070095static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080096 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070097 if (ufd.get() < 0) {
98 if (errno != ENOENT) {
99 PLOG(WARNING) << "Could not open profile " << profile;
100 return false;
101 } else {
102 // Nothing to clear. That's ok.
103 return true;
104 }
105 }
106
107 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
108 if (errno != EWOULDBLOCK) {
109 PLOG(WARNING) << "Error locking profile " << profile;
110 }
111 // This implies that the app owning this profile is running
112 // (and has acquired the lock).
113 //
114 // If we can't acquire the lock bail out since clearing is useless anyway
115 // (the app will write again to the profile).
116 //
117 // Note:
118 // This does not impact the this is not an issue for the profiling correctness.
119 // In case this is needed because of an app upgrade, profiles will still be
120 // eventually cleared by the app itself due to checksum mismatch.
121 // If this is needed because profman advised, then keeping the data around
122 // until the next run is again not an issue.
123 //
124 // If the app attempts to acquire a lock while we've held one here,
125 // it will simply skip the current write cycle.
126 return false;
127 }
128
129 bool truncated = ftruncate(ufd.get(), 0) == 0;
130 if (!truncated) {
131 PLOG(WARNING) << "Could not truncate " << profile;
132 }
133 if (flock(ufd.get(), LOCK_UN) != 0) {
134 PLOG(WARNING) << "Error unlocking profile " << profile;
135 }
136 return truncated;
137}
138
Calin Juravle114f0812017-03-08 19:05:07 -0800139// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800140// The location is the profile name for primary apks or the dex path for secondary dex files.
141static bool clear_reference_profile(const std::string& package_name, const std::string& location,
142 bool is_secondary_dex) {
143 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700144}
145
Calin Juravle114f0812017-03-08 19:05:07 -0800146// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800147// The location is the profile name for primary apks or the dex path for secondary dex files.
148static bool clear_current_profile(const std::string& package_name, const std::string& location,
149 userid_t user, bool is_secondary_dex) {
150 return clear_profile(create_current_profile_path(user, package_name, location,
151 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 primary apk of the given package.
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.
156bool clear_primary_reference_profile(const std::string& package_name,
157 const std::string& location) {
158 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800159}
160
161// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800162// The location is the profile name for primary apks or the dex path for secondary dex files.
163bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700164 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800165 // 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 -0700166 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
167 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800168 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700169 }
170 return success;
171}
172
Calin Juravle114f0812017-03-08 19:05:07 -0800173// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800174bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
175 userid_t user) {
176 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800177}
178
Jeff Sharkey90aff262016-12-12 14:28:24 -0700179static int split_count(const char *str)
180{
181 char *ctx;
182 int count = 0;
183 char buf[kPropertyValueMax];
184
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600185 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700186 char *pBuf = buf;
187
188 while(strtok_r(pBuf, " ", &ctx) != NULL) {
189 count++;
190 pBuf = NULL;
191 }
192
193 return count;
194}
195
196static int split(char *buf, const char **argv)
197{
198 char *ctx;
199 int count = 0;
200 char *tok;
201 char *pBuf = buf;
202
203 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
204 argv[count++] = tok;
205 pBuf = NULL;
206 }
207
208 return count;
209}
210
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700211static const char* get_location_from_path(const char* path) {
212 static constexpr char kLocationSeparator = '/';
213 const char *location = strrchr(path, kLocationSeparator);
214 if (location == NULL) {
215 return path;
216 } else {
217 // Skip the separator character.
218 return location + 1;
219 }
220}
221
Jeff Sharkey90aff262016-12-12 14:28:24 -0700222static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
223 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100224 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700225 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
David Brazdil52249162018-02-12 18:04:59 -0800226 const char* class_loader_context, int target_sdk_version, bool enable_hidden_api_checks) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700227 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
228
229 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
230 ALOGE("Instruction set %s longer than max length of %d",
231 instruction_set, MAX_INSTRUCTION_SET_LEN);
232 return;
233 }
234
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700235 // Get the relative path to the input file.
236 const char* relative_input_file_name = get_location_from_path(input_file_name);
237
Jeff Sharkey90aff262016-12-12 14:28:24 -0700238 char dex2oat_Xms_flag[kPropertyValueMax];
239 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
240
241 char dex2oat_Xmx_flag[kPropertyValueMax];
242 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
243
244 char dex2oat_threads_buf[kPropertyValueMax];
245 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
246 ? "dalvik.vm.dex2oat-threads"
247 : "dalvik.vm.boot-dex2oat-threads",
248 dex2oat_threads_buf,
249 NULL) > 0;
250 char dex2oat_threads_arg[kPropertyValueMax + 2];
251 if (have_dex2oat_threads_flag) {
252 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
253 }
254
255 char dex2oat_isa_features_key[kPropertyKeyMax];
256 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
257 char dex2oat_isa_features[kPropertyValueMax];
258 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
259 dex2oat_isa_features, NULL) > 0;
260
261 char dex2oat_isa_variant_key[kPropertyKeyMax];
262 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
263 char dex2oat_isa_variant[kPropertyValueMax];
264 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
265 dex2oat_isa_variant, NULL) > 0;
266
267 const char *dex2oat_norelocation = "-Xnorelocate";
268 bool have_dex2oat_relocation_skip_flag = false;
269
270 char dex2oat_flags[kPropertyValueMax];
271 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
272 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
273 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
274
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100275 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700276 char vold_decrypt[kPropertyValueMax];
277 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
278 bool skip_compilation = (have_vold_decrypt &&
279 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
280 (strcmp(vold_decrypt, "1") == 0)));
281
282 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
283
284 char app_image_format[kPropertyValueMax];
285 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
286 bool have_app_image_format =
287 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
288 if (have_app_image_format) {
289 sprintf(image_format_arg, "--image-format=%s", app_image_format);
290 }
291
292 char dex2oat_large_app_threshold[kPropertyValueMax];
293 bool have_dex2oat_large_app_threshold =
294 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
295 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
296 if (have_dex2oat_large_app_threshold) {
297 sprintf(dex2oat_large_app_threshold_arg,
298 "--very-large-app-threshold=%s",
299 dex2oat_large_app_threshold);
300 }
301
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700302 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700303 const char* dex2oat_bin = "/system/bin/dex2oat";
304 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700305 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700306 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
307 dex2oat_bin = kDex2oatDebugPath;
308 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700309
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700310 bool generate_minidebug_info = kEnableMinidebugInfo &&
311 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
312 kMinidebugInfoSystemPropertyDefault);
313
Jeff Sharkey90aff262016-12-12 14:28:24 -0700314 static const char* RUNTIME_ARG = "--runtime-arg";
315
316 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
317
George Burgess IV36cebe772017-01-25 11:52:01 -0800318 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
319 // use arraysize instead.
320 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
321 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
322 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
323 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
324 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
325 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
326 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
327 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
328 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
329 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
330 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
331 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700332 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800333 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700334 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800335 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700336 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
David Brazdil570d3982018-01-16 20:15:43 +0000337 char target_sdk_version_arg[arraysize("-Xtarget-sdk-version:") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700338 char class_loader_context_arg[class_loader_context_size];
339 if (class_loader_context != nullptr) {
340 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
341 class_loader_context);
342 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700343
344 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700345 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700346 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
347 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
348 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
349 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
350 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
351 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
352 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
353 if (swap_fd >= 0) {
354 have_dex2oat_swap_fd = true;
355 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
356 }
357 if (image_fd >= 0) {
358 have_dex2oat_image_fd = true;
359 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
360 }
361
362 if (have_dex2oat_Xms_flag) {
363 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
364 }
365 if (have_dex2oat_Xmx_flag) {
366 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
367 }
David Brazdil570d3982018-01-16 20:15:43 +0000368 sprintf(target_sdk_version_arg, "-Xtarget-sdk-version:%d", target_sdk_version);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700369
370 // Compute compiler filter.
371
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100372 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700373 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600374 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
375 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700376 have_dex2oat_compiler_filter_flag = true;
377 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100378 } else if (compiler_filter != nullptr) {
379 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700380 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100381 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
382 have_dex2oat_compiler_filter_flag = true;
383 } else {
384 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
385 compiler_filter,
386 kPropertyValueMax);
387 }
388 }
389
390 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700391 char dex2oat_compiler_filter_flag[kPropertyValueMax];
392 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
393 dex2oat_compiler_filter_flag, NULL) > 0;
394 if (have_dex2oat_compiler_filter_flag) {
395 sprintf(dex2oat_compiler_filter_arg,
396 "--compiler-filter=%s",
397 dex2oat_compiler_filter_flag);
398 }
399 }
400
401 // Check whether all apps should be compiled debuggable.
402 if (!debuggable) {
403 char prop_buf[kPropertyValueMax];
404 debuggable =
405 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
406 (prop_buf[0] == '1');
407 }
408 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
409 if (profile_fd != -1) {
410 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
411 }
412
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700413 // Get the directory of the apk to pass as a base classpath directory.
414 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
415 std::string apk_dir(input_file_name);
416 unsigned long dir_index = apk_dir.rfind('/');
417 bool has_base_dir = dir_index != std::string::npos;
418 if (has_base_dir) {
419 apk_dir = apk_dir.substr(0, dir_index);
420 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
421 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700422
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700423
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700424 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700425
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800426 // Disable cdex if update input vdex is true since this combination of options is not
427 // supported.
Mathieu Chartier1fb463e2018-01-09 15:16:10 -0800428 // Disable cdex for non-background compiles since we don't want to regress app install until
429 // there are enough benefits to justify the tradeoff.
430 const bool disable_cdex = !background_job_compile || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800431
Jeff Sharkey90aff262016-12-12 14:28:24 -0700432 const char* argv[9 // program name, mandatory arguments and the final NULL
433 + (have_dex2oat_isa_variant ? 1 : 0)
434 + (have_dex2oat_isa_features ? 1 : 0)
435 + (have_dex2oat_Xms_flag ? 2 : 0)
436 + (have_dex2oat_Xmx_flag ? 2 : 0)
437 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
438 + (have_dex2oat_threads_flag ? 1 : 0)
439 + (have_dex2oat_swap_fd ? 1 : 0)
440 + (have_dex2oat_image_fd ? 1 : 0)
441 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
442 + (generate_debug_info ? 1 : 0)
443 + (debuggable ? 1 : 0)
444 + (have_app_image_format ? 1 : 0)
445 + dex2oat_flags_count
446 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700447 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700448 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700449 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800450 + (disable_cdex ? 1 : 0)
David Brazdil570d3982018-01-16 20:15:43 +0000451 + (generate_minidebug_info ? 1 : 0)
David Brazdil7fcbb812018-01-17 17:05:40 +0000452 + (target_sdk_version != 0 ? 2 : 0)
David Brazdil52249162018-02-12 18:04:59 -0800453 + (enable_hidden_api_checks ? 2 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700454 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700455 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700456 argv[i++] = zip_fd_arg;
457 argv[i++] = zip_location_arg;
458 argv[i++] = input_vdex_fd_arg;
459 argv[i++] = output_vdex_fd_arg;
460 argv[i++] = oat_fd_arg;
461 argv[i++] = oat_location_arg;
462 argv[i++] = instruction_set_arg;
463 if (have_dex2oat_isa_variant) {
464 argv[i++] = instruction_set_variant_arg;
465 }
466 if (have_dex2oat_isa_features) {
467 argv[i++] = instruction_set_features_arg;
468 }
469 if (have_dex2oat_Xms_flag) {
470 argv[i++] = RUNTIME_ARG;
471 argv[i++] = dex2oat_Xms_arg;
472 }
473 if (have_dex2oat_Xmx_flag) {
474 argv[i++] = RUNTIME_ARG;
475 argv[i++] = dex2oat_Xmx_arg;
476 }
477 if (have_dex2oat_compiler_filter_flag) {
478 argv[i++] = dex2oat_compiler_filter_arg;
479 }
480 if (have_dex2oat_threads_flag) {
481 argv[i++] = dex2oat_threads_arg;
482 }
483 if (have_dex2oat_swap_fd) {
484 argv[i++] = dex2oat_swap_fd;
485 }
486 if (have_dex2oat_image_fd) {
487 argv[i++] = dex2oat_image_fd;
488 }
489 if (generate_debug_info) {
490 argv[i++] = "--generate-debug-info";
491 }
492 if (debuggable) {
493 argv[i++] = "--debuggable";
494 }
495 if (have_app_image_format) {
496 argv[i++] = image_format_arg;
497 }
498 if (have_dex2oat_large_app_threshold) {
499 argv[i++] = dex2oat_large_app_threshold_arg;
500 }
501 if (dex2oat_flags_count) {
502 i += split(dex2oat_flags, argv + i);
503 }
504 if (have_dex2oat_relocation_skip_flag) {
505 argv[i++] = RUNTIME_ARG;
506 argv[i++] = dex2oat_norelocation;
507 }
508 if (profile_fd != -1) {
509 argv[i++] = profile_arg;
510 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700511 if (has_base_dir) {
512 argv[i++] = base_dir;
513 }
Calin Juravle52c45822017-07-13 22:50:21 -0700514 if (class_loader_context != nullptr) {
515 argv[i++] = class_loader_context_arg;
516 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700517 if (generate_minidebug_info) {
518 argv[i++] = kMinidebugDex2oatFlag;
519 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800520 if (disable_cdex) {
521 argv[i++] = kDisableCompactDexFlag;
522 }
David Brazdil570d3982018-01-16 20:15:43 +0000523 if (target_sdk_version != 0) {
524 argv[i++] = RUNTIME_ARG;
525 argv[i++] = target_sdk_version_arg;
526 }
David Brazdil52249162018-02-12 18:04:59 -0800527 if (enable_hidden_api_checks) {
David Brazdil7fcbb812018-01-17 17:05:40 +0000528 argv[i++] = RUNTIME_ARG;
David Brazdil52249162018-02-12 18:04:59 -0800529 argv[i++] = "-Xhidden-api-checks";
David Brazdil7fcbb812018-01-17 17:05:40 +0000530 }
Calin Juravle52c45822017-07-13 22:50:21 -0700531
Jeff Sharkey90aff262016-12-12 14:28:24 -0700532 // Do not add after dex2oat_flags, they should override others for debugging.
533 argv[i] = NULL;
534
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700535 execv(dex2oat_bin, (char * const *)argv);
536 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700537}
538
539/*
540 * Whether dexopt should use a swap file when compiling an APK.
541 *
542 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
543 * itself, anyways).
544 *
545 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
546 *
547 * Otherwise, return true if this is a low-mem device.
548 *
549 * Otherwise, return default value.
550 */
551static bool kAlwaysProvideSwapFile = false;
552static bool kDefaultProvideSwapFile = true;
553
554static bool ShouldUseSwapFileForDexopt() {
555 if (kAlwaysProvideSwapFile) {
556 return true;
557 }
558
559 // Check the "override" property. If it exists, return value == "true".
560 char dex2oat_prop_buf[kPropertyValueMax];
561 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
562 if (strcmp(dex2oat_prop_buf, "true") == 0) {
563 return true;
564 } else {
565 return false;
566 }
567 }
568
569 // Shortcut for default value. This is an implementation optimization for the process sketched
570 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
571 // as low-mem is never returning false. The compiler will optimize this away if it can.
572 if (kDefaultProvideSwapFile) {
573 return true;
574 }
575
576 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
577 if (is_low_mem) {
578 return true;
579 }
580
581 // Default value must be false here.
582 return kDefaultProvideSwapFile;
583}
584
Richard Uhler76cc0272016-12-08 10:46:35 +0000585static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700586 if (set_to_bg) {
587 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
588 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
589 exit(70);
590 }
591 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
592 ALOGE("setpriority failed: %s\n", strerror(errno));
593 exit(71);
594 }
595 }
596}
597
Calin Juravle29591732017-11-20 17:46:19 -0800598static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
599 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800600 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800601 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800602 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800603 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800604 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605 }
Calin Juravle114f0812017-03-08 19:05:07 -0800606 // Profiles should belong to the app; make sure of that by giving ownership to
607 // the app uid. If we cannot do that, there's no point in returning the fd
608 // since dex2oat/profman will fail with SElinux denials.
609 if (fchown(fd.get(), uid, uid) < 0) {
610 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800611 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800612 }
Calin Juravle29591732017-11-20 17:46:19 -0800613 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800614}
615
Calin Juravle29591732017-11-20 17:46:19 -0800616static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800617 // Do not follow symlinks when opening a profile:
618 // - primary profiles should not contain symlinks in their paths
619 // - secondary dex paths should have been already resolved and validated
620 flags |= O_NOFOLLOW;
621
Calin Juravle29591732017-11-20 17:46:19 -0800622 // Check if we need to create the profile
623 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
624 unique_fd fd;
625 if ((flags & O_CREAT) != 0) {
626 fd = create_profile(uid, profile, flags);
627 } else {
628 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
629 }
630
Calin Juravle114f0812017-03-08 19:05:07 -0800631 if (fd.get() < 0) {
632 if (errno != ENOENT) {
633 // Profiles might be missing for various reasons. For example, in a
634 // multi-user environment, the profile directory for one user can be created
635 // after we start a merge. In this case the current profile for that user
636 // will not be found.
637 // Also, the secondary dex profiles might be deleted by the app at any time,
638 // so we can't we need to prepare if they are missing.
639 PLOG(ERROR) << "Failed to open profile " << profile;
640 }
641 return invalid_unique_fd();
642 }
643
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644 return fd;
645}
646
Calin Juravle824a64d2018-01-18 20:23:17 -0800647static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
648 const std::string& location, bool is_secondary_dex) {
649 std::string profile = create_current_profile_path(user, package_name, location,
650 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800651 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800652}
653
Calin Juravle824a64d2018-01-18 20:23:17 -0800654static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
655 const std::string& location, bool read_write, bool is_secondary_dex) {
656 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800657 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
658}
659
660static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800661 const std::string& location) {
662 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800663 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800664}
665
Calin Juravle824a64d2018-01-18 20:23:17 -0800666static void open_profile_files(uid_t uid, const std::string& package_name,
667 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800668 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700669 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800670 *reference_profile_fd = open_reference_profile(uid, package_name, location,
671 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700672
Calin Juravle114f0812017-03-08 19:05:07 -0800673 // For secondary dex files, we don't really need the user but we use it for sanity checks.
674 // Note: the user owning the dex file should be the current user.
675 std::vector<userid_t> users;
676 if (is_secondary_dex){
677 users.push_back(multiuser_get_user_id(uid));
678 } else {
679 users = get_known_users(/*volume_uuid*/ nullptr);
680 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700681 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800682 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
683 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700684 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800685 if (profile_fd.get() >= 0) {
686 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700687 }
688 }
689}
690
691static void drop_capabilities(uid_t uid) {
692 if (setgid(uid) != 0) {
693 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
694 exit(64);
695 }
696 if (setuid(uid) != 0) {
697 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
698 exit(65);
699 }
700 // drop capabilities
701 struct __user_cap_header_struct capheader;
702 struct __user_cap_data_struct capdata[2];
703 memset(&capheader, 0, sizeof(capheader));
704 memset(&capdata, 0, sizeof(capdata));
705 capheader.version = _LINUX_CAPABILITY_VERSION_3;
706 if (capset(&capheader, &capdata[0]) < 0) {
707 ALOGE("capset failed: %s\n", strerror(errno));
708 exit(66);
709 }
710}
711
712static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
713static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
714static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
715static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
716static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
717
Calin Juravlef63d4792018-01-30 17:43:34 +0000718static void run_profman(const std::vector<unique_fd>& profile_fds,
719 const unique_fd& reference_profile_fd,
720 const std::vector<unique_fd>* apk_fds,
721 bool copy_and_update) {
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700722 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700723
Calin Juravlef63d4792018-01-30 17:43:34 +0000724 if (copy_and_update) {
725 CHECK_EQ(1u, profile_fds.size());
726 CHECK(apk_fds != nullptr);
727 CHECK_EQ(1u, apk_fds->size());
728 }
729 std::vector<std::string> profile_args(profile_fds.size());
730 for (size_t k = 0; k < profile_fds.size(); k++) {
731 profile_args[k] = "--profile-file-fd=" + std::to_string(profile_fds[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700732 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800733 std::string reference_profile_arg = "--reference-profile-file-fd="
734 + std::to_string(reference_profile_fd.get());
735
736 std::vector<std::string> apk_args;
737 if (apk_fds != nullptr) {
738 for (size_t k = 0; k < apk_fds->size(); k++) {
739 apk_args.push_back("--apk-fd=" + std::to_string((*apk_fds)[k].get()));
740 }
741 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742
743 // program name, reference profile fd, the final NULL and the profile fds
Calin Juravlef63d4792018-01-30 17:43:34 +0000744 const char* argv[3 + profile_args.size() + apk_args.size() + (copy_and_update ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700745 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700746 argv[i++] = profman_bin;
Calin Juravle0d0a4922018-01-23 19:54:11 -0800747 argv[i++] = reference_profile_arg.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700748 for (size_t k = 0; k < profile_args.size(); k++) {
749 argv[i++] = profile_args[k].c_str();
750 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800751 for (size_t k = 0; k < apk_args.size(); k++) {
752 argv[i++] = apk_args[k].c_str();
753 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000754 if (copy_and_update) {
755 argv[i++] = "--copy-and-update-profile-key";
756 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700757 // Do not add after dex2oat_flags, they should override others for debugging.
758 argv[i] = NULL;
759
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700760 execv(profman_bin, (char * const *)argv);
761 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700762 exit(68); /* only get here on exec failure */
763}
764
Calin Juravlef63d4792018-01-30 17:43:34 +0000765
766static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
767 const unique_fd& reference_profile_fd,
768 const std::vector<unique_fd>* apk_fds = nullptr) {
769 run_profman(profiles_fd, reference_profile_fd, apk_fds, /*copy_and_update*/false);
770}
771
772
773static void run_profman_copy_and_update(unique_fd&& profile_fd,
774 unique_fd&& reference_profile_fd,
775 unique_fd&& apk_fd) {
776 std::vector<unique_fd> profiles_fd;
777 profiles_fd.push_back(std::move(profile_fd));
778 std::vector<unique_fd> apk_fds;
779 apk_fds.push_back(std::move(apk_fd));
780
781 run_profman(profiles_fd, reference_profile_fd, &apk_fds, /*copy_and_update*/true);
782}
783
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800785// The location is the package name for primary apks or the dex path for secondary dex files.
786// Returns true if there is enough information in the current profiles that makes it
787// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700788// If the return value is true all the current profiles would have been merged into
789// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800790static bool analyze_profiles(uid_t uid, const std::string& package_name,
791 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800792 std::vector<unique_fd> profiles_fd;
793 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800794 open_profile_files(uid, package_name, location, is_secondary_dex,
795 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800796 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700797 // Skip profile guided compilation because no profiles were found.
798 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700799 return false;
800 }
801
Jeff Sharkey90aff262016-12-12 14:28:24 -0700802 pid_t pid = fork();
803 if (pid == 0) {
804 /* child -- drop privileges before continuing */
805 drop_capabilities(uid);
806 run_profman_merge(profiles_fd, reference_profile_fd);
807 exit(68); /* only get here on exec failure */
808 }
809 /* parent */
810 int return_code = wait_child(pid);
811 bool need_to_compile = false;
812 bool should_clear_current_profiles = false;
813 bool should_clear_reference_profile = false;
814 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800815 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816 } else {
817 return_code = WEXITSTATUS(return_code);
818 switch (return_code) {
819 case PROFMAN_BIN_RETURN_CODE_COMPILE:
820 need_to_compile = true;
821 should_clear_current_profiles = true;
822 should_clear_reference_profile = false;
823 break;
824 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
825 need_to_compile = false;
826 should_clear_current_profiles = false;
827 should_clear_reference_profile = false;
828 break;
829 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800830 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700831 need_to_compile = false;
832 should_clear_current_profiles = true;
833 should_clear_reference_profile = true;
834 break;
835 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
836 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
837 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800838 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700839 need_to_compile = false;
840 should_clear_current_profiles = false;
841 should_clear_reference_profile = false;
842 break;
843 default:
844 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800845 LOG(WARNING) << "Unknown error code while processing profiles for location "
846 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 need_to_compile = false;
848 should_clear_current_profiles = true;
849 should_clear_reference_profile = true;
850 break;
851 }
852 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800853
Jeff Sharkey90aff262016-12-12 14:28:24 -0700854 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800855 if (is_secondary_dex) {
856 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800857 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
858 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800859 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800860 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800861 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862 }
863 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800864 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700865 }
866 return need_to_compile;
867}
868
Calin Juravle114f0812017-03-08 19:05:07 -0800869// Decides if profile guided compilation is needed or not based on existing profiles.
870// The analysis is done for the primary apks of the given package.
871// Returns true if there is enough information in the current profiles that makes it
872// worth to recompile the package.
873// If the return value is true all the current profiles would have been merged into
874// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800875bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
876 const std::string& profile_name) {
877 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800878}
879
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800880static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
881 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800883 const std::vector<unique_fd>& apk_fds,
884 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700885 std::vector<std::string> profman_args;
886 static const char* PROFMAN_BIN = "/system/bin/profman";
887 profman_args.push_back(PROFMAN_BIN);
888 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800889 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700890 if (reference_profile_fd != -1) {
891 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800892 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700893 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800894 for (size_t i = 0; i < profile_fds.size(); i++) {
895 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 }
897 for (const std::string& dex_location : dex_locations) {
898 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
899 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800900 for (size_t i = 0; i < apk_fds.size(); i++) {
901 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 }
903 const char **argv = new const char*[profman_args.size() + 1];
904 size_t i = 0;
905 for (const std::string& profman_arg : profman_args) {
906 argv[i++] = profman_arg.c_str();
907 }
908 argv[i] = NULL;
909
910 execv(PROFMAN_BIN, (char * const *)argv);
911 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
912 exit(68); /* only get here on exec failure */
913}
914
Calin Juravle408cd4a2018-01-20 23:34:18 -0800915bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
916 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800917 std::vector<unique_fd> profile_fds;
918 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800919 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
920 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700921
Calin Juravle408cd4a2018-01-20 23:34:18 -0800922 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800923 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700924
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800925 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700926 const bool has_profiles = !profile_fds.empty();
927
928 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800929 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700930 return false;
931 }
932
Calin Juravle114f0812017-03-08 19:05:07 -0800933 unique_fd output_fd(open(out_file_name.c_str(),
934 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800936 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937 return false;
938 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800939
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800941 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800942 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
943 if (apk_fd == -1) {
944 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
945 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700946 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800947 dex_locations.push_back(get_location_from_path(code_path.c_str()));
948 apk_fds.push_back(std::move(apk_fd));
949
Jeff Sharkey90aff262016-12-12 14:28:24 -0700950
951 pid_t pid = fork();
952 if (pid == 0) {
953 /* child -- drop privileges before continuing */
954 drop_capabilities(uid);
955 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
956 apk_fds, output_fd);
957 exit(68); /* only get here on exec failure */
958 }
959 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700960 int return_code = wait_child(pid);
961 if (!WIFEXITED(return_code)) {
962 LOG(WARNING) << "profman failed for package " << pkgname << ": "
963 << return_code;
964 return false;
965 }
966 return true;
967}
968
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700969bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800970 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700971 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
972 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800973 package_name,
974 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700975 /*read_write*/ true,
976 /*secondary*/ false));
977 if (in_fd.get() < 0) {
978 PLOG(WARNING) << "Could not open profile " << system_profile;
979 return false;
980 }
981 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800982 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700983 return false;
984 }
985
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700986 // As a security measure we want to write the profile information with the reduced capabilities
987 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700988 pid_t pid = fork();
989 if (pid == 0) {
990 /* child -- drop privileges before continuing */
991 drop_capabilities(packageUid);
992
993 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
994 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800995 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700996 }
997 // This implies that the app owning this profile is running
998 // (and has acquired the lock).
999 //
1000 // The app never acquires the lock for the reference profiles of primary apks.
1001 // Only dex2oat from installd will do that. Since installd is single threaded
1002 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001003 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001004 return false;
1005 }
1006
1007 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1008 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001009 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001010 }
1011
1012 // Copy over data.
1013 static constexpr size_t kBufferSize = 4 * 1024;
1014 char buffer[kBufferSize];
1015 while (true) {
1016 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1017 if (bytes == 0) {
1018 break;
1019 }
1020 write(out_fd.get(), buffer, bytes);
1021 }
1022 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001023 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001024 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001025 // Use _exit since we don't want to run the global destructors in the child.
1026 // b/62597429
1027 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001028 }
1029 /* parent */
1030 int return_code = wait_child(pid);
1031 return return_code == 0;
1032}
1033
Jeff Sharkey90aff262016-12-12 14:28:24 -07001034static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1035 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1036 if (EndsWith(oat_path, ".dex")) {
1037 std::string new_path = oat_path;
1038 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001039 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001040 return new_path;
1041 }
1042
1043 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1044 // case (where the base name will have an extension for the B artifact).
1045 size_t odex_pos = oat_path.rfind(".odex");
1046 if (odex_pos != std::string::npos) {
1047 std::string new_path = oat_path;
1048 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1049 CHECK_NE(new_path.find(new_ext), std::string::npos);
1050 return new_path;
1051 }
1052
1053 // Don't know how to handle this.
1054 return "";
1055}
1056
1057// Translate the given oat path to an art (app image) path. An empty string
1058// denotes an error.
1059static std::string create_image_filename(const std::string& oat_path) {
1060 return replace_file_extension(oat_path, ".art");
1061}
1062
1063// Translate the given oat path to a vdex path. An empty string denotes an error.
1064static std::string create_vdex_filename(const std::string& oat_path) {
1065 return replace_file_extension(oat_path, ".vdex");
1066}
1067
Jeff Sharkey90aff262016-12-12 14:28:24 -07001068static int open_output_file(const char* file_name, bool recreate, int permissions) {
1069 int flags = O_RDWR | O_CREAT;
1070 if (recreate) {
1071 if (unlink(file_name) < 0) {
1072 if (errno != ENOENT) {
1073 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1074 }
1075 }
1076 flags |= O_EXCL;
1077 }
1078 return open(file_name, flags, permissions);
1079}
1080
Calin Juravle2289c0a2017-02-15 12:44:14 -08001081static bool set_permissions_and_ownership(
1082 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1083 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1084 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085 if (fchmod(fd,
1086 S_IRUSR|S_IWUSR|S_IRGRP |
1087 (is_public ? S_IROTH : 0)) < 0) {
1088 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1089 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001090 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001091 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1092 return false;
1093 }
1094 return true;
1095}
1096
1097static bool IsOutputDalvikCache(const char* oat_dir) {
1098 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1099 // into '!'. Play it safe by handling it both.
1100 // TODO: ensure we never get null.
1101 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1102 return oat_dir == nullptr || oat_dir[0] == '!';
1103}
1104
Calin Juravled23dee72017-07-06 16:29:11 -07001105// Best-effort check whether we can fit the the path into our buffers.
1106// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1107// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1108// extension to the cache path (5 bytes).
1109// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1110static bool validate_dex_path_size(const std::string& dex_path) {
1111 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1112 LOG(ERROR) << "dex_path too long: " << dex_path;
1113 return false;
1114 }
1115 return true;
1116}
1117
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001119 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001120 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 return false;
1122 }
1123
1124 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001125 // Oat dirs for secondary dex files are already validated.
1126 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1128 return false;
1129 }
1130 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1131 return false;
1132 }
1133 } else {
1134 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1135 return false;
1136 }
1137 }
1138 return true;
1139}
1140
1141// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1142// on destruction. It will also run the given cleanup (unless told not to) after closing.
1143//
1144// Usage example:
1145//
Calin Juravle7a570e82017-01-14 16:23:30 -08001146// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001147// [name]() {
1148// unlink(name.c_str());
1149// });
1150// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1151// wrapper if captured as a reference.
1152//
1153// if (file.get() == -1) {
1154// // Error opening...
1155// }
1156//
1157// ...
1158// if (error) {
1159// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1160// // and delete the file (after the fd is closed).
1161// return -1;
1162// }
1163//
1164// (Success case)
1165// file.SetCleanup(false);
1166// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1167// // (leaving the file around; after the fd is closed).
1168//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169class Dex2oatFileWrapper {
1170 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001171 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001172 }
1173
Calin Juravle7a570e82017-01-14 16:23:30 -08001174 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1175 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1176
1177 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1178 value_ = other.value_;
1179 cleanup_ = other.cleanup_;
1180 do_cleanup_ = other.do_cleanup_;
1181 auto_close_ = other.auto_close_;
1182 other.release();
1183 }
1184
1185 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1186 value_ = other.value_;
1187 cleanup_ = other.cleanup_;
1188 do_cleanup_ = other.do_cleanup_;
1189 auto_close_ = other.auto_close_;
1190 other.release();
1191 return *this;
1192 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001193
1194 ~Dex2oatFileWrapper() {
1195 reset(-1);
1196 }
1197
1198 int get() {
1199 return value_;
1200 }
1201
1202 void SetCleanup(bool cleanup) {
1203 do_cleanup_ = cleanup;
1204 }
1205
1206 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001208 close(value_);
1209 }
1210 if (do_cleanup_ && cleanup_ != nullptr) {
1211 cleanup_();
1212 }
1213
1214 value_ = new_value;
1215 }
1216
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 void reset(int new_value, std::function<void ()> new_cleanup) {
1218 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001219 close(value_);
1220 }
1221 if (do_cleanup_ && cleanup_ != nullptr) {
1222 cleanup_();
1223 }
1224
1225 value_ = new_value;
1226 cleanup_ = new_cleanup;
1227 }
1228
Calin Juravle7a570e82017-01-14 16:23:30 -08001229 void DisableAutoClose() {
1230 auto_close_ = false;
1231 }
1232
Jeff Sharkey90aff262016-12-12 14:28:24 -07001233 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001234 void release() {
1235 value_ = -1;
1236 do_cleanup_ = false;
1237 cleanup_ = nullptr;
1238 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001239 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001240 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001241 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001242 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001243};
1244
Calin Juravle7a570e82017-01-14 16:23:30 -08001245// (re)Creates the app image if needed.
1246Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001247 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001248
1249 // We don't create an image for secondary dex files.
1250 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001251 return Dex2oatFileWrapper();
1252 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001253
Calin Juravle7a570e82017-01-14 16:23:30 -08001254 const std::string image_path = create_image_filename(out_oat_path);
1255 if (image_path.empty()) {
1256 // Happens when the out_oat_path has an unknown extension.
1257 return Dex2oatFileWrapper();
1258 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001259
1260 // Use app images only if it is enabled (by a set image format) and we are compiling
1261 // profile-guided (so the app image doesn't conservatively contain all classes).
1262 if (!profile_guided) {
1263 // In case there is a stale image, remove it now. Ignore any error.
1264 unlink(image_path.c_str());
1265 return Dex2oatFileWrapper();
1266 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001267 char app_image_format[kPropertyValueMax];
1268 bool have_app_image_format =
1269 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1270 if (!have_app_image_format) {
1271 return Dex2oatFileWrapper();
1272 }
1273 // Recreate is true since we do not want to modify a mapped image. If the app is
1274 // already running and we modify the image file, it can cause crashes (b/27493510).
1275 Dex2oatFileWrapper wrapper_fd(
1276 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1277 [image_path]() { unlink(image_path.c_str()); });
1278 if (wrapper_fd.get() < 0) {
1279 // Could not create application image file. Go on since we can compile without it.
1280 LOG(ERROR) << "installd could not create '" << image_path
1281 << "' for image file during dexopt";
1282 // If we have a valid image file path but no image fd, explicitly erase the image file.
1283 if (unlink(image_path.c_str()) < 0) {
1284 if (errno != ENOENT) {
1285 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1286 }
1287 }
1288 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001289 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001290 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1291 wrapper_fd.reset(-1);
1292 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001293
Calin Juravle7a570e82017-01-14 16:23:30 -08001294 return wrapper_fd;
1295}
1296
1297// Creates the dexopt swap file if necessary and return its fd.
1298// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001299unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001300 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001301 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001302 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001303 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001304 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001305 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001306 if (swap_fd.get() < 0) {
1307 // Could not create swap file. Optimistically go on and hope that we can compile
1308 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001309 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001310 } else {
1311 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001312 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001313 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1314 }
1315 }
1316 return swap_fd;
1317}
1318
1319// Opens the reference profiles if needed.
1320// 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 -08001321Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001322 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001323 bool is_public, int uid, bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001324 // Public apps should not be compiled with profile information ever. Same goes for the special
1325 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001326 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001327 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001328 }
Calin Juravle114f0812017-03-08 19:05:07 -08001329
1330 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001331 std::string location;
1332 if (is_secondary_dex) {
1333 location = dex_path;
1334 } else {
1335 if (profile_name == nullptr) {
1336 // This path is taken for system server re-compilation lunched from ZygoteInit.
1337 return Dex2oatFileWrapper();
1338 } else {
1339 location = profile_name;
1340 }
1341 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001342 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1343 is_secondary_dex);
1344 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1345 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001346 };
1347 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001348}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001349
Calin Juravle7a570e82017-01-14 16:23:30 -08001350// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1351// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001352bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001353 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001354 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001355 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1356 CHECK(in_vdex_wrapper_fd != nullptr);
1357 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001358 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1359 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001360 char in_odex_path[PKG_PATH_MAX];
1361 int dexopt_action = abs(dexopt_needed);
1362 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001363 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001364
1365 // Infer the name of the output VDEX.
1366 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1367 if (out_vdex_path_str.empty()) {
1368 return false;
1369 }
1370
1371 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001372 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001373 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1374 const char* path = nullptr;
1375 if (is_odex_location) {
1376 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1377 path = in_odex_path;
1378 } else {
1379 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001380 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001381 }
1382 } else {
1383 path = out_oat_path;
1384 }
1385 in_vdex_path_str = create_vdex_filename(path);
1386 if (in_vdex_path_str.empty()) {
1387 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001388 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001389 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001390 // We can update in place when all these conditions are met:
1391 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1392 // on /system typically cannot be updated in place).
1393 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1394 // cannot be currently used by a running process.
1395 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1396 // different vdex files to operate.
1397 update_vdex_in_place =
1398 (in_vdex_path_str == out_vdex_path_str) &&
1399 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1400 !profile_guided;
1401 if (update_vdex_in_place) {
1402 // Open the file read-write to be able to update it.
1403 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1404 if (in_vdex_wrapper_fd->get() == -1) {
1405 // If we failed to open the file, we cannot update it in place.
1406 update_vdex_in_place = false;
1407 }
1408 } else {
1409 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1410 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001411 }
1412
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001413 // If we are updating the vdex in place, we do not need to recreate a vdex,
1414 // and can use the same existing one.
1415 if (update_vdex_in_place) {
1416 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1417 // have bogus stale vdex files.
1418 out_vdex_wrapper_fd->reset(
1419 in_vdex_wrapper_fd->get(),
1420 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1421 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1422 // wrapper).
1423 in_vdex_wrapper_fd->DisableAutoClose();
1424 } else {
1425 out_vdex_wrapper_fd->reset(
1426 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1427 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1428 if (out_vdex_wrapper_fd->get() < 0) {
1429 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1430 return false;
1431 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001432 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001433 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001434 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001435 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1436 return false;
1437 }
1438
1439 // If we got here we successfully opened the vdex files.
1440 return true;
1441}
1442
1443// Opens the output oat file for the given apk.
1444// If successful it stores the output path into out_oat_path and returns true.
1445Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001446 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1447 char* out_oat_path) {
1448 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001449 return Dex2oatFileWrapper();
1450 }
1451 const std::string out_oat_path_str(out_oat_path);
1452 Dex2oatFileWrapper wrapper_fd(
1453 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1454 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1455 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001456 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001457 } else if (!set_permissions_and_ownership(
1458 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001459 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1460 wrapper_fd.reset(-1);
1461 }
1462 return wrapper_fd;
1463}
1464
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001465// Creates RDONLY fds for oat and vdex files, if exist.
1466// Returns false if it fails to create oat out path for the given apk path.
1467// Note that the method returns true even if the files could not be opened.
1468bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1469 const std::string& oat_dir,
1470 const std::string& instruction_set,
1471 bool is_secondary_dex,
1472 unique_fd* oat_file_fd,
1473 unique_fd* vdex_file_fd) {
1474 char oat_path[PKG_PATH_MAX];
1475 if (!create_oat_out_path(apk_path.c_str(),
1476 instruction_set.c_str(),
1477 oat_dir.c_str(),
1478 is_secondary_dex,
1479 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001480 LOG(ERROR) << "Could not create oat out path for "
1481 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001482 return false;
1483 }
1484 oat_file_fd->reset(open(oat_path, O_RDONLY));
1485 if (oat_file_fd->get() < 0) {
1486 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1487 }
1488
1489 std::string vdex_filename = create_vdex_filename(oat_path);
1490 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1491 if (vdex_file_fd->get() < 0) {
1492 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1493 }
1494
1495 return true;
1496}
1497
Calin Juravle7a570e82017-01-14 16:23:30 -08001498// Updates the access times of out_oat_path based on those from apk_path.
1499void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1500 struct stat input_stat;
1501 memset(&input_stat, 0, sizeof(input_stat));
1502 if (stat(apk_path, &input_stat) != 0) {
1503 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1504 return;
1505 }
1506
1507 struct utimbuf ut;
1508 ut.actime = input_stat.st_atime;
1509 ut.modtime = input_stat.st_mtime;
1510 if (utime(out_oat_path, &ut) != 0) {
1511 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1512 }
1513}
1514
Calin Juravle80a21252017-01-17 14:43:25 -08001515// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001516// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1517// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1518// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001519static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1520 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1521 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001522 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001523 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001524 const char* dexoptanalyzer_bin =
1525 is_debug_runtime()
1526 ? "/system/bin/dexoptanalyzerd"
1527 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001528 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1529
Calin Juravled23dee72017-07-06 16:29:11 -07001530 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1531 LOG(ERROR) << "Instruction set " << instruction_set
1532 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001533 return;
1534 }
1535
Calin Juravled23dee72017-07-06 16:29:11 -07001536 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001537 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1538 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1539 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001540 std::string isa_arg = "--isa=" + instruction_set;
1541 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001542 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001543 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001544 std::string class_loader_context_arg = "--class-loader-context=";
1545 if (class_loader_context != nullptr) {
1546 class_loader_context_arg += class_loader_context;
1547 }
Calin Juravle80a21252017-01-17 14:43:25 -08001548
Calin Juravle80a21252017-01-17 14:43:25 -08001549 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001550 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001551 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001552 (vdex_fd >= 0 ? 1 : 0) +
1553 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001554 (downgrade ? 1 : 0) +
1555 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001556 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001557 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001558 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001559 argv[i++] = dex_file_arg.c_str();
1560 argv[i++] = isa_arg.c_str();
1561 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001562 if (oat_fd >= 0) {
1563 argv[i++] = oat_fd_arg.c_str();
1564 }
1565 if (vdex_fd >= 0) {
1566 argv[i++] = vdex_fd_arg.c_str();
1567 }
1568 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001569 if (profile_was_updated) {
1570 argv[i++] = assume_profile_changed;
1571 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001572 if (downgrade) {
1573 argv[i++] = downgrade_flag;
1574 }
Calin Juravle58cab072017-09-12 01:02:26 -07001575 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001576 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001577 }
Calin Juravle80a21252017-01-17 14:43:25 -08001578 argv[i] = NULL;
1579
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001580 execv(dexoptanalyzer_bin, (char * const *)argv);
1581 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001582}
1583
1584// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001585static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001586 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001587 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001588 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001589 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001590 return false;
1591 }
Calin Juravle114f0812017-03-08 19:05:07 -08001592 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001593
Calin Juravle80a21252017-01-17 14:43:25 -08001594 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001595 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1596 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001597 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001598 return false;
1599 }
1600
1601 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001602 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001603
Calin Juravle7d765462017-09-04 15:57:10 -07001604 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001605 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001606 return false;
1607 }
1608
1609 return true;
1610}
1611
Calin Juravle7d765462017-09-04 15:57:10 -07001612// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1613// secondary dex files. This return codes are returned by the child process created for
1614// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001615
Calin Juravle7d765462017-09-04 15:57:10 -07001616// The dexoptanalyzer was not invoked because of validation or IO errors.
1617static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1618// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1619static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1620
1621// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001622// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1623// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001624// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1625// of dexoptanalyzer.
1626static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001627 int* dexopt_needed_out) {
1628 // The result values are defined in dexoptanalyzer.
1629 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001630 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001631 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001632 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001633 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001634 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001635 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001636 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001637 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001638 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001639 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001640 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1641 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1642 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001643 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1644 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001645 << " : dexoptanalyzer result=" << result;
1646 return false;
Calin Juravle7d765462017-09-04 15:57:10 -07001647 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1648 // If the file does not exist there's no need for dexopt.
1649 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1650 return true;
1651 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1652 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001653 default:
Calin Juravle7d765462017-09-04 15:57:10 -07001654 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1655 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001656 return false;
1657 }
1658}
1659
Calin Juravle7d765462017-09-04 15:57:10 -07001660enum SecondaryDexAccess {
1661 kSecondaryDexAccessReadOk = 0,
1662 kSecondaryDexAccessDoesNotExist = 1,
1663 kSecondaryDexAccessPermissionError = 2,
1664 kSecondaryDexAccessIOError = 3
1665};
1666
1667static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1668 // Check if the path exists and can be read. If not, there's nothing to do.
1669 if (access(dex_path.c_str(), R_OK) == 0) {
1670 return kSecondaryDexAccessReadOk;
1671 } else {
1672 if (errno == ENOENT) {
1673 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1674 return kSecondaryDexAccessDoesNotExist;
1675 } else {
1676 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1677 return errno == EACCES
1678 ? kSecondaryDexAccessPermissionError
1679 : kSecondaryDexAccessIOError;
1680 }
1681 }
1682}
1683
1684static bool is_file_public(const std::string& filename) {
1685 struct stat file_stat;
1686 if (stat(filename.c_str(), &file_stat) == 0) {
1687 return (file_stat.st_mode & S_IROTH) != 0;
1688 }
1689 return false;
1690}
1691
1692// Create the oat file structure for the secondary dex 'dex_path' and assign
1693// the individual path component to the 'out_' parameters.
1694static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1695 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1696 size_t dirIndex = dex_path.rfind('/');
1697 if (dirIndex == std::string::npos) {
1698 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1699 return false;
1700 }
1701 // TODO(calin): we have similar computations in at lest 3 other places
1702 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1703 // using string append.
1704 std::string apk_dir = dex_path.substr(0, dirIndex);
1705 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1706 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1707
1708 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1709 /*is_secondary_dex*/true, out_oat_path)) {
1710 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1711 return false;
1712 }
1713 return true;
1714}
1715
1716// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1717// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1718static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1719 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1720 *out_storage_flag = FLAG_STORAGE_CE;
1721 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1722 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1723 return false;
1724 }
1725 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1726 *out_storage_flag = FLAG_STORAGE_DE;
1727 } else {
1728 LOG(ERROR) << "Secondary dex storage flag must be set";
1729 return false;
1730 }
1731 return true;
1732}
1733
Calin Juravlec9eab382017-01-25 01:17:17 -08001734// 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 -08001735// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1736// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001737// When returning true, the output parameters will be:
1738// - is_public_out: whether or not the oat file should not be made public
1739// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1740// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001741static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001742 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001743 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle7d765462017-09-04 15:57:10 -07001744 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1745 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001746 int storage_flag;
Calin Juravle7d765462017-09-04 15:57:10 -07001747 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001748 return false;
1749 }
Calin Juravle7d765462017-09-04 15:57:10 -07001750 // Compute the oat dir as it's not easy to extract it from the child computation.
1751 char oat_path[PKG_PATH_MAX];
1752 char oat_dir[PKG_PATH_MAX];
1753 char oat_isa_dir[PKG_PATH_MAX];
1754 if (!create_secondary_dex_oat_layout(
1755 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1756 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001757 return false;
1758 }
Calin Juravle7d765462017-09-04 15:57:10 -07001759 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001760
Calin Juravle80a21252017-01-17 14:43:25 -08001761 pid_t pid = fork();
1762 if (pid == 0) {
1763 // child -- drop privileges before continuing.
1764 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001765
1766 // Validate the path structure.
1767 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1768 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1769 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1770 }
1771
1772 // Open the dex file.
1773 unique_fd zip_fd;
1774 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1775 if (zip_fd.get() < 0) {
1776 if (errno == ENOENT) {
1777 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1778 } else {
1779 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1780 }
1781 }
1782
1783 // Prepare the oat directories.
1784 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1785 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1786 }
1787
1788 // Open the vdex/oat files if any.
1789 unique_fd oat_file_fd;
1790 unique_fd vdex_file_fd;
1791 if (!maybe_open_oat_and_vdex_file(dex_path,
1792 *oat_dir_out,
1793 instruction_set,
1794 true /* is_secondary_dex */,
1795 &oat_file_fd,
1796 &vdex_file_fd)) {
1797 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1798 }
1799
1800 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001801 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1802 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001803
1804 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001805 exec_dexoptanalyzer(dex_path,
1806 vdex_file_fd.get(),
1807 oat_file_fd.get(),
1808 zip_fd.get(),
1809 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001810 compiler_filter, profile_was_updated,
1811 downgrade,
1812 class_loader_context);
1813 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1814 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001815 }
1816
1817 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001818 int result = wait_child(pid);
1819 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001820 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001821 return false;
1822 }
1823 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001824 // Check that we successfully executed dexoptanalyzer.
1825 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1826
1827 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1828
Calin Juravle80a21252017-01-17 14:43:25 -08001829 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001830 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1831 // makes the code simpler; force compilation is only needed during tests).
1832 if (success &&
1833 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1834 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001835 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1836 }
1837
Calin Juravle7d765462017-09-04 15:57:10 -07001838 // Check if we should make the oat file public.
1839 // Note that if the dex file is not public the compiled code cannot be made public.
1840 // It is ok to check this flag outside in the parent process.
1841 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1842
Calin Juravle80a21252017-01-17 14:43:25 -08001843 return success;
1844}
1845
Calin Juravlec9eab382017-01-25 01:17:17 -08001846int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001847 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001848 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle824a64d2018-01-18 20:23:17 -08001849 bool downgrade, int target_sdk_version, const char* profile_name) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001850 CHECK(pkgname != nullptr);
1851 CHECK(pkgname[0] != 0);
1852 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1853 LOG_FATAL("dexopt flags contains unknown fields\n");
1854 }
1855
Calin Juravled23dee72017-07-06 16:29:11 -07001856 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001857 return -1;
1858 }
1859
1860 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1861 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1862 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001863 }
1864
Calin Juravleebc8a792017-04-04 20:21:05 -07001865 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001866 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1867 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1868 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001869 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001870 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001871 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001872
1873 // Check if we're dealing with a secondary dex file and if we need to compile it.
1874 std::string oat_dir_str;
1875 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001876 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001877 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle7d765462017-09-04 15:57:10 -07001878 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001879 oat_dir = oat_dir_str.c_str();
1880 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1881 return 0; // Nothing to do, report success.
1882 }
1883 } else {
1884 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) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001896 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001897 return -1;
1898 }
1899
1900 // Create the output OAT file.
1901 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001902 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001903 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001904 if (out_oat_fd.get() < 0) {
1905 return -1;
1906 }
1907
1908 // Open vdex files.
1909 Dex2oatFileWrapper in_vdex_fd;
1910 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001911 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1912 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001913 return -1;
1914 }
1915
Calin Juravlecb556e32017-04-04 20:22:50 -07001916 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1917 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1918 // fully inherit their parent context).
1919 // Note that for primary apk the oat files are created before, in a separate installd
1920 // call which also does the restorecon. TODO(calin): unify the paths.
1921 if (is_secondary_dex) {
1922 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1923 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1924 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1925 return -1;
1926 }
1927 }
1928
Jeff Sharkey90aff262016-12-12 14:28:24 -07001929 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001930 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001931
Calin Juravle7a570e82017-01-14 16:23:30 -08001932 // Create the app image file if needed.
1933 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001934 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001935
Calin Juravle7a570e82017-01-14 16:23:30 -08001936 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001937 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001938 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001939
Calin Juravlec9eab382017-01-25 01:17:17 -08001940 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001941
1942 pid_t pid = fork();
1943 if (pid == 0) {
1944 /* child -- drop privileges before continuing */
1945 drop_capabilities(uid);
1946
Richard Uhler76cc0272016-12-08 10:46:35 +00001947 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001948 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1949 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1950 _exit(67);
1951 }
1952
Richard Uhler76cc0272016-12-08 10:46:35 +00001953 run_dex2oat(input_fd.get(),
1954 out_oat_fd.get(),
1955 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001956 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001957 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001958 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001959 out_oat_path,
1960 swap_fd.get(),
1961 instruction_set,
1962 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001963 debuggable,
1964 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001965 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00001966 reference_profile_fd.get(),
David Brazdil570d3982018-01-16 20:15:43 +00001967 class_loader_context,
David Brazdil7fcbb812018-01-17 17:05:40 +00001968 target_sdk_version,
David Brazdil52249162018-02-12 18:04:59 -08001969 enable_hidden_api_checks);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001970 _exit(68); /* only get here on exec failure */
1971 } else {
1972 int res = wait_child(pid);
1973 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001974 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001975 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001976 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001977 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001978 }
1979 }
1980
Calin Juravlec9eab382017-01-25 01:17:17 -08001981 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001982
1983 // We've been successful, don't delete output.
1984 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001985 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001986 image_fd.SetCleanup(false);
1987 reference_profile_fd.SetCleanup(false);
1988
1989 return 0;
1990}
1991
Calin Juravlec9eab382017-01-25 01:17:17 -08001992// Try to remove the given directory. Log an error if the directory exists
1993// and is empty but could not be removed.
1994static bool rmdir_if_empty(const char* dir) {
1995 if (rmdir(dir) == 0) {
1996 return true;
1997 }
1998 if (errno == ENOENT || errno == ENOTEMPTY) {
1999 return true;
2000 }
2001 PLOG(ERROR) << "Failed to remove dir: " << dir;
2002 return false;
2003}
2004
2005// Try to unlink the given file. Log an error if the file exists and could not
2006// be unlinked.
2007static bool unlink_if_exists(const std::string& file) {
2008 if (unlink(file.c_str()) == 0) {
2009 return true;
2010 }
2011 if (errno == ENOENT) {
2012 return true;
2013
2014 }
2015 PLOG(ERROR) << "Could not unlink: " << file;
2016 return false;
2017}
2018
Calin Juravle7d765462017-09-04 15:57:10 -07002019enum ReconcileSecondaryDexResult {
2020 kReconcileSecondaryDexExists = 0,
2021 kReconcileSecondaryDexCleanedUp = 1,
2022 kReconcileSecondaryDexValidationError = 2,
2023 kReconcileSecondaryDexCleanUpError = 3,
2024 kReconcileSecondaryDexAccessIOError = 4,
2025};
Calin Juravlec9eab382017-01-25 01:17:17 -08002026
2027// Reconcile the secondary dex 'dex_path' and its generated oat files.
2028// Return true if all the parameters are valid and the secondary dex file was
2029// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2030// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2031// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2032// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2033// Return false if there were errors during processing. In this case
2034// out_secondary_dex_exists will be set to false.
2035bool reconcile_secondary_dex_file(const std::string& dex_path,
2036 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2037 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2038 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002039 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002040 if (isas.size() == 0) {
2041 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2042 return false;
2043 }
2044
Calin Juravle7d765462017-09-04 15:57:10 -07002045 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2046 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2047 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002048 return false;
2049 }
2050
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002051 // As a security measure we want to unlink art artifacts with the reduced capabilities
2052 // of the package user id. So we fork and drop capabilities in the child.
2053 pid_t pid = fork();
2054 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002055 /* child -- drop privileges before continuing */
2056 drop_capabilities(uid);
2057
2058 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2059 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2060 uid, storage_flag)) {
2061 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2062 _exit(kReconcileSecondaryDexValidationError);
2063 }
2064
2065 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2066 switch (access_check) {
2067 case kSecondaryDexAccessDoesNotExist:
2068 // File does not exist. Proceed with cleaning.
2069 break;
2070 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2071 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2072 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2073 default:
2074 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2075 _exit(kReconcileSecondaryDexValidationError);
2076 }
2077
2078 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002079 char oat_path[PKG_PATH_MAX];
2080 char oat_dir[PKG_PATH_MAX];
2081 char oat_isa_dir[PKG_PATH_MAX];
2082 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002083 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle7d765462017-09-04 15:57:10 -07002084 if (!create_secondary_dex_oat_layout(
2085 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
2086 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
2087 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002088 }
Calin Juravle51314092017-05-18 15:33:05 -07002089
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002090 // Delete oat/vdex/art files.
2091 result = unlink_if_exists(oat_path) && result;
2092 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2093 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002094
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002095 // Delete profiles.
2096 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002097 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002098 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002099 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002100 result = unlink_if_exists(current_profile) && result;
2101 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002102
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002103 // We upgraded once the location of current profile for secondary dex files.
2104 // Check for any previous left-overs and remove them as well.
2105 std::string old_current_profile = dex_path + ".prof";
2106 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002107
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002108 // Try removing the directories as well, they might be empty.
2109 result = rmdir_if_empty(oat_isa_dir) && result;
2110 result = rmdir_if_empty(oat_dir) && result;
2111 }
Calin Juravle7d765462017-09-04 15:57:10 -07002112 if (!result) {
2113 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2114 }
2115 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002116 }
2117
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002118 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002119 if (!WIFEXITED(return_code)) {
2120 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2121 } else {
2122 return_code = WEXITSTATUS(return_code);
2123 }
2124
2125 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2126
2127 switch (return_code) {
2128 case kReconcileSecondaryDexCleanedUp:
2129 case kReconcileSecondaryDexValidationError:
2130 // If we couldn't validate assume the dex file does not exist.
2131 // This will purge the entry from the PM records.
2132 *out_secondary_dex_exists = false;
2133 return true;
2134 case kReconcileSecondaryDexExists:
2135 *out_secondary_dex_exists = true;
2136 return true;
2137 case kReconcileSecondaryDexAccessIOError:
2138 // We had an access IO error.
2139 // Return false so that we can try again.
2140 // The value of out_secondary_dex_exists does not matter in this case and by convention
2141 // is set to false.
2142 *out_secondary_dex_exists = false;
2143 return false;
2144 default:
2145 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2146 *out_secondary_dex_exists = false;
2147 return false;
2148 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002149}
2150
Alan Stokesa25d90c2017-10-16 10:56:00 +01002151// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2152// Returns true if all parameters are valid and the hash successfully computed and stored in
2153// out_secondary_dex_hash.
2154// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2155// the app.
2156// For any other errors (e.g. if any of the parameters are invalid) returns false.
2157bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2158 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2159 std::vector<uint8_t>* out_secondary_dex_hash) {
2160 out_secondary_dex_hash->clear();
2161
2162 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2163
2164 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2165 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2166 << storage_flag;
2167 return false;
2168 }
2169
2170 // Pipe to get the hash result back from our child process.
2171 unique_fd pipe_read, pipe_write;
2172 if (!Pipe(&pipe_read, &pipe_write)) {
2173 PLOG(ERROR) << "Failed to create pipe";
2174 return false;
2175 }
2176
2177 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2178 // access data the app itself can access.
2179 pid_t pid = fork();
2180 if (pid == 0) {
2181 // child -- drop privileges before continuing
2182 drop_capabilities(uid);
2183 pipe_read.reset();
2184
2185 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2186 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2187 _exit(1);
2188 }
2189
2190 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2191 if (fd == -1) {
2192 if (errno == EACCES || errno == ENOENT) {
2193 // Not treated as an error.
2194 _exit(0);
2195 }
2196 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
2197 _exit(1);
2198 }
2199
2200 SHA256_CTX ctx;
2201 SHA256_Init(&ctx);
2202
2203 std::vector<uint8_t> buffer(65536);
2204 while (true) {
2205 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2206 if (bytes_read == 0) {
2207 break;
2208 } else if (bytes_read == -1) {
2209 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
2210 _exit(1);
2211 }
2212
2213 SHA256_Update(&ctx, buffer.data(), bytes_read);
2214 }
2215
2216 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2217 SHA256_Final(hash.data(), &ctx);
2218 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
2219 _exit(1);
2220 }
2221
2222 _exit(0);
2223 }
2224
2225 // parent
2226 pipe_write.reset();
2227
2228 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2229 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2230 out_secondary_dex_hash->clear();
2231 }
2232 return wait_child(pid) == 0;
2233}
2234
Jeff Sharkey90aff262016-12-12 14:28:24 -07002235// Helper for move_ab, so that we can have common failure-case cleanup.
2236static bool unlink_and_rename(const char* from, const char* to) {
2237 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2238 // return a failure.
2239 struct stat s;
2240 if (stat(to, &s) == 0) {
2241 if (!S_ISREG(s.st_mode)) {
2242 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2243 return false;
2244 }
2245 if (unlink(to) != 0) {
2246 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2247 return false;
2248 }
2249 } else {
2250 // This may be a permission problem. We could investigate the error code, but we'll just
2251 // let the rename failure do the work for us.
2252 }
2253
2254 // Try to rename "to" to "from."
2255 if (rename(from, to) != 0) {
2256 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2257 return false;
2258 }
2259 return true;
2260}
2261
2262// Move/rename a B artifact (from) to an A artifact (to).
2263static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2264 // Check whether B exists.
2265 {
2266 struct stat s;
2267 if (stat(b_path.c_str(), &s) != 0) {
2268 // Silently ignore for now. The service calling this isn't smart enough to understand
2269 // lack of artifacts at the moment.
2270 return false;
2271 }
2272 if (!S_ISREG(s.st_mode)) {
2273 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2274 // Try to unlink, but swallow errors.
2275 unlink(b_path.c_str());
2276 return false;
2277 }
2278 }
2279
2280 // Rename B to A.
2281 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2282 // Delete the b_path so we don't try again (or fail earlier).
2283 if (unlink(b_path.c_str()) != 0) {
2284 PLOG(ERROR) << "Could not unlink " << b_path;
2285 }
2286
2287 return false;
2288 }
2289
2290 return true;
2291}
2292
2293bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2294 // Get the current slot suffix. No suffix, no A/B.
2295 std::string slot_suffix;
2296 {
2297 char buf[kPropertyValueMax];
2298 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2299 return false;
2300 }
2301 slot_suffix = buf;
2302
2303 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2304 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2305 return false;
2306 }
2307 }
2308
2309 // Validate other inputs.
2310 if (validate_apk_path(apk_path) != 0) {
2311 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2312 return false;
2313 }
2314 if (validate_apk_path(oat_dir) != 0) {
2315 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2316 return false;
2317 }
2318
2319 char a_path[PKG_PATH_MAX];
2320 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2321 return false;
2322 }
2323 const std::string a_vdex_path = create_vdex_filename(a_path);
2324 const std::string a_image_path = create_image_filename(a_path);
2325
2326 // B path = A path + slot suffix.
2327 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2328 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2329 const std::string b_image_path = StringPrintf("%s.%s",
2330 a_image_path.c_str(),
2331 slot_suffix.c_str());
2332
2333 bool success = true;
2334 if (move_ab_path(b_path, a_path)) {
2335 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2336 // Note: we can live without an app image. As such, ignore failure to move the image file.
2337 // If we decide to require the app image, or the app image being moved correctly,
2338 // then change accordingly.
2339 constexpr bool kIgnoreAppImageFailure = true;
2340
2341 if (!a_image_path.empty()) {
2342 if (!move_ab_path(b_image_path, a_image_path)) {
2343 unlink(a_image_path.c_str());
2344 if (!kIgnoreAppImageFailure) {
2345 success = false;
2346 }
2347 }
2348 }
2349 } else {
2350 // Cleanup: delete B image, ignore errors.
2351 unlink(b_image_path.c_str());
2352 success = false;
2353 }
2354 } else {
2355 // Cleanup: delete B image, ignore errors.
2356 unlink(b_vdex_path.c_str());
2357 unlink(b_image_path.c_str());
2358 success = false;
2359 }
2360 return success;
2361}
2362
2363bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2364 // Delete the oat/odex file.
2365 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002366 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002367 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002368 return false;
2369 }
2370
2371 // In case of a permission failure report the issue. Otherwise just print a warning.
2372 auto unlink_and_check = [](const char* path) -> bool {
2373 int result = unlink(path);
2374 if (result != 0) {
2375 if (errno == EACCES || errno == EPERM) {
2376 PLOG(ERROR) << "Could not unlink " << path;
2377 return false;
2378 }
2379 PLOG(WARNING) << "Could not unlink " << path;
2380 }
2381 return true;
2382 };
2383
2384 // Delete the oat/odex file.
2385 bool return_value_oat = unlink_and_check(out_path);
2386
2387 // Derive and delete the app image.
2388 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2389
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002390 // Derive and delete the vdex file.
2391 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2392
Jeff Sharkey90aff262016-12-12 14:28:24 -07002393 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002394 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002395}
2396
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002397static bool is_absolute_path(const std::string& path) {
2398 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2399 LOG(ERROR) << "Invalid absolute path " << path;
2400 return false;
2401 } else {
2402 return true;
2403 }
2404}
2405
2406static bool is_valid_instruction_set(const std::string& instruction_set) {
2407 // TODO: add explicit whitelisting of instruction sets
2408 if (instruction_set.find('/') != std::string::npos) {
2409 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2410 return false;
2411 } else {
2412 return true;
2413 }
2414}
2415
2416bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2417 const char *apk_path, const char *instruction_set) {
2418 std::string oat_dir_ = oat_dir;
2419 std::string apk_path_ = apk_path;
2420 std::string instruction_set_ = instruction_set;
2421
2422 if (!is_absolute_path(oat_dir_)) return false;
2423 if (!is_absolute_path(apk_path_)) return false;
2424 if (!is_valid_instruction_set(instruction_set_)) return false;
2425
2426 std::string::size_type end = apk_path_.rfind('.');
2427 std::string::size_type start = apk_path_.rfind('/', end);
2428 if (end == std::string::npos || start == std::string::npos) {
2429 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2430 return false;
2431 }
2432
2433 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2434 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2435 const char* res = res_.c_str();
2436 if (strlen(res) >= PKG_PATH_MAX) {
2437 LOG(ERROR) << "Result too large";
2438 return false;
2439 } else {
2440 strlcpy(path, res, PKG_PATH_MAX);
2441 return true;
2442 }
2443}
2444
2445bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2446 const char *instruction_set) {
2447 std::string apk_path_ = apk_path;
2448 std::string instruction_set_ = instruction_set;
2449
2450 if (!is_absolute_path(apk_path_)) return false;
2451 if (!is_valid_instruction_set(instruction_set_)) return false;
2452
2453 std::string::size_type end = apk_path_.rfind('.');
2454 std::string::size_type start = apk_path_.rfind('/', end);
2455 if (end == std::string::npos || start == std::string::npos) {
2456 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2457 return false;
2458 }
2459
2460 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2461 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2462}
2463
2464bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2465 const char *instruction_set) {
2466 std::string src_ = src;
2467 std::string instruction_set_ = instruction_set;
2468
2469 if (!is_absolute_path(src_)) return false;
2470 if (!is_valid_instruction_set(instruction_set_)) return false;
2471
2472 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2473 if (*it == '/') {
2474 *it = '@';
2475 }
2476 }
2477
2478 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2479 + DALVIK_CACHE_POSTFIX;
2480 const char* res = res_.c_str();
2481 if (strlen(res) >= PKG_PATH_MAX) {
2482 LOG(ERROR) << "Result too large";
2483 return false;
2484 } else {
2485 strlcpy(path, res, PKG_PATH_MAX);
2486 return true;
2487 }
2488}
2489
Calin Juravle0d0a4922018-01-23 19:54:11 -08002490bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds) {
2491 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2492 for (const std::string& elem : classpaths_elems) {
2493 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2494 if (fd < 0) {
2495 PLOG(ERROR) << "Could not open classpath elem " << elem;
2496 return false;
2497 } else {
2498 apk_fds->push_back(std::move(fd));
2499 }
2500 }
2501 return true;
2502}
2503
2504static bool create_app_profile_snapshot(int32_t app_id,
2505 const std::string& package_name,
2506 const std::string& profile_name,
2507 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002508 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2509
Calin Juravle824a64d2018-01-18 20:23:17 -08002510 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002511 if (snapshot_fd < 0) {
2512 return false;
2513 }
2514
2515 std::vector<unique_fd> profiles_fd;
2516 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002517 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2518 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002519 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2520 return false;
2521 }
2522
2523 profiles_fd.push_back(std::move(reference_profile_fd));
2524
Calin Juravle0d0a4922018-01-23 19:54:11 -08002525 // Open the class paths elements. These will be used to filter out profile data that does
2526 // not belong to the classpath during merge.
2527 std::vector<unique_fd> apk_fds;
2528 if (!open_classpath_files(classpath, &apk_fds)) {
2529 return false;
2530 }
2531
Calin Juravle29591732017-11-20 17:46:19 -08002532 pid_t pid = fork();
2533 if (pid == 0) {
2534 /* child -- drop privileges before continuing */
2535 drop_capabilities(app_shared_gid);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002536 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds);
Calin Juravle29591732017-11-20 17:46:19 -08002537 exit(42); /* only get here on exec failure */
2538 }
2539
2540 /* parent */
2541 int return_code = wait_child(pid);
2542 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002543 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002544 return false;
2545 }
2546
2547 return true;
2548}
2549
Calin Juravle0d0a4922018-01-23 19:54:11 -08002550static bool create_boot_image_profile_snapshot(const std::string& package_name,
2551 const std::string& profile_name,
2552 const std::string& classpath) {
2553 // The reference profile directory for the android package might not be prepared. Do it now.
2554 const std::string ref_profile_dir =
2555 create_primary_reference_profile_package_dir_path(package_name);
2556 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2557 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2558 return false;
2559 }
2560
2561 // Open and create the snapshot profile.
2562 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2563
2564 // Collect all non empty profiles.
2565 // The collection will traverse all applications profiles and find the non empty files.
2566 // This has the potential of inspecting a large number of files and directories (depending
2567 // on the number of applications and users). So there is a slight increase in the chance
2568 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2569 // fail the snapshot and aggregate whatever profile we could open.
2570 //
2571 // The profile snapshot is a best effort based on available data it's ok if some data
2572 // from some apps is missing. It will be counter productive for the snapshot to fail
2573 // because we could not open or read some of the files.
2574 std::vector<std::string> profiles;
2575 if (!collect_profiles(&profiles)) {
2576 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2577 }
2578
2579 // If we have no profiles return early.
2580 if (profiles.empty()) {
2581 return true;
2582 }
2583
2584 // Open the classpath elements. These will be used to filter out profile data that does
2585 // not belong to the classpath during merge.
2586 std::vector<unique_fd> apk_fds;
2587 if (!open_classpath_files(classpath, &apk_fds)) {
2588 return false;
2589 }
2590
2591 // If we could not open any files from the classpath return an error.
2592 if (apk_fds.empty()) {
2593 LOG(ERROR) << "Could not open any of the classpath elements.";
2594 return false;
2595 }
2596
2597 // Aggregate the profiles in batches of kAggregationBatchSize.
2598 // We do this to avoid opening a huge a amount of files.
2599 static constexpr size_t kAggregationBatchSize = 10;
2600
2601 std::vector<unique_fd> profiles_fd;
2602 for (size_t i = 0; i < profiles.size(); ) {
2603 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2604 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2605 if (fd.get() >= 0) {
2606 profiles_fd.push_back(std::move(fd));
2607 }
2608 }
2609 pid_t pid = fork();
2610 if (pid == 0) {
2611 /* child -- drop privileges before continuing */
2612 drop_capabilities(AID_SYSTEM);
2613
2614 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds);
2615 exit(42); /* only get here on exec failure */
2616 }
2617
2618 /* parent */
2619 int return_code = wait_child(pid);
2620 if (!WIFEXITED(return_code)) {
2621 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2622 return false;
2623 }
2624 return true;
2625 }
2626 return true;
2627}
2628
2629bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2630 const std::string& profile_name, const std::string& classpath) {
2631 if (app_id == -1) {
2632 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2633 } else {
2634 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2635 }
2636}
2637
Calin Juravlec3b049e2018-01-18 22:32:58 -08002638bool prepare_app_profile(const std::string& package_name,
2639 userid_t user_id,
2640 appid_t app_id,
2641 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002642 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002643 const std::unique_ptr<std::string>& dex_metadata) {
2644 // Prepare the current profile.
2645 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2646 /*is_secondary_dex*/ false);
2647 uid_t uid = multiuser_get_uid(user_id, app_id);
2648 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2649 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2650 return false;
2651 }
2652
2653 // Check if we need to install the profile from the dex metadata.
2654 if (dex_metadata == nullptr) {
2655 return true;
2656 }
2657
2658 // We have a dex metdata. Merge the profile into the reference profile.
2659 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2660 /*read_write*/ true, /*is_secondary_dex*/ false);
2661 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2662 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002663 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2664 if (apk_fd < 0) {
2665 PLOG(ERROR) << "Could not open code path " << code_path;
2666 return false;
2667 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002668
2669 pid_t pid = fork();
2670 if (pid == 0) {
2671 /* child -- drop privileges before continuing */
2672 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2673 drop_capabilities(app_shared_gid);
2674
Calin Juravlef63d4792018-01-30 17:43:34 +00002675 // The copy and update takes ownership over the fds.
2676 run_profman_copy_and_update(std::move(dex_metadata_fd),
2677 std::move(ref_profile_fd),
2678 std::move(apk_fd));
Calin Juravlec3b049e2018-01-18 22:32:58 -08002679 exit(42); /* only get here on exec failure */
2680 }
2681
2682 /* parent */
2683 int return_code = wait_child(pid);
2684 if (!WIFEXITED(return_code)) {
2685 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2686 return false;
2687 }
2688 return true;
2689}
2690
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002691} // namespace installd
2692} // namespace android