blob: 57c64c6098685273f9669681fb66dc9b7bdf19ba [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
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070042#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010043#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <private/android_filesystem_config.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070045#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070046#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070047
48#include "dexopt.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060049#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070050#include "installd_deps.h"
51#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070052#include "utils.h"
53
Jeff Sharkey90aff262016-12-12 14:28:24 -070054using android::base::EndsWith;
Alan Stokesa25d90c2017-10-16 10:56:00 +010055using android::base::ReadFully;
56using android::base::StringPrintf;
57using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080058using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070059
60namespace android {
61namespace installd {
62
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070063// Should minidebug info be included in compiled artifacts? Even if this value is
64// "true," usage might still be conditional to other constraints, e.g., system
65// property overrides.
66static constexpr bool kEnableMinidebugInfo = true;
67
68static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
69static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
70static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080071static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070072
Calin Juravle114f0812017-03-08 19:05:07 -080073// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
74struct FreeDelete {
75 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
76 void operator()(const void* ptr) const {
77 free(const_cast<void*>(ptr));
78 }
79};
80
81// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
82template <typename T>
83using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
84
Calin Juravle1a0af3b2017-03-09 14:33:33 -080085static unique_fd invalid_unique_fd() {
86 return unique_fd(-1);
87}
88
Andreas Gampe6a9cf722017-07-24 16:49:10 -070089static bool is_debug_runtime() {
90 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
91}
92
David Sehra3b5ab62017-10-25 14:27:29 -070093static bool is_debuggable_build() {
94 return android::base::GetBoolProperty("ro.debuggable", false);
95}
96
Jeff Sharkey90aff262016-12-12 14:28:24 -070097static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080098 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070099 if (ufd.get() < 0) {
100 if (errno != ENOENT) {
101 PLOG(WARNING) << "Could not open profile " << profile;
102 return false;
103 } else {
104 // Nothing to clear. That's ok.
105 return true;
106 }
107 }
108
109 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
110 if (errno != EWOULDBLOCK) {
111 PLOG(WARNING) << "Error locking profile " << profile;
112 }
113 // This implies that the app owning this profile is running
114 // (and has acquired the lock).
115 //
116 // If we can't acquire the lock bail out since clearing is useless anyway
117 // (the app will write again to the profile).
118 //
119 // Note:
120 // This does not impact the this is not an issue for the profiling correctness.
121 // In case this is needed because of an app upgrade, profiles will still be
122 // eventually cleared by the app itself due to checksum mismatch.
123 // If this is needed because profman advised, then keeping the data around
124 // until the next run is again not an issue.
125 //
126 // If the app attempts to acquire a lock while we've held one here,
127 // it will simply skip the current write cycle.
128 return false;
129 }
130
131 bool truncated = ftruncate(ufd.get(), 0) == 0;
132 if (!truncated) {
133 PLOG(WARNING) << "Could not truncate " << profile;
134 }
135 if (flock(ufd.get(), LOCK_UN) != 0) {
136 PLOG(WARNING) << "Error unlocking profile " << profile;
137 }
138 return truncated;
139}
140
Calin Juravle114f0812017-03-08 19:05:07 -0800141// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800142// The location is the profile name for primary apks or the dex path for secondary dex files.
143static bool clear_reference_profile(const std::string& package_name, const std::string& location,
144 bool is_secondary_dex) {
145 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700146}
147
Calin Juravle114f0812017-03-08 19:05:07 -0800148// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800149// The location is the profile name for primary apks or the dex path for secondary dex files.
150static bool clear_current_profile(const std::string& package_name, const std::string& location,
151 userid_t user, bool is_secondary_dex) {
152 return clear_profile(create_current_profile_path(user, package_name, location,
153 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154}
155
Calin Juravle114f0812017-03-08 19:05:07 -0800156// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800157// The location is the profile name for primary apks or the dex path for secondary dex files.
158bool clear_primary_reference_profile(const std::string& package_name,
159 const std::string& location) {
160 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800161}
162
163// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800164// The location is the profile name for primary apks or the dex path for secondary dex files.
165bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700166 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800167 // 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 -0700168 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
169 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800170 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700171 }
172 return success;
173}
174
Calin Juravle114f0812017-03-08 19:05:07 -0800175// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800176bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
177 userid_t user) {
178 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800179}
180
Jeff Sharkey90aff262016-12-12 14:28:24 -0700181static int split_count(const char *str)
182{
183 char *ctx;
184 int count = 0;
185 char buf[kPropertyValueMax];
186
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600187 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700188 char *pBuf = buf;
189
190 while(strtok_r(pBuf, " ", &ctx) != NULL) {
191 count++;
192 pBuf = NULL;
193 }
194
195 return count;
196}
197
198static int split(char *buf, const char **argv)
199{
200 char *ctx;
201 int count = 0;
202 char *tok;
203 char *pBuf = buf;
204
205 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
206 argv[count++] = tok;
207 pBuf = NULL;
208 }
209
210 return count;
211}
212
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700213static const char* get_location_from_path(const char* path) {
214 static constexpr char kLocationSeparator = '/';
215 const char *location = strrchr(path, kLocationSeparator);
216 if (location == NULL) {
217 return path;
218 } else {
219 // Skip the separator character.
220 return location + 1;
221 }
222}
223
Jeff Sharkey90aff262016-12-12 14:28:24 -0700224static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
225 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100226 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700227 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
Calin Juravle62c5a372018-02-01 17:03:23 +0000228 const char* class_loader_context, int target_sdk_version, bool enable_hidden_api_checks,
Calin Juravle2efc4022018-02-13 18:31:32 -0800229 int dex_metadata_fd, const char* compilation_reason) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700230 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
231
232 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
233 ALOGE("Instruction set %s longer than max length of %d",
234 instruction_set, MAX_INSTRUCTION_SET_LEN);
235 return;
236 }
237
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700238 // Get the relative path to the input file.
239 const char* relative_input_file_name = get_location_from_path(input_file_name);
240
Jeff Sharkey90aff262016-12-12 14:28:24 -0700241 char dex2oat_Xms_flag[kPropertyValueMax];
242 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
243
244 char dex2oat_Xmx_flag[kPropertyValueMax];
245 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
246
247 char dex2oat_threads_buf[kPropertyValueMax];
248 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
249 ? "dalvik.vm.dex2oat-threads"
250 : "dalvik.vm.boot-dex2oat-threads",
251 dex2oat_threads_buf,
252 NULL) > 0;
253 char dex2oat_threads_arg[kPropertyValueMax + 2];
254 if (have_dex2oat_threads_flag) {
255 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
256 }
257
258 char dex2oat_isa_features_key[kPropertyKeyMax];
259 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
260 char dex2oat_isa_features[kPropertyValueMax];
261 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
262 dex2oat_isa_features, NULL) > 0;
263
264 char dex2oat_isa_variant_key[kPropertyKeyMax];
265 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
266 char dex2oat_isa_variant[kPropertyValueMax];
267 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
268 dex2oat_isa_variant, NULL) > 0;
269
270 const char *dex2oat_norelocation = "-Xnorelocate";
271 bool have_dex2oat_relocation_skip_flag = false;
272
273 char dex2oat_flags[kPropertyValueMax];
274 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
275 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
276 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
277
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100278 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700279 char vold_decrypt[kPropertyValueMax];
280 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
281 bool skip_compilation = (have_vold_decrypt &&
282 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
283 (strcmp(vold_decrypt, "1") == 0)));
284
285 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
286
287 char app_image_format[kPropertyValueMax];
288 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
289 bool have_app_image_format =
290 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
291 if (have_app_image_format) {
292 sprintf(image_format_arg, "--image-format=%s", app_image_format);
293 }
294
295 char dex2oat_large_app_threshold[kPropertyValueMax];
296 bool have_dex2oat_large_app_threshold =
297 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
298 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
299 if (have_dex2oat_large_app_threshold) {
300 sprintf(dex2oat_large_app_threshold_arg,
301 "--very-large-app-threshold=%s",
302 dex2oat_large_app_threshold);
303 }
304
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700305 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700306 const char* dex2oat_bin = "/system/bin/dex2oat";
307 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700308 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700309 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
310 dex2oat_bin = kDex2oatDebugPath;
311 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700312
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700313 bool generate_minidebug_info = kEnableMinidebugInfo &&
314 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
315 kMinidebugInfoSystemPropertyDefault);
316
Jeff Sharkey90aff262016-12-12 14:28:24 -0700317 static const char* RUNTIME_ARG = "--runtime-arg";
318
319 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
320
George Burgess IV36cebe772017-01-25 11:52:01 -0800321 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
322 // use arraysize instead.
323 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
324 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
325 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
326 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
327 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
328 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
329 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
330 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
331 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
332 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
333 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
334 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700335 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800336 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700337 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800338 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700339 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
David Brazdil570d3982018-01-16 20:15:43 +0000340 char target_sdk_version_arg[arraysize("-Xtarget-sdk-version:") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700341 char class_loader_context_arg[class_loader_context_size];
342 if (class_loader_context != nullptr) {
343 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
344 class_loader_context);
345 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700346
347 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700348 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700349 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
350 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
351 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
352 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
353 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
354 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
355 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
356 if (swap_fd >= 0) {
357 have_dex2oat_swap_fd = true;
358 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
359 }
360 if (image_fd >= 0) {
361 have_dex2oat_image_fd = true;
362 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
363 }
364
365 if (have_dex2oat_Xms_flag) {
366 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
367 }
368 if (have_dex2oat_Xmx_flag) {
369 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
370 }
David Brazdil570d3982018-01-16 20:15:43 +0000371 sprintf(target_sdk_version_arg, "-Xtarget-sdk-version:%d", target_sdk_version);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700372
373 // Compute compiler filter.
374
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100375 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700376 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600377 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
378 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700379 have_dex2oat_compiler_filter_flag = true;
380 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100381 } else if (compiler_filter != nullptr) {
382 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700383 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100384 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
385 have_dex2oat_compiler_filter_flag = true;
386 } else {
387 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
388 compiler_filter,
389 kPropertyValueMax);
390 }
391 }
392
393 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700394 char dex2oat_compiler_filter_flag[kPropertyValueMax];
395 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
396 dex2oat_compiler_filter_flag, NULL) > 0;
397 if (have_dex2oat_compiler_filter_flag) {
398 sprintf(dex2oat_compiler_filter_arg,
399 "--compiler-filter=%s",
400 dex2oat_compiler_filter_flag);
401 }
402 }
403
404 // Check whether all apps should be compiled debuggable.
405 if (!debuggable) {
406 char prop_buf[kPropertyValueMax];
407 debuggable =
408 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
409 (prop_buf[0] == '1');
410 }
411 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
412 if (profile_fd != -1) {
413 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
414 }
415
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700416 // Get the directory of the apk to pass as a base classpath directory.
417 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
418 std::string apk_dir(input_file_name);
419 unsigned long dir_index = apk_dir.rfind('/');
420 bool has_base_dir = dir_index != std::string::npos;
421 if (has_base_dir) {
422 apk_dir = apk_dir.substr(0, dir_index);
423 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
424 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700425
Calin Juravle62c5a372018-02-01 17:03:23 +0000426 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700427
Calin Juravle2efc4022018-02-13 18:31:32 -0800428 std::string compilation_reason_arg = compilation_reason == nullptr
429 ? ""
430 : std::string("--compilation-reason=") + compilation_reason;
431
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700432 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700433
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800434 // Disable cdex if update input vdex is true since this combination of options is not
435 // supported.
Mathieu Chartier1fb463e2018-01-09 15:16:10 -0800436 // Disable cdex for non-background compiles since we don't want to regress app install until
437 // there are enough benefits to justify the tradeoff.
438 const bool disable_cdex = !background_job_compile || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800439
Jeff Sharkey90aff262016-12-12 14:28:24 -0700440 const char* argv[9 // program name, mandatory arguments and the final NULL
441 + (have_dex2oat_isa_variant ? 1 : 0)
442 + (have_dex2oat_isa_features ? 1 : 0)
443 + (have_dex2oat_Xms_flag ? 2 : 0)
444 + (have_dex2oat_Xmx_flag ? 2 : 0)
445 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
446 + (have_dex2oat_threads_flag ? 1 : 0)
447 + (have_dex2oat_swap_fd ? 1 : 0)
448 + (have_dex2oat_image_fd ? 1 : 0)
449 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
450 + (generate_debug_info ? 1 : 0)
451 + (debuggable ? 1 : 0)
452 + (have_app_image_format ? 1 : 0)
453 + dex2oat_flags_count
454 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700455 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700456 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700457 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800458 + (disable_cdex ? 1 : 0)
David Brazdil570d3982018-01-16 20:15:43 +0000459 + (generate_minidebug_info ? 1 : 0)
David Brazdil7fcbb812018-01-17 17:05:40 +0000460 + (target_sdk_version != 0 ? 2 : 0)
Calin Juravle62c5a372018-02-01 17:03:23 +0000461 + (enable_hidden_api_checks ? 2 : 0)
Calin Juravle2efc4022018-02-13 18:31:32 -0800462 + (dex_metadata_fd > -1 ? 1 : 0)
463 + (compilation_reason != nullptr ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700464 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700465 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700466 argv[i++] = zip_fd_arg;
467 argv[i++] = zip_location_arg;
468 argv[i++] = input_vdex_fd_arg;
469 argv[i++] = output_vdex_fd_arg;
470 argv[i++] = oat_fd_arg;
471 argv[i++] = oat_location_arg;
472 argv[i++] = instruction_set_arg;
473 if (have_dex2oat_isa_variant) {
474 argv[i++] = instruction_set_variant_arg;
475 }
476 if (have_dex2oat_isa_features) {
477 argv[i++] = instruction_set_features_arg;
478 }
479 if (have_dex2oat_Xms_flag) {
480 argv[i++] = RUNTIME_ARG;
481 argv[i++] = dex2oat_Xms_arg;
482 }
483 if (have_dex2oat_Xmx_flag) {
484 argv[i++] = RUNTIME_ARG;
485 argv[i++] = dex2oat_Xmx_arg;
486 }
487 if (have_dex2oat_compiler_filter_flag) {
488 argv[i++] = dex2oat_compiler_filter_arg;
489 }
490 if (have_dex2oat_threads_flag) {
491 argv[i++] = dex2oat_threads_arg;
492 }
493 if (have_dex2oat_swap_fd) {
494 argv[i++] = dex2oat_swap_fd;
495 }
496 if (have_dex2oat_image_fd) {
497 argv[i++] = dex2oat_image_fd;
498 }
499 if (generate_debug_info) {
500 argv[i++] = "--generate-debug-info";
501 }
502 if (debuggable) {
503 argv[i++] = "--debuggable";
504 }
505 if (have_app_image_format) {
506 argv[i++] = image_format_arg;
507 }
508 if (have_dex2oat_large_app_threshold) {
509 argv[i++] = dex2oat_large_app_threshold_arg;
510 }
511 if (dex2oat_flags_count) {
512 i += split(dex2oat_flags, argv + i);
513 }
514 if (have_dex2oat_relocation_skip_flag) {
515 argv[i++] = RUNTIME_ARG;
516 argv[i++] = dex2oat_norelocation;
517 }
518 if (profile_fd != -1) {
519 argv[i++] = profile_arg;
520 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700521 if (has_base_dir) {
522 argv[i++] = base_dir;
523 }
Calin Juravle52c45822017-07-13 22:50:21 -0700524 if (class_loader_context != nullptr) {
525 argv[i++] = class_loader_context_arg;
526 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700527 if (generate_minidebug_info) {
528 argv[i++] = kMinidebugDex2oatFlag;
529 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800530 if (disable_cdex) {
531 argv[i++] = kDisableCompactDexFlag;
532 }
David Brazdil570d3982018-01-16 20:15:43 +0000533 if (target_sdk_version != 0) {
534 argv[i++] = RUNTIME_ARG;
535 argv[i++] = target_sdk_version_arg;
536 }
David Brazdil52249162018-02-12 18:04:59 -0800537 if (enable_hidden_api_checks) {
David Brazdil7fcbb812018-01-17 17:05:40 +0000538 argv[i++] = RUNTIME_ARG;
David Brazdil52249162018-02-12 18:04:59 -0800539 argv[i++] = "-Xhidden-api-checks";
David Brazdil7fcbb812018-01-17 17:05:40 +0000540 }
Calin Juravle52c45822017-07-13 22:50:21 -0700541
Calin Juravle62c5a372018-02-01 17:03:23 +0000542 if (dex_metadata_fd > -1) {
543 argv[i++] = dex_metadata_fd_arg.c_str();
544 }
Calin Juravle2efc4022018-02-13 18:31:32 -0800545
546 if(compilation_reason != nullptr) {
547 argv[i++] = compilation_reason_arg.c_str();
548 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700549 // Do not add after dex2oat_flags, they should override others for debugging.
550 argv[i] = NULL;
551
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700552 execv(dex2oat_bin, (char * const *)argv);
553 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700554}
555
556/*
557 * Whether dexopt should use a swap file when compiling an APK.
558 *
559 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
560 * itself, anyways).
561 *
562 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
563 *
564 * Otherwise, return true if this is a low-mem device.
565 *
566 * Otherwise, return default value.
567 */
568static bool kAlwaysProvideSwapFile = false;
569static bool kDefaultProvideSwapFile = true;
570
571static bool ShouldUseSwapFileForDexopt() {
572 if (kAlwaysProvideSwapFile) {
573 return true;
574 }
575
576 // Check the "override" property. If it exists, return value == "true".
577 char dex2oat_prop_buf[kPropertyValueMax];
578 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
579 if (strcmp(dex2oat_prop_buf, "true") == 0) {
580 return true;
581 } else {
582 return false;
583 }
584 }
585
586 // Shortcut for default value. This is an implementation optimization for the process sketched
587 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
588 // as low-mem is never returning false. The compiler will optimize this away if it can.
589 if (kDefaultProvideSwapFile) {
590 return true;
591 }
592
593 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
594 if (is_low_mem) {
595 return true;
596 }
597
598 // Default value must be false here.
599 return kDefaultProvideSwapFile;
600}
601
Richard Uhler76cc0272016-12-08 10:46:35 +0000602static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700603 if (set_to_bg) {
604 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
605 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
606 exit(70);
607 }
608 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
609 ALOGE("setpriority failed: %s\n", strerror(errno));
610 exit(71);
611 }
612 }
613}
614
Calin Juravle29591732017-11-20 17:46:19 -0800615static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
616 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800617 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800618 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800619 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800620 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800621 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700622 }
Calin Juravle114f0812017-03-08 19:05:07 -0800623 // Profiles should belong to the app; make sure of that by giving ownership to
624 // the app uid. If we cannot do that, there's no point in returning the fd
625 // since dex2oat/profman will fail with SElinux denials.
626 if (fchown(fd.get(), uid, uid) < 0) {
627 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800628 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800629 }
Calin Juravle29591732017-11-20 17:46:19 -0800630 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800631}
632
Calin Juravle29591732017-11-20 17:46:19 -0800633static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800634 // Do not follow symlinks when opening a profile:
635 // - primary profiles should not contain symlinks in their paths
636 // - secondary dex paths should have been already resolved and validated
637 flags |= O_NOFOLLOW;
638
Calin Juravle29591732017-11-20 17:46:19 -0800639 // Check if we need to create the profile
640 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
641 unique_fd fd;
642 if ((flags & O_CREAT) != 0) {
643 fd = create_profile(uid, profile, flags);
644 } else {
645 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
646 }
647
Calin Juravle114f0812017-03-08 19:05:07 -0800648 if (fd.get() < 0) {
649 if (errno != ENOENT) {
650 // Profiles might be missing for various reasons. For example, in a
651 // multi-user environment, the profile directory for one user can be created
652 // after we start a merge. In this case the current profile for that user
653 // will not be found.
654 // Also, the secondary dex profiles might be deleted by the app at any time,
655 // so we can't we need to prepare if they are missing.
656 PLOG(ERROR) << "Failed to open profile " << profile;
657 }
658 return invalid_unique_fd();
659 }
660
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 return fd;
662}
663
Calin Juravle824a64d2018-01-18 20:23:17 -0800664static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
665 const std::string& location, bool is_secondary_dex) {
666 std::string profile = create_current_profile_path(user, package_name, location,
667 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800668 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800669}
670
Calin Juravle824a64d2018-01-18 20:23:17 -0800671static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
672 const std::string& location, bool read_write, bool is_secondary_dex) {
673 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800674 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
675}
676
677static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800678 const std::string& location) {
679 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800680 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800681}
682
Calin Juravle824a64d2018-01-18 20:23:17 -0800683static void open_profile_files(uid_t uid, const std::string& package_name,
684 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800685 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700686 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800687 *reference_profile_fd = open_reference_profile(uid, package_name, location,
688 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700689
Calin Juravle114f0812017-03-08 19:05:07 -0800690 // For secondary dex files, we don't really need the user but we use it for sanity checks.
691 // Note: the user owning the dex file should be the current user.
692 std::vector<userid_t> users;
693 if (is_secondary_dex){
694 users.push_back(multiuser_get_user_id(uid));
695 } else {
696 users = get_known_users(/*volume_uuid*/ nullptr);
697 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700698 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800699 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
700 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800702 if (profile_fd.get() >= 0) {
703 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700704 }
705 }
706}
707
708static void drop_capabilities(uid_t uid) {
709 if (setgid(uid) != 0) {
710 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
711 exit(64);
712 }
713 if (setuid(uid) != 0) {
714 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
715 exit(65);
716 }
717 // drop capabilities
718 struct __user_cap_header_struct capheader;
719 struct __user_cap_data_struct capdata[2];
720 memset(&capheader, 0, sizeof(capheader));
721 memset(&capdata, 0, sizeof(capdata));
722 capheader.version = _LINUX_CAPABILITY_VERSION_3;
723 if (capset(&capheader, &capdata[0]) < 0) {
724 ALOGE("capset failed: %s\n", strerror(errno));
725 exit(66);
726 }
727}
728
729static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
730static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
731static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
732static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
733static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
734
Calin Juravlef63d4792018-01-30 17:43:34 +0000735static void run_profman(const std::vector<unique_fd>& profile_fds,
736 const unique_fd& reference_profile_fd,
737 const std::vector<unique_fd>* apk_fds,
738 bool copy_and_update) {
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700739 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700740
Calin Juravlef63d4792018-01-30 17:43:34 +0000741 if (copy_and_update) {
742 CHECK_EQ(1u, profile_fds.size());
743 CHECK(apk_fds != nullptr);
744 CHECK_EQ(1u, apk_fds->size());
745 }
746 std::vector<std::string> profile_args(profile_fds.size());
747 for (size_t k = 0; k < profile_fds.size(); k++) {
748 profile_args[k] = "--profile-file-fd=" + std::to_string(profile_fds[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700749 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800750 std::string reference_profile_arg = "--reference-profile-file-fd="
751 + std::to_string(reference_profile_fd.get());
752
753 std::vector<std::string> apk_args;
754 if (apk_fds != nullptr) {
755 for (size_t k = 0; k < apk_fds->size(); k++) {
756 apk_args.push_back("--apk-fd=" + std::to_string((*apk_fds)[k].get()));
757 }
758 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700759
760 // program name, reference profile fd, the final NULL and the profile fds
Calin Juravlef63d4792018-01-30 17:43:34 +0000761 const char* argv[3 + profile_args.size() + apk_args.size() + (copy_and_update ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700762 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700763 argv[i++] = profman_bin;
Calin Juravle0d0a4922018-01-23 19:54:11 -0800764 argv[i++] = reference_profile_arg.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700765 for (size_t k = 0; k < profile_args.size(); k++) {
766 argv[i++] = profile_args[k].c_str();
767 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800768 for (size_t k = 0; k < apk_args.size(); k++) {
769 argv[i++] = apk_args[k].c_str();
770 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000771 if (copy_and_update) {
772 argv[i++] = "--copy-and-update-profile-key";
773 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774 // Do not add after dex2oat_flags, they should override others for debugging.
775 argv[i] = NULL;
776
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700777 execv(profman_bin, (char * const *)argv);
778 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 exit(68); /* only get here on exec failure */
780}
781
Calin Juravlef63d4792018-01-30 17:43:34 +0000782
783static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
784 const unique_fd& reference_profile_fd,
785 const std::vector<unique_fd>* apk_fds = nullptr) {
786 run_profman(profiles_fd, reference_profile_fd, apk_fds, /*copy_and_update*/false);
787}
788
789
790static void run_profman_copy_and_update(unique_fd&& profile_fd,
791 unique_fd&& reference_profile_fd,
792 unique_fd&& apk_fd) {
793 std::vector<unique_fd> profiles_fd;
794 profiles_fd.push_back(std::move(profile_fd));
795 std::vector<unique_fd> apk_fds;
796 apk_fds.push_back(std::move(apk_fd));
797
798 run_profman(profiles_fd, reference_profile_fd, &apk_fds, /*copy_and_update*/true);
799}
800
Jeff Sharkey90aff262016-12-12 14:28:24 -0700801// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800802// The location is the package name for primary apks or the dex path for secondary dex files.
803// Returns true if there is enough information in the current profiles that makes it
804// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700805// If the return value is true all the current profiles would have been merged into
806// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800807static bool analyze_profiles(uid_t uid, const std::string& package_name,
808 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800809 std::vector<unique_fd> profiles_fd;
810 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800811 open_profile_files(uid, package_name, location, is_secondary_dex,
812 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800813 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 // Skip profile guided compilation because no profiles were found.
815 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816 return false;
817 }
818
Jeff Sharkey90aff262016-12-12 14:28:24 -0700819 pid_t pid = fork();
820 if (pid == 0) {
821 /* child -- drop privileges before continuing */
822 drop_capabilities(uid);
823 run_profman_merge(profiles_fd, reference_profile_fd);
824 exit(68); /* only get here on exec failure */
825 }
826 /* parent */
827 int return_code = wait_child(pid);
828 bool need_to_compile = false;
829 bool should_clear_current_profiles = false;
830 bool should_clear_reference_profile = false;
831 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800832 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 } else {
834 return_code = WEXITSTATUS(return_code);
835 switch (return_code) {
836 case PROFMAN_BIN_RETURN_CODE_COMPILE:
837 need_to_compile = true;
838 should_clear_current_profiles = true;
839 should_clear_reference_profile = false;
840 break;
841 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
842 need_to_compile = false;
843 should_clear_current_profiles = false;
844 should_clear_reference_profile = false;
845 break;
846 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800847 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700848 need_to_compile = false;
849 should_clear_current_profiles = true;
850 should_clear_reference_profile = true;
851 break;
852 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
853 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
854 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800855 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856 need_to_compile = false;
857 should_clear_current_profiles = false;
858 should_clear_reference_profile = false;
859 break;
860 default:
861 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800862 LOG(WARNING) << "Unknown error code while processing profiles for location "
863 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700864 need_to_compile = false;
865 should_clear_current_profiles = true;
866 should_clear_reference_profile = true;
867 break;
868 }
869 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800870
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800872 if (is_secondary_dex) {
873 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800874 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
875 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800876 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800877 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800878 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879 }
880 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800881 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700882 }
883 return need_to_compile;
884}
885
Calin Juravle114f0812017-03-08 19:05:07 -0800886// Decides if profile guided compilation is needed or not based on existing profiles.
887// The analysis is done for the primary apks of the given package.
888// Returns true if there is enough information in the current profiles that makes it
889// worth to recompile the package.
890// If the return value is true all the current profiles would have been merged into
891// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800892bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
893 const std::string& profile_name) {
894 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800895}
896
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800897static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
898 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700899 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800900 const std::vector<unique_fd>& apk_fds,
901 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 std::vector<std::string> profman_args;
903 static const char* PROFMAN_BIN = "/system/bin/profman";
904 profman_args.push_back(PROFMAN_BIN);
905 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800906 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700907 if (reference_profile_fd != -1) {
908 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800909 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800911 for (size_t i = 0; i < profile_fds.size(); i++) {
912 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700913 }
914 for (const std::string& dex_location : dex_locations) {
915 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
916 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800917 for (size_t i = 0; i < apk_fds.size(); i++) {
918 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700919 }
920 const char **argv = new const char*[profman_args.size() + 1];
921 size_t i = 0;
922 for (const std::string& profman_arg : profman_args) {
923 argv[i++] = profman_arg.c_str();
924 }
925 argv[i] = NULL;
926
927 execv(PROFMAN_BIN, (char * const *)argv);
928 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
929 exit(68); /* only get here on exec failure */
930}
931
Calin Juravle408cd4a2018-01-20 23:34:18 -0800932bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
933 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800934 std::vector<unique_fd> profile_fds;
935 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800936 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
937 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700938
Calin Juravle408cd4a2018-01-20 23:34:18 -0800939 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800940 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700941
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800942 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700943 const bool has_profiles = !profile_fds.empty();
944
945 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800946 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700947 return false;
948 }
949
Calin Juravle114f0812017-03-08 19:05:07 -0800950 unique_fd output_fd(open(out_file_name.c_str(),
951 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700952 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800953 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954 return false;
955 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800956
Jeff Sharkey90aff262016-12-12 14:28:24 -0700957 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800958 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800959 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
960 if (apk_fd == -1) {
961 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
962 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700963 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800964 dex_locations.push_back(get_location_from_path(code_path.c_str()));
965 apk_fds.push_back(std::move(apk_fd));
966
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967
968 pid_t pid = fork();
969 if (pid == 0) {
970 /* child -- drop privileges before continuing */
971 drop_capabilities(uid);
972 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
973 apk_fds, output_fd);
974 exit(68); /* only get here on exec failure */
975 }
976 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700977 int return_code = wait_child(pid);
978 if (!WIFEXITED(return_code)) {
979 LOG(WARNING) << "profman failed for package " << pkgname << ": "
980 << return_code;
981 return false;
982 }
983 return true;
984}
985
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700986bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -0800987 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700988 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
989 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -0800990 package_name,
991 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700992 /*read_write*/ true,
993 /*secondary*/ false));
994 if (in_fd.get() < 0) {
995 PLOG(WARNING) << "Could not open profile " << system_profile;
996 return false;
997 }
998 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800999 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001000 return false;
1001 }
1002
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001003 // As a security measure we want to write the profile information with the reduced capabilities
1004 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001005 pid_t pid = fork();
1006 if (pid == 0) {
1007 /* child -- drop privileges before continuing */
1008 drop_capabilities(packageUid);
1009
1010 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1011 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001012 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001013 }
1014 // This implies that the app owning this profile is running
1015 // (and has acquired the lock).
1016 //
1017 // The app never acquires the lock for the reference profiles of primary apks.
1018 // Only dex2oat from installd will do that. Since installd is single threaded
1019 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001020 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001021 return false;
1022 }
1023
1024 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1025 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001026 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001027 }
1028
1029 // Copy over data.
1030 static constexpr size_t kBufferSize = 4 * 1024;
1031 char buffer[kBufferSize];
1032 while (true) {
1033 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1034 if (bytes == 0) {
1035 break;
1036 }
1037 write(out_fd.get(), buffer, bytes);
1038 }
1039 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001040 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001041 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001042 // Use _exit since we don't want to run the global destructors in the child.
1043 // b/62597429
1044 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001045 }
1046 /* parent */
1047 int return_code = wait_child(pid);
1048 return return_code == 0;
1049}
1050
Jeff Sharkey90aff262016-12-12 14:28:24 -07001051static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1052 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1053 if (EndsWith(oat_path, ".dex")) {
1054 std::string new_path = oat_path;
1055 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001056 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001057 return new_path;
1058 }
1059
1060 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1061 // case (where the base name will have an extension for the B artifact).
1062 size_t odex_pos = oat_path.rfind(".odex");
1063 if (odex_pos != std::string::npos) {
1064 std::string new_path = oat_path;
1065 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1066 CHECK_NE(new_path.find(new_ext), std::string::npos);
1067 return new_path;
1068 }
1069
1070 // Don't know how to handle this.
1071 return "";
1072}
1073
1074// Translate the given oat path to an art (app image) path. An empty string
1075// denotes an error.
1076static std::string create_image_filename(const std::string& oat_path) {
1077 return replace_file_extension(oat_path, ".art");
1078}
1079
1080// Translate the given oat path to a vdex path. An empty string denotes an error.
1081static std::string create_vdex_filename(const std::string& oat_path) {
1082 return replace_file_extension(oat_path, ".vdex");
1083}
1084
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085static int open_output_file(const char* file_name, bool recreate, int permissions) {
1086 int flags = O_RDWR | O_CREAT;
1087 if (recreate) {
1088 if (unlink(file_name) < 0) {
1089 if (errno != ENOENT) {
1090 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1091 }
1092 }
1093 flags |= O_EXCL;
1094 }
1095 return open(file_name, flags, permissions);
1096}
1097
Calin Juravle2289c0a2017-02-15 12:44:14 -08001098static bool set_permissions_and_ownership(
1099 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1100 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1101 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001102 if (fchmod(fd,
1103 S_IRUSR|S_IWUSR|S_IRGRP |
1104 (is_public ? S_IROTH : 0)) < 0) {
1105 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1106 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001107 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001108 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1109 return false;
1110 }
1111 return true;
1112}
1113
1114static bool IsOutputDalvikCache(const char* oat_dir) {
1115 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1116 // into '!'. Play it safe by handling it both.
1117 // TODO: ensure we never get null.
1118 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1119 return oat_dir == nullptr || oat_dir[0] == '!';
1120}
1121
Calin Juravled23dee72017-07-06 16:29:11 -07001122// Best-effort check whether we can fit the the path into our buffers.
1123// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1124// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1125// extension to the cache path (5 bytes).
1126// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1127static bool validate_dex_path_size(const std::string& dex_path) {
1128 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1129 LOG(ERROR) << "dex_path too long: " << dex_path;
1130 return false;
1131 }
1132 return true;
1133}
1134
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001136 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001137 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001138 return false;
1139 }
1140
1141 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001142 // Oat dirs for secondary dex files are already validated.
1143 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001144 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1145 return false;
1146 }
1147 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1148 return false;
1149 }
1150 } else {
1151 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1152 return false;
1153 }
1154 }
1155 return true;
1156}
1157
1158// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1159// on destruction. It will also run the given cleanup (unless told not to) after closing.
1160//
1161// Usage example:
1162//
Calin Juravle7a570e82017-01-14 16:23:30 -08001163// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001164// [name]() {
1165// unlink(name.c_str());
1166// });
1167// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1168// wrapper if captured as a reference.
1169//
1170// if (file.get() == -1) {
1171// // Error opening...
1172// }
1173//
1174// ...
1175// if (error) {
1176// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1177// // and delete the file (after the fd is closed).
1178// return -1;
1179// }
1180//
1181// (Success case)
1182// file.SetCleanup(false);
1183// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1184// // (leaving the file around; after the fd is closed).
1185//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001186class Dex2oatFileWrapper {
1187 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001188 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001189 }
1190
Calin Juravle7a570e82017-01-14 16:23:30 -08001191 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1192 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1193
1194 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1195 value_ = other.value_;
1196 cleanup_ = other.cleanup_;
1197 do_cleanup_ = other.do_cleanup_;
1198 auto_close_ = other.auto_close_;
1199 other.release();
1200 }
1201
1202 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1203 value_ = other.value_;
1204 cleanup_ = other.cleanup_;
1205 do_cleanup_ = other.do_cleanup_;
1206 auto_close_ = other.auto_close_;
1207 other.release();
1208 return *this;
1209 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001210
1211 ~Dex2oatFileWrapper() {
1212 reset(-1);
1213 }
1214
1215 int get() {
1216 return value_;
1217 }
1218
1219 void SetCleanup(bool cleanup) {
1220 do_cleanup_ = cleanup;
1221 }
1222
1223 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001224 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001225 close(value_);
1226 }
1227 if (do_cleanup_ && cleanup_ != nullptr) {
1228 cleanup_();
1229 }
1230
1231 value_ = new_value;
1232 }
1233
Calin Juravle7a570e82017-01-14 16:23:30 -08001234 void reset(int new_value, std::function<void ()> new_cleanup) {
1235 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001236 close(value_);
1237 }
1238 if (do_cleanup_ && cleanup_ != nullptr) {
1239 cleanup_();
1240 }
1241
1242 value_ = new_value;
1243 cleanup_ = new_cleanup;
1244 }
1245
Calin Juravle7a570e82017-01-14 16:23:30 -08001246 void DisableAutoClose() {
1247 auto_close_ = false;
1248 }
1249
Jeff Sharkey90aff262016-12-12 14:28:24 -07001250 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001251 void release() {
1252 value_ = -1;
1253 do_cleanup_ = false;
1254 cleanup_ = nullptr;
1255 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001256 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001257 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001258 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001259 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260};
1261
Calin Juravle7a570e82017-01-14 16:23:30 -08001262// (re)Creates the app image if needed.
1263Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001264 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001265
1266 // We don't create an image for secondary dex files.
1267 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001268 return Dex2oatFileWrapper();
1269 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001270
Calin Juravle7a570e82017-01-14 16:23:30 -08001271 const std::string image_path = create_image_filename(out_oat_path);
1272 if (image_path.empty()) {
1273 // Happens when the out_oat_path has an unknown extension.
1274 return Dex2oatFileWrapper();
1275 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001276
1277 // Use app images only if it is enabled (by a set image format) and we are compiling
1278 // profile-guided (so the app image doesn't conservatively contain all classes).
1279 if (!profile_guided) {
1280 // In case there is a stale image, remove it now. Ignore any error.
1281 unlink(image_path.c_str());
1282 return Dex2oatFileWrapper();
1283 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001284 char app_image_format[kPropertyValueMax];
1285 bool have_app_image_format =
1286 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1287 if (!have_app_image_format) {
1288 return Dex2oatFileWrapper();
1289 }
1290 // Recreate is true since we do not want to modify a mapped image. If the app is
1291 // already running and we modify the image file, it can cause crashes (b/27493510).
1292 Dex2oatFileWrapper wrapper_fd(
1293 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1294 [image_path]() { unlink(image_path.c_str()); });
1295 if (wrapper_fd.get() < 0) {
1296 // Could not create application image file. Go on since we can compile without it.
1297 LOG(ERROR) << "installd could not create '" << image_path
1298 << "' for image file during dexopt";
1299 // If we have a valid image file path but no image fd, explicitly erase the image file.
1300 if (unlink(image_path.c_str()) < 0) {
1301 if (errno != ENOENT) {
1302 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1303 }
1304 }
1305 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001306 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001307 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1308 wrapper_fd.reset(-1);
1309 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001310
Calin Juravle7a570e82017-01-14 16:23:30 -08001311 return wrapper_fd;
1312}
1313
1314// Creates the dexopt swap file if necessary and return its fd.
1315// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001316unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001317 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001318 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001319 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001320 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001321 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001322 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001323 if (swap_fd.get() < 0) {
1324 // Could not create swap file. Optimistically go on and hope that we can compile
1325 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001326 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001327 } else {
1328 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001329 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001330 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1331 }
1332 }
1333 return swap_fd;
1334}
1335
1336// Opens the reference profiles if needed.
1337// 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 -08001338Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001339 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001340 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001341 // If we are not profile guided compilation, or we are compiling system server
1342 // do not bother to open the profiles; we won't be using them.
1343 if (!profile_guided || (pkgname[0] == '*')) {
1344 return Dex2oatFileWrapper();
1345 }
1346
1347 // If this is a secondary dex path which is public do not open the profile.
1348 // We cannot compile public secondary dex paths with profiles. That's because
1349 // it will expose how the dex files are used by their owner.
1350 //
1351 // Note that the PackageManager is responsible to set the is_public flag for
1352 // primary apks and we do not check it here. In some cases, e.g. when
1353 // compiling with a public profile from the .dm file the PackageManager will
1354 // set is_public toghether with the profile guided compilation.
1355 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001356 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001357 }
Calin Juravle114f0812017-03-08 19:05:07 -08001358
1359 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001360 std::string location;
1361 if (is_secondary_dex) {
1362 location = dex_path;
1363 } else {
1364 if (profile_name == nullptr) {
1365 // This path is taken for system server re-compilation lunched from ZygoteInit.
1366 return Dex2oatFileWrapper();
1367 } else {
1368 location = profile_name;
1369 }
1370 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001371 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1372 is_secondary_dex);
1373 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1374 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001375 };
1376 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001377}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001378
Calin Juravle7a570e82017-01-14 16:23:30 -08001379// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1380// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001381bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001382 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001383 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001384 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1385 CHECK(in_vdex_wrapper_fd != nullptr);
1386 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001387 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1388 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001389 char in_odex_path[PKG_PATH_MAX];
1390 int dexopt_action = abs(dexopt_needed);
1391 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001392 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001393
1394 // Infer the name of the output VDEX.
1395 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1396 if (out_vdex_path_str.empty()) {
1397 return false;
1398 }
1399
1400 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001401 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001402 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1403 const char* path = nullptr;
1404 if (is_odex_location) {
1405 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1406 path = in_odex_path;
1407 } else {
1408 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001409 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001410 }
1411 } else {
1412 path = out_oat_path;
1413 }
1414 in_vdex_path_str = create_vdex_filename(path);
1415 if (in_vdex_path_str.empty()) {
1416 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001417 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001418 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001419 // We can update in place when all these conditions are met:
1420 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1421 // on /system typically cannot be updated in place).
1422 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1423 // cannot be currently used by a running process.
1424 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1425 // different vdex files to operate.
1426 update_vdex_in_place =
1427 (in_vdex_path_str == out_vdex_path_str) &&
1428 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1429 !profile_guided;
1430 if (update_vdex_in_place) {
1431 // Open the file read-write to be able to update it.
1432 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1433 if (in_vdex_wrapper_fd->get() == -1) {
1434 // If we failed to open the file, we cannot update it in place.
1435 update_vdex_in_place = false;
1436 }
1437 } else {
1438 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1439 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001440 }
1441
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001442 // If we are updating the vdex in place, we do not need to recreate a vdex,
1443 // and can use the same existing one.
1444 if (update_vdex_in_place) {
1445 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1446 // have bogus stale vdex files.
1447 out_vdex_wrapper_fd->reset(
1448 in_vdex_wrapper_fd->get(),
1449 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1450 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1451 // wrapper).
1452 in_vdex_wrapper_fd->DisableAutoClose();
1453 } else {
1454 out_vdex_wrapper_fd->reset(
1455 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1456 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1457 if (out_vdex_wrapper_fd->get() < 0) {
1458 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1459 return false;
1460 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001461 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001462 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001463 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001464 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1465 return false;
1466 }
1467
1468 // If we got here we successfully opened the vdex files.
1469 return true;
1470}
1471
1472// Opens the output oat file for the given apk.
1473// If successful it stores the output path into out_oat_path and returns true.
1474Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001475 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1476 char* out_oat_path) {
1477 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001478 return Dex2oatFileWrapper();
1479 }
1480 const std::string out_oat_path_str(out_oat_path);
1481 Dex2oatFileWrapper wrapper_fd(
1482 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1483 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1484 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001485 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001486 } else if (!set_permissions_and_ownership(
1487 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001488 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1489 wrapper_fd.reset(-1);
1490 }
1491 return wrapper_fd;
1492}
1493
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001494// Creates RDONLY fds for oat and vdex files, if exist.
1495// Returns false if it fails to create oat out path for the given apk path.
1496// Note that the method returns true even if the files could not be opened.
1497bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1498 const std::string& oat_dir,
1499 const std::string& instruction_set,
1500 bool is_secondary_dex,
1501 unique_fd* oat_file_fd,
1502 unique_fd* vdex_file_fd) {
1503 char oat_path[PKG_PATH_MAX];
1504 if (!create_oat_out_path(apk_path.c_str(),
1505 instruction_set.c_str(),
1506 oat_dir.c_str(),
1507 is_secondary_dex,
1508 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001509 LOG(ERROR) << "Could not create oat out path for "
1510 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001511 return false;
1512 }
1513 oat_file_fd->reset(open(oat_path, O_RDONLY));
1514 if (oat_file_fd->get() < 0) {
1515 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1516 }
1517
1518 std::string vdex_filename = create_vdex_filename(oat_path);
1519 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1520 if (vdex_file_fd->get() < 0) {
1521 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1522 }
1523
1524 return true;
1525}
1526
Calin Juravle7a570e82017-01-14 16:23:30 -08001527// Updates the access times of out_oat_path based on those from apk_path.
1528void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1529 struct stat input_stat;
1530 memset(&input_stat, 0, sizeof(input_stat));
1531 if (stat(apk_path, &input_stat) != 0) {
1532 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1533 return;
1534 }
1535
1536 struct utimbuf ut;
1537 ut.actime = input_stat.st_atime;
1538 ut.modtime = input_stat.st_mtime;
1539 if (utime(out_oat_path, &ut) != 0) {
1540 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1541 }
1542}
1543
Calin Juravle80a21252017-01-17 14:43:25 -08001544// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001545// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1546// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1547// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001548static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1549 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1550 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001551 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001552 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001553 const char* dexoptanalyzer_bin =
1554 is_debug_runtime()
1555 ? "/system/bin/dexoptanalyzerd"
1556 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001557 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1558
Calin Juravled23dee72017-07-06 16:29:11 -07001559 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1560 LOG(ERROR) << "Instruction set " << instruction_set
1561 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001562 return;
1563 }
1564
Calin Juravled23dee72017-07-06 16:29:11 -07001565 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001566 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1567 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1568 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001569 std::string isa_arg = "--isa=" + instruction_set;
1570 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001571 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001572 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001573 std::string class_loader_context_arg = "--class-loader-context=";
1574 if (class_loader_context != nullptr) {
1575 class_loader_context_arg += class_loader_context;
1576 }
Calin Juravle80a21252017-01-17 14:43:25 -08001577
Calin Juravle80a21252017-01-17 14:43:25 -08001578 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001579 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001580 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001581 (vdex_fd >= 0 ? 1 : 0) +
1582 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001583 (downgrade ? 1 : 0) +
1584 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001585 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001586 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001587 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001588 argv[i++] = dex_file_arg.c_str();
1589 argv[i++] = isa_arg.c_str();
1590 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001591 if (oat_fd >= 0) {
1592 argv[i++] = oat_fd_arg.c_str();
1593 }
1594 if (vdex_fd >= 0) {
1595 argv[i++] = vdex_fd_arg.c_str();
1596 }
1597 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001598 if (profile_was_updated) {
1599 argv[i++] = assume_profile_changed;
1600 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001601 if (downgrade) {
1602 argv[i++] = downgrade_flag;
1603 }
Calin Juravle58cab072017-09-12 01:02:26 -07001604 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001605 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001606 }
Calin Juravle80a21252017-01-17 14:43:25 -08001607 argv[i] = NULL;
1608
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001609 execv(dexoptanalyzer_bin, (char * const *)argv);
1610 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001611}
1612
1613// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001614static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001615 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001616 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001617 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001618 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001619 return false;
1620 }
Calin Juravle114f0812017-03-08 19:05:07 -08001621 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001622
Calin Juravle80a21252017-01-17 14:43:25 -08001623 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001624 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1625 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001626 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001627 return false;
1628 }
1629
1630 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001631 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001632
Calin Juravle7d765462017-09-04 15:57:10 -07001633 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001634 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001635 return false;
1636 }
1637
1638 return true;
1639}
1640
Calin Juravle7d765462017-09-04 15:57:10 -07001641// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1642// secondary dex files. This return codes are returned by the child process created for
1643// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001644
Calin Juravle7d765462017-09-04 15:57:10 -07001645// The dexoptanalyzer was not invoked because of validation or IO errors.
1646static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1647// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1648static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1649
1650// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001651// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1652// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001653// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1654// of dexoptanalyzer.
1655static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001656 int* dexopt_needed_out) {
1657 // The result values are defined in dexoptanalyzer.
1658 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001659 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001660 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001661 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001662 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001663 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001664 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001665 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001666 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001667 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001668 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001669 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1670 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1671 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001672 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1673 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001674 << " : dexoptanalyzer result=" << result;
1675 return false;
Calin Juravle7d765462017-09-04 15:57:10 -07001676 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1677 // If the file does not exist there's no need for dexopt.
1678 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1679 return true;
1680 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1681 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001682 default:
Calin Juravle7d765462017-09-04 15:57:10 -07001683 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1684 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001685 return false;
1686 }
1687}
1688
Calin Juravle7d765462017-09-04 15:57:10 -07001689enum SecondaryDexAccess {
1690 kSecondaryDexAccessReadOk = 0,
1691 kSecondaryDexAccessDoesNotExist = 1,
1692 kSecondaryDexAccessPermissionError = 2,
1693 kSecondaryDexAccessIOError = 3
1694};
1695
1696static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1697 // Check if the path exists and can be read. If not, there's nothing to do.
1698 if (access(dex_path.c_str(), R_OK) == 0) {
1699 return kSecondaryDexAccessReadOk;
1700 } else {
1701 if (errno == ENOENT) {
1702 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1703 return kSecondaryDexAccessDoesNotExist;
1704 } else {
1705 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1706 return errno == EACCES
1707 ? kSecondaryDexAccessPermissionError
1708 : kSecondaryDexAccessIOError;
1709 }
1710 }
1711}
1712
1713static bool is_file_public(const std::string& filename) {
1714 struct stat file_stat;
1715 if (stat(filename.c_str(), &file_stat) == 0) {
1716 return (file_stat.st_mode & S_IROTH) != 0;
1717 }
1718 return false;
1719}
1720
1721// Create the oat file structure for the secondary dex 'dex_path' and assign
1722// the individual path component to the 'out_' parameters.
1723static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1724 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1725 size_t dirIndex = dex_path.rfind('/');
1726 if (dirIndex == std::string::npos) {
1727 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1728 return false;
1729 }
1730 // TODO(calin): we have similar computations in at lest 3 other places
1731 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1732 // using string append.
1733 std::string apk_dir = dex_path.substr(0, dirIndex);
1734 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1735 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1736
1737 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1738 /*is_secondary_dex*/true, out_oat_path)) {
1739 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1740 return false;
1741 }
1742 return true;
1743}
1744
1745// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1746// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1747static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1748 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1749 *out_storage_flag = FLAG_STORAGE_CE;
1750 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1751 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1752 return false;
1753 }
1754 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1755 *out_storage_flag = FLAG_STORAGE_DE;
1756 } else {
1757 LOG(ERROR) << "Secondary dex storage flag must be set";
1758 return false;
1759 }
1760 return true;
1761}
1762
Calin Juravlec9eab382017-01-25 01:17:17 -08001763// 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 -08001764// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1765// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001766// When returning true, the output parameters will be:
1767// - is_public_out: whether or not the oat file should not be made public
1768// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1769// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001770static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001771 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001772 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle7d765462017-09-04 15:57:10 -07001773 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1774 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001775 int storage_flag;
Calin Juravle7d765462017-09-04 15:57:10 -07001776 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001777 return false;
1778 }
Calin Juravle7d765462017-09-04 15:57:10 -07001779 // Compute the oat dir as it's not easy to extract it from the child computation.
1780 char oat_path[PKG_PATH_MAX];
1781 char oat_dir[PKG_PATH_MAX];
1782 char oat_isa_dir[PKG_PATH_MAX];
1783 if (!create_secondary_dex_oat_layout(
1784 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1785 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001786 return false;
1787 }
Calin Juravle7d765462017-09-04 15:57:10 -07001788 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001789
Calin Juravle80a21252017-01-17 14:43:25 -08001790 pid_t pid = fork();
1791 if (pid == 0) {
1792 // child -- drop privileges before continuing.
1793 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001794
1795 // Validate the path structure.
1796 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1797 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1798 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1799 }
1800
1801 // Open the dex file.
1802 unique_fd zip_fd;
1803 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1804 if (zip_fd.get() < 0) {
1805 if (errno == ENOENT) {
1806 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1807 } else {
1808 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1809 }
1810 }
1811
1812 // Prepare the oat directories.
1813 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1814 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1815 }
1816
1817 // Open the vdex/oat files if any.
1818 unique_fd oat_file_fd;
1819 unique_fd vdex_file_fd;
1820 if (!maybe_open_oat_and_vdex_file(dex_path,
1821 *oat_dir_out,
1822 instruction_set,
1823 true /* is_secondary_dex */,
1824 &oat_file_fd,
1825 &vdex_file_fd)) {
1826 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1827 }
1828
1829 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001830 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1831 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001832
1833 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001834 exec_dexoptanalyzer(dex_path,
1835 vdex_file_fd.get(),
1836 oat_file_fd.get(),
1837 zip_fd.get(),
1838 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001839 compiler_filter, profile_was_updated,
1840 downgrade,
1841 class_loader_context);
1842 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1843 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001844 }
1845
1846 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001847 int result = wait_child(pid);
1848 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001849 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001850 return false;
1851 }
1852 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001853 // Check that we successfully executed dexoptanalyzer.
1854 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1855
1856 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1857
Calin Juravle80a21252017-01-17 14:43:25 -08001858 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001859 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1860 // makes the code simpler; force compilation is only needed during tests).
1861 if (success &&
1862 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1863 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001864 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1865 }
1866
Calin Juravle7d765462017-09-04 15:57:10 -07001867 // Check if we should make the oat file public.
1868 // Note that if the dex file is not public the compiled code cannot be made public.
1869 // It is ok to check this flag outside in the parent process.
1870 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1871
Calin Juravle80a21252017-01-17 14:43:25 -08001872 return success;
1873}
1874
Andreas Gampe023b2242018-02-28 16:03:25 -08001875static std::string format_dexopt_error(int retcode, const char* dex_path) {
1876 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, retcode);
1877}
1878
Calin Juravlec9eab382017-01-25 01:17:17 -08001879int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001880 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001881 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001882 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001883 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001884 CHECK(pkgname != nullptr);
1885 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001886 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001887 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1888 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001889
Calin Juravled23dee72017-07-06 16:29:11 -07001890 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001891 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001892 return -1;
1893 }
1894
1895 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001896 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1897 class_loader_context);
1898 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001899 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001900 }
1901
Calin Juravleebc8a792017-04-04 20:21:05 -07001902 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001903 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1904 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1905 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001906 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001907 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001908 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001909
1910 // Check if we're dealing with a secondary dex file and if we need to compile it.
1911 std::string oat_dir_str;
1912 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001913 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001914 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle7d765462017-09-04 15:57:10 -07001915 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001916 oat_dir = oat_dir_str.c_str();
1917 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1918 return 0; // Nothing to do, report success.
1919 }
1920 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08001921 *error_msg = "Failed processing secondary.";
Calin Juravle80a21252017-01-17 14:43:25 -08001922 return -1; // We had an error, logged in the process method.
1923 }
1924 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001925 // Currently these flags are only use for secondary dex files.
1926 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001927 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1928 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1929 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001930
1931 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001932 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001933 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001934 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1935 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08001936 return -1;
1937 }
1938
1939 // Create the output OAT file.
1940 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001941 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001942 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001943 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001944 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08001945 return -1;
1946 }
1947
1948 // Open vdex files.
1949 Dex2oatFileWrapper in_vdex_fd;
1950 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001951 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1952 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001953 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001954 return -1;
1955 }
1956
Calin Juravlecb556e32017-04-04 20:22:50 -07001957 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1958 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1959 // fully inherit their parent context).
1960 // Note that for primary apk the oat files are created before, in a separate installd
1961 // call which also does the restorecon. TODO(calin): unify the paths.
1962 if (is_secondary_dex) {
1963 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1964 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001965 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1966 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07001967 return -1;
1968 }
1969 }
1970
Jeff Sharkey90aff262016-12-12 14:28:24 -07001971 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001972 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001973
Calin Juravle7a570e82017-01-14 16:23:30 -08001974 // Create the app image file if needed.
1975 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001976 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001977
Calin Juravle7a570e82017-01-14 16:23:30 -08001978 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001979 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08001980 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001981
Calin Juravle62c5a372018-02-01 17:03:23 +00001982 unique_fd dex_metadata_fd;
1983 if (dex_metadata_path != nullptr) {
1984 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
1985 if (dex_metadata_fd.get() < 0) {
1986 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1987 }
1988 }
1989
Andreas Gampe023b2242018-02-28 16:03:25 -08001990 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07001991
1992 pid_t pid = fork();
1993 if (pid == 0) {
1994 /* child -- drop privileges before continuing */
1995 drop_capabilities(uid);
1996
Richard Uhler76cc0272016-12-08 10:46:35 +00001997 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001998 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001999 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002000 _exit(67);
2001 }
2002
Richard Uhler76cc0272016-12-08 10:46:35 +00002003 run_dex2oat(input_fd.get(),
2004 out_oat_fd.get(),
2005 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08002006 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00002007 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07002008 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00002009 out_oat_path,
2010 swap_fd.get(),
2011 instruction_set,
2012 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00002013 debuggable,
2014 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002015 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00002016 reference_profile_fd.get(),
David Brazdil570d3982018-01-16 20:15:43 +00002017 class_loader_context,
David Brazdil7fcbb812018-01-17 17:05:40 +00002018 target_sdk_version,
Calin Juravle62c5a372018-02-01 17:03:23 +00002019 enable_hidden_api_checks,
Calin Juravle2efc4022018-02-13 18:31:32 -08002020 dex_metadata_fd.get(),
2021 compilation_reason);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002022 _exit(68); /* only get here on exec failure */
2023 } else {
2024 int res = wait_child(pid);
2025 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002026 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002027 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002028 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2029 << std::hex << std::setw(4) << res << ", process failed";
2030 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002031 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002032 }
2033 }
2034
Calin Juravlec9eab382017-01-25 01:17:17 -08002035 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002036
2037 // We've been successful, don't delete output.
2038 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002039 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002040 image_fd.SetCleanup(false);
2041 reference_profile_fd.SetCleanup(false);
2042
2043 return 0;
2044}
2045
Calin Juravlec9eab382017-01-25 01:17:17 -08002046// Try to remove the given directory. Log an error if the directory exists
2047// and is empty but could not be removed.
2048static bool rmdir_if_empty(const char* dir) {
2049 if (rmdir(dir) == 0) {
2050 return true;
2051 }
2052 if (errno == ENOENT || errno == ENOTEMPTY) {
2053 return true;
2054 }
2055 PLOG(ERROR) << "Failed to remove dir: " << dir;
2056 return false;
2057}
2058
2059// Try to unlink the given file. Log an error if the file exists and could not
2060// be unlinked.
2061static bool unlink_if_exists(const std::string& file) {
2062 if (unlink(file.c_str()) == 0) {
2063 return true;
2064 }
2065 if (errno == ENOENT) {
2066 return true;
2067
2068 }
2069 PLOG(ERROR) << "Could not unlink: " << file;
2070 return false;
2071}
2072
Calin Juravle7d765462017-09-04 15:57:10 -07002073enum ReconcileSecondaryDexResult {
2074 kReconcileSecondaryDexExists = 0,
2075 kReconcileSecondaryDexCleanedUp = 1,
2076 kReconcileSecondaryDexValidationError = 2,
2077 kReconcileSecondaryDexCleanUpError = 3,
2078 kReconcileSecondaryDexAccessIOError = 4,
2079};
Calin Juravlec9eab382017-01-25 01:17:17 -08002080
2081// Reconcile the secondary dex 'dex_path' and its generated oat files.
2082// Return true if all the parameters are valid and the secondary dex file was
2083// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2084// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2085// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2086// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2087// Return false if there were errors during processing. In this case
2088// out_secondary_dex_exists will be set to false.
2089bool reconcile_secondary_dex_file(const std::string& dex_path,
2090 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2091 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2092 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002093 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002094 if (isas.size() == 0) {
2095 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2096 return false;
2097 }
2098
Calin Juravle7d765462017-09-04 15:57:10 -07002099 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2100 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2101 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002102 return false;
2103 }
2104
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002105 // As a security measure we want to unlink art artifacts with the reduced capabilities
2106 // of the package user id. So we fork and drop capabilities in the child.
2107 pid_t pid = fork();
2108 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002109 /* child -- drop privileges before continuing */
2110 drop_capabilities(uid);
2111
2112 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2113 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2114 uid, storage_flag)) {
2115 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2116 _exit(kReconcileSecondaryDexValidationError);
2117 }
2118
2119 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2120 switch (access_check) {
2121 case kSecondaryDexAccessDoesNotExist:
2122 // File does not exist. Proceed with cleaning.
2123 break;
2124 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2125 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2126 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2127 default:
2128 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2129 _exit(kReconcileSecondaryDexValidationError);
2130 }
2131
2132 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002133 char oat_path[PKG_PATH_MAX];
2134 char oat_dir[PKG_PATH_MAX];
2135 char oat_isa_dir[PKG_PATH_MAX];
2136 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002137 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle7d765462017-09-04 15:57:10 -07002138 if (!create_secondary_dex_oat_layout(
2139 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
2140 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
2141 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002142 }
Calin Juravle51314092017-05-18 15:33:05 -07002143
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002144 // Delete oat/vdex/art files.
2145 result = unlink_if_exists(oat_path) && result;
2146 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2147 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002148
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002149 // Delete profiles.
2150 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002151 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002152 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002153 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002154 result = unlink_if_exists(current_profile) && result;
2155 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002156
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002157 // We upgraded once the location of current profile for secondary dex files.
2158 // Check for any previous left-overs and remove them as well.
2159 std::string old_current_profile = dex_path + ".prof";
2160 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002161
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002162 // Try removing the directories as well, they might be empty.
2163 result = rmdir_if_empty(oat_isa_dir) && result;
2164 result = rmdir_if_empty(oat_dir) && result;
2165 }
Calin Juravle7d765462017-09-04 15:57:10 -07002166 if (!result) {
2167 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2168 }
2169 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002170 }
2171
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002172 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002173 if (!WIFEXITED(return_code)) {
2174 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2175 } else {
2176 return_code = WEXITSTATUS(return_code);
2177 }
2178
2179 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2180
2181 switch (return_code) {
2182 case kReconcileSecondaryDexCleanedUp:
2183 case kReconcileSecondaryDexValidationError:
2184 // If we couldn't validate assume the dex file does not exist.
2185 // This will purge the entry from the PM records.
2186 *out_secondary_dex_exists = false;
2187 return true;
2188 case kReconcileSecondaryDexExists:
2189 *out_secondary_dex_exists = true;
2190 return true;
2191 case kReconcileSecondaryDexAccessIOError:
2192 // We had an access IO error.
2193 // Return false so that we can try again.
2194 // The value of out_secondary_dex_exists does not matter in this case and by convention
2195 // is set to false.
2196 *out_secondary_dex_exists = false;
2197 return false;
2198 default:
2199 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2200 *out_secondary_dex_exists = false;
2201 return false;
2202 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002203}
2204
Alan Stokesa25d90c2017-10-16 10:56:00 +01002205// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2206// Returns true if all parameters are valid and the hash successfully computed and stored in
2207// out_secondary_dex_hash.
2208// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2209// the app.
2210// For any other errors (e.g. if any of the parameters are invalid) returns false.
2211bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2212 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2213 std::vector<uint8_t>* out_secondary_dex_hash) {
2214 out_secondary_dex_hash->clear();
2215
2216 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2217
2218 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2219 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2220 << storage_flag;
2221 return false;
2222 }
2223
2224 // Pipe to get the hash result back from our child process.
2225 unique_fd pipe_read, pipe_write;
2226 if (!Pipe(&pipe_read, &pipe_write)) {
2227 PLOG(ERROR) << "Failed to create pipe";
2228 return false;
2229 }
2230
2231 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2232 // access data the app itself can access.
2233 pid_t pid = fork();
2234 if (pid == 0) {
2235 // child -- drop privileges before continuing
2236 drop_capabilities(uid);
2237 pipe_read.reset();
2238
2239 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2240 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2241 _exit(1);
2242 }
2243
2244 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2245 if (fd == -1) {
2246 if (errno == EACCES || errno == ENOENT) {
2247 // Not treated as an error.
2248 _exit(0);
2249 }
2250 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
2251 _exit(1);
2252 }
2253
2254 SHA256_CTX ctx;
2255 SHA256_Init(&ctx);
2256
2257 std::vector<uint8_t> buffer(65536);
2258 while (true) {
2259 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2260 if (bytes_read == 0) {
2261 break;
2262 } else if (bytes_read == -1) {
2263 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
2264 _exit(1);
2265 }
2266
2267 SHA256_Update(&ctx, buffer.data(), bytes_read);
2268 }
2269
2270 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2271 SHA256_Final(hash.data(), &ctx);
2272 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
2273 _exit(1);
2274 }
2275
2276 _exit(0);
2277 }
2278
2279 // parent
2280 pipe_write.reset();
2281
2282 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2283 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2284 out_secondary_dex_hash->clear();
2285 }
2286 return wait_child(pid) == 0;
2287}
2288
Jeff Sharkey90aff262016-12-12 14:28:24 -07002289// Helper for move_ab, so that we can have common failure-case cleanup.
2290static bool unlink_and_rename(const char* from, const char* to) {
2291 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2292 // return a failure.
2293 struct stat s;
2294 if (stat(to, &s) == 0) {
2295 if (!S_ISREG(s.st_mode)) {
2296 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2297 return false;
2298 }
2299 if (unlink(to) != 0) {
2300 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2301 return false;
2302 }
2303 } else {
2304 // This may be a permission problem. We could investigate the error code, but we'll just
2305 // let the rename failure do the work for us.
2306 }
2307
2308 // Try to rename "to" to "from."
2309 if (rename(from, to) != 0) {
2310 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2311 return false;
2312 }
2313 return true;
2314}
2315
2316// Move/rename a B artifact (from) to an A artifact (to).
2317static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2318 // Check whether B exists.
2319 {
2320 struct stat s;
2321 if (stat(b_path.c_str(), &s) != 0) {
2322 // Silently ignore for now. The service calling this isn't smart enough to understand
2323 // lack of artifacts at the moment.
2324 return false;
2325 }
2326 if (!S_ISREG(s.st_mode)) {
2327 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2328 // Try to unlink, but swallow errors.
2329 unlink(b_path.c_str());
2330 return false;
2331 }
2332 }
2333
2334 // Rename B to A.
2335 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2336 // Delete the b_path so we don't try again (or fail earlier).
2337 if (unlink(b_path.c_str()) != 0) {
2338 PLOG(ERROR) << "Could not unlink " << b_path;
2339 }
2340
2341 return false;
2342 }
2343
2344 return true;
2345}
2346
2347bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2348 // Get the current slot suffix. No suffix, no A/B.
2349 std::string slot_suffix;
2350 {
2351 char buf[kPropertyValueMax];
2352 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2353 return false;
2354 }
2355 slot_suffix = buf;
2356
2357 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2358 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2359 return false;
2360 }
2361 }
2362
2363 // Validate other inputs.
2364 if (validate_apk_path(apk_path) != 0) {
2365 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2366 return false;
2367 }
2368 if (validate_apk_path(oat_dir) != 0) {
2369 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2370 return false;
2371 }
2372
2373 char a_path[PKG_PATH_MAX];
2374 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2375 return false;
2376 }
2377 const std::string a_vdex_path = create_vdex_filename(a_path);
2378 const std::string a_image_path = create_image_filename(a_path);
2379
2380 // B path = A path + slot suffix.
2381 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2382 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2383 const std::string b_image_path = StringPrintf("%s.%s",
2384 a_image_path.c_str(),
2385 slot_suffix.c_str());
2386
2387 bool success = true;
2388 if (move_ab_path(b_path, a_path)) {
2389 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2390 // Note: we can live without an app image. As such, ignore failure to move the image file.
2391 // If we decide to require the app image, or the app image being moved correctly,
2392 // then change accordingly.
2393 constexpr bool kIgnoreAppImageFailure = true;
2394
2395 if (!a_image_path.empty()) {
2396 if (!move_ab_path(b_image_path, a_image_path)) {
2397 unlink(a_image_path.c_str());
2398 if (!kIgnoreAppImageFailure) {
2399 success = false;
2400 }
2401 }
2402 }
2403 } else {
2404 // Cleanup: delete B image, ignore errors.
2405 unlink(b_image_path.c_str());
2406 success = false;
2407 }
2408 } else {
2409 // Cleanup: delete B image, ignore errors.
2410 unlink(b_vdex_path.c_str());
2411 unlink(b_image_path.c_str());
2412 success = false;
2413 }
2414 return success;
2415}
2416
2417bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2418 // Delete the oat/odex file.
2419 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002420 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002421 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002422 return false;
2423 }
2424
2425 // In case of a permission failure report the issue. Otherwise just print a warning.
2426 auto unlink_and_check = [](const char* path) -> bool {
2427 int result = unlink(path);
2428 if (result != 0) {
2429 if (errno == EACCES || errno == EPERM) {
2430 PLOG(ERROR) << "Could not unlink " << path;
2431 return false;
2432 }
2433 PLOG(WARNING) << "Could not unlink " << path;
2434 }
2435 return true;
2436 };
2437
2438 // Delete the oat/odex file.
2439 bool return_value_oat = unlink_and_check(out_path);
2440
2441 // Derive and delete the app image.
2442 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2443
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002444 // Derive and delete the vdex file.
2445 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2446
Jeff Sharkey90aff262016-12-12 14:28:24 -07002447 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002448 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002449}
2450
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002451static bool is_absolute_path(const std::string& path) {
2452 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2453 LOG(ERROR) << "Invalid absolute path " << path;
2454 return false;
2455 } else {
2456 return true;
2457 }
2458}
2459
2460static bool is_valid_instruction_set(const std::string& instruction_set) {
2461 // TODO: add explicit whitelisting of instruction sets
2462 if (instruction_set.find('/') != std::string::npos) {
2463 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2464 return false;
2465 } else {
2466 return true;
2467 }
2468}
2469
2470bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2471 const char *apk_path, const char *instruction_set) {
2472 std::string oat_dir_ = oat_dir;
2473 std::string apk_path_ = apk_path;
2474 std::string instruction_set_ = instruction_set;
2475
2476 if (!is_absolute_path(oat_dir_)) return false;
2477 if (!is_absolute_path(apk_path_)) return false;
2478 if (!is_valid_instruction_set(instruction_set_)) return false;
2479
2480 std::string::size_type end = apk_path_.rfind('.');
2481 std::string::size_type start = apk_path_.rfind('/', end);
2482 if (end == std::string::npos || start == std::string::npos) {
2483 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2484 return false;
2485 }
2486
2487 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2488 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2489 const char* res = res_.c_str();
2490 if (strlen(res) >= PKG_PATH_MAX) {
2491 LOG(ERROR) << "Result too large";
2492 return false;
2493 } else {
2494 strlcpy(path, res, PKG_PATH_MAX);
2495 return true;
2496 }
2497}
2498
2499bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2500 const char *instruction_set) {
2501 std::string apk_path_ = apk_path;
2502 std::string instruction_set_ = instruction_set;
2503
2504 if (!is_absolute_path(apk_path_)) return false;
2505 if (!is_valid_instruction_set(instruction_set_)) return false;
2506
2507 std::string::size_type end = apk_path_.rfind('.');
2508 std::string::size_type start = apk_path_.rfind('/', end);
2509 if (end == std::string::npos || start == std::string::npos) {
2510 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2511 return false;
2512 }
2513
2514 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2515 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2516}
2517
2518bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2519 const char *instruction_set) {
2520 std::string src_ = src;
2521 std::string instruction_set_ = instruction_set;
2522
2523 if (!is_absolute_path(src_)) return false;
2524 if (!is_valid_instruction_set(instruction_set_)) return false;
2525
2526 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2527 if (*it == '/') {
2528 *it = '@';
2529 }
2530 }
2531
2532 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2533 + DALVIK_CACHE_POSTFIX;
2534 const char* res = res_.c_str();
2535 if (strlen(res) >= PKG_PATH_MAX) {
2536 LOG(ERROR) << "Result too large";
2537 return false;
2538 } else {
2539 strlcpy(path, res, PKG_PATH_MAX);
2540 return true;
2541 }
2542}
2543
Calin Juravle0d0a4922018-01-23 19:54:11 -08002544bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds) {
2545 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2546 for (const std::string& elem : classpaths_elems) {
2547 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2548 if (fd < 0) {
2549 PLOG(ERROR) << "Could not open classpath elem " << elem;
2550 return false;
2551 } else {
2552 apk_fds->push_back(std::move(fd));
2553 }
2554 }
2555 return true;
2556}
2557
2558static bool create_app_profile_snapshot(int32_t app_id,
2559 const std::string& package_name,
2560 const std::string& profile_name,
2561 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002562 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2563
Calin Juravle824a64d2018-01-18 20:23:17 -08002564 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002565 if (snapshot_fd < 0) {
2566 return false;
2567 }
2568
2569 std::vector<unique_fd> profiles_fd;
2570 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002571 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2572 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002573 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2574 return false;
2575 }
2576
2577 profiles_fd.push_back(std::move(reference_profile_fd));
2578
Calin Juravle0d0a4922018-01-23 19:54:11 -08002579 // Open the class paths elements. These will be used to filter out profile data that does
2580 // not belong to the classpath during merge.
2581 std::vector<unique_fd> apk_fds;
2582 if (!open_classpath_files(classpath, &apk_fds)) {
2583 return false;
2584 }
2585
Calin Juravle29591732017-11-20 17:46:19 -08002586 pid_t pid = fork();
2587 if (pid == 0) {
2588 /* child -- drop privileges before continuing */
2589 drop_capabilities(app_shared_gid);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002590 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds);
Calin Juravle29591732017-11-20 17:46:19 -08002591 exit(42); /* only get here on exec failure */
2592 }
2593
2594 /* parent */
2595 int return_code = wait_child(pid);
2596 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002597 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002598 return false;
2599 }
2600
2601 return true;
2602}
2603
Calin Juravle0d0a4922018-01-23 19:54:11 -08002604static bool create_boot_image_profile_snapshot(const std::string& package_name,
2605 const std::string& profile_name,
2606 const std::string& classpath) {
2607 // The reference profile directory for the android package might not be prepared. Do it now.
2608 const std::string ref_profile_dir =
2609 create_primary_reference_profile_package_dir_path(package_name);
2610 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2611 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2612 return false;
2613 }
2614
2615 // Open and create the snapshot profile.
2616 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2617
2618 // Collect all non empty profiles.
2619 // The collection will traverse all applications profiles and find the non empty files.
2620 // This has the potential of inspecting a large number of files and directories (depending
2621 // on the number of applications and users). So there is a slight increase in the chance
2622 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2623 // fail the snapshot and aggregate whatever profile we could open.
2624 //
2625 // The profile snapshot is a best effort based on available data it's ok if some data
2626 // from some apps is missing. It will be counter productive for the snapshot to fail
2627 // because we could not open or read some of the files.
2628 std::vector<std::string> profiles;
2629 if (!collect_profiles(&profiles)) {
2630 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2631 }
2632
2633 // If we have no profiles return early.
2634 if (profiles.empty()) {
2635 return true;
2636 }
2637
2638 // Open the classpath elements. These will be used to filter out profile data that does
2639 // not belong to the classpath during merge.
2640 std::vector<unique_fd> apk_fds;
2641 if (!open_classpath_files(classpath, &apk_fds)) {
2642 return false;
2643 }
2644
2645 // If we could not open any files from the classpath return an error.
2646 if (apk_fds.empty()) {
2647 LOG(ERROR) << "Could not open any of the classpath elements.";
2648 return false;
2649 }
2650
2651 // Aggregate the profiles in batches of kAggregationBatchSize.
2652 // We do this to avoid opening a huge a amount of files.
2653 static constexpr size_t kAggregationBatchSize = 10;
2654
2655 std::vector<unique_fd> profiles_fd;
2656 for (size_t i = 0; i < profiles.size(); ) {
2657 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2658 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2659 if (fd.get() >= 0) {
2660 profiles_fd.push_back(std::move(fd));
2661 }
2662 }
2663 pid_t pid = fork();
2664 if (pid == 0) {
2665 /* child -- drop privileges before continuing */
2666 drop_capabilities(AID_SYSTEM);
2667
2668 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds);
2669 exit(42); /* only get here on exec failure */
2670 }
2671
2672 /* parent */
2673 int return_code = wait_child(pid);
2674 if (!WIFEXITED(return_code)) {
2675 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2676 return false;
2677 }
2678 return true;
2679 }
2680 return true;
2681}
2682
2683bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2684 const std::string& profile_name, const std::string& classpath) {
2685 if (app_id == -1) {
2686 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2687 } else {
2688 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2689 }
2690}
2691
Calin Juravlec3b049e2018-01-18 22:32:58 -08002692bool prepare_app_profile(const std::string& package_name,
2693 userid_t user_id,
2694 appid_t app_id,
2695 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002696 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002697 const std::unique_ptr<std::string>& dex_metadata) {
2698 // Prepare the current profile.
2699 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2700 /*is_secondary_dex*/ false);
2701 uid_t uid = multiuser_get_uid(user_id, app_id);
2702 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2703 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2704 return false;
2705 }
2706
2707 // Check if we need to install the profile from the dex metadata.
2708 if (dex_metadata == nullptr) {
2709 return true;
2710 }
2711
2712 // We have a dex metdata. Merge the profile into the reference profile.
2713 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2714 /*read_write*/ true, /*is_secondary_dex*/ false);
2715 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2716 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002717 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2718 if (apk_fd < 0) {
2719 PLOG(ERROR) << "Could not open code path " << code_path;
2720 return false;
2721 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002722
2723 pid_t pid = fork();
2724 if (pid == 0) {
2725 /* child -- drop privileges before continuing */
2726 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2727 drop_capabilities(app_shared_gid);
2728
Calin Juravlef63d4792018-01-30 17:43:34 +00002729 // The copy and update takes ownership over the fds.
2730 run_profman_copy_and_update(std::move(dex_metadata_fd),
2731 std::move(ref_profile_fd),
2732 std::move(apk_fd));
Calin Juravlec3b049e2018-01-18 22:32:58 -08002733 exit(42); /* only get here on exec failure */
2734 }
2735
2736 /* parent */
2737 int return_code = wait_child(pid);
2738 if (!WIFEXITED(return_code)) {
2739 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2740 return false;
2741 }
2742 return true;
2743}
2744
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002745} // namespace installd
2746} // namespace android