blob: a2bce41ecad566ed9bb30a9bf9f17595aa5fdb1c [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
Jeff Sharkey90aff262016-12-12 14:28:24 -070018#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070019#include <stdlib.h>
20#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070021#include <sys/capability.h>
22#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070023#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070024#include <sys/time.h>
25#include <sys/types.h>
26#include <sys/resource.h>
27#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070028#include <unistd.h>
29
Mark Salyzyna5e161b2016-09-29 08:08:05 -070030#include <android/log.h> // TODO: Move everything to base/logging.
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070031#include <android-base/logging.h>
32#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070033#include <android-base/strings.h>
34#include <android-base/unique_fd.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070035#include <cutils/properties.h>
36#include <cutils/sched_policy.h>
37#include <private/android_filesystem_config.h>
38#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070039
40#include "dexopt.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include "installd_deps.h"
42#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070043#include "utils.h"
44
45using android::base::StringPrintf;
Jeff Sharkey90aff262016-12-12 14:28:24 -070046using android::base::EndsWith;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070047
48namespace android {
49namespace installd {
50
51static const char* parse_null(const char* arg) {
52 if (strcmp(arg, "!") == 0) {
53 return nullptr;
54 } else {
55 return arg;
56 }
57}
58
Jeff Sharkey90aff262016-12-12 14:28:24 -070059static bool clear_profile(const std::string& profile) {
60 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
61 if (ufd.get() < 0) {
62 if (errno != ENOENT) {
63 PLOG(WARNING) << "Could not open profile " << profile;
64 return false;
65 } else {
66 // Nothing to clear. That's ok.
67 return true;
68 }
69 }
70
71 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
72 if (errno != EWOULDBLOCK) {
73 PLOG(WARNING) << "Error locking profile " << profile;
74 }
75 // This implies that the app owning this profile is running
76 // (and has acquired the lock).
77 //
78 // If we can't acquire the lock bail out since clearing is useless anyway
79 // (the app will write again to the profile).
80 //
81 // Note:
82 // This does not impact the this is not an issue for the profiling correctness.
83 // In case this is needed because of an app upgrade, profiles will still be
84 // eventually cleared by the app itself due to checksum mismatch.
85 // If this is needed because profman advised, then keeping the data around
86 // until the next run is again not an issue.
87 //
88 // If the app attempts to acquire a lock while we've held one here,
89 // it will simply skip the current write cycle.
90 return false;
91 }
92
93 bool truncated = ftruncate(ufd.get(), 0) == 0;
94 if (!truncated) {
95 PLOG(WARNING) << "Could not truncate " << profile;
96 }
97 if (flock(ufd.get(), LOCK_UN) != 0) {
98 PLOG(WARNING) << "Error unlocking profile " << profile;
99 }
100 return truncated;
101}
102
103bool clear_reference_profile(const char* pkgname) {
104 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
105 std::string reference_profile = create_primary_profile(reference_profile_dir);
106 return clear_profile(reference_profile);
107}
108
109bool clear_current_profile(const char* pkgname, userid_t user) {
110 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
111 std::string profile = create_primary_profile(profile_dir);
112 return clear_profile(profile);
113}
114
115bool clear_current_profiles(const char* pkgname) {
116 bool success = true;
117 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
118 for (auto user : users) {
119 success &= clear_current_profile(pkgname, user);
120 }
121 return success;
122}
123
124static int split_count(const char *str)
125{
126 char *ctx;
127 int count = 0;
128 char buf[kPropertyValueMax];
129
130 strncpy(buf, str, sizeof(buf));
131 char *pBuf = buf;
132
133 while(strtok_r(pBuf, " ", &ctx) != NULL) {
134 count++;
135 pBuf = NULL;
136 }
137
138 return count;
139}
140
141static int split(char *buf, const char **argv)
142{
143 char *ctx;
144 int count = 0;
145 char *tok;
146 char *pBuf = buf;
147
148 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
149 argv[count++] = tok;
150 pBuf = NULL;
151 }
152
153 return count;
154}
155
156static void run_patchoat(int input_oat_fd, int input_vdex_fd, int out_oat_fd, int out_vdex_fd,
157 const char* input_oat_file_name, const char* input_vdex_file_name,
158 const char* output_oat_file_name, const char* output_vdex_file_name,
159 const char *pkgname ATTRIBUTE_UNUSED, const char *instruction_set)
160{
161 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
162 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
163
164 static const char* PATCHOAT_BIN = "/system/bin/patchoat";
165 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
166 ALOGE("Instruction set %s longer than max length of %d",
167 instruction_set, MAX_INSTRUCTION_SET_LEN);
168 return;
169 }
170
171 /* input_file_name/input_fd should be the .odex/.oat file that is precompiled. I think*/
172 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
173 char input_oat_fd_arg[strlen("--input-oat-fd=") + MAX_INT_LEN];
174 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
175 char output_oat_fd_arg[strlen("--output-oat-fd=") + MAX_INT_LEN];
176 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
177 const char* patched_image_location_arg = "--patched-image-location=/system/framework/boot.art";
178 // The caller has already gotten all the locks we need.
179 const char* no_lock_arg = "--no-lock-output";
180 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
181 sprintf(output_oat_fd_arg, "--output-oat-fd=%d", out_oat_fd);
182 sprintf(input_oat_fd_arg, "--input-oat-fd=%d", input_oat_fd);
183 ALOGV("Running %s isa=%s in-oat-fd=%d (%s) in-vdex-fd=%d (%s) "
184 "out-oat-fd=%d (%s) out-vdex-fd=%d (%s)\n",
185 PATCHOAT_BIN, instruction_set,
186 input_oat_fd, input_oat_file_name,
187 input_vdex_fd, input_vdex_file_name,
188 out_oat_fd, output_oat_file_name,
189 out_vdex_fd, output_vdex_file_name);
190
191 /* patchoat, patched-image-location, no-lock, isa, input-fd, output-fd */
192 char* argv[9];
193 argv[0] = (char*) PATCHOAT_BIN;
194 argv[1] = (char*) patched_image_location_arg;
195 argv[2] = (char*) no_lock_arg;
196 argv[3] = instruction_set_arg;
197 argv[4] = input_oat_fd_arg;
198 argv[5] = input_vdex_fd_arg;
199 argv[6] = output_oat_fd_arg;
200 argv[7] = output_vdex_fd_arg;
201 argv[8] = NULL;
202
203 execv(PATCHOAT_BIN, (char* const *)argv);
204 ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
205}
206
207static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
208 const char* input_file_name, const char* output_file_name, int swap_fd,
209 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
210 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
211 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
212
213 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
214 ALOGE("Instruction set %s longer than max length of %d",
215 instruction_set, MAX_INSTRUCTION_SET_LEN);
216 return;
217 }
218
219 char dex2oat_Xms_flag[kPropertyValueMax];
220 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
221
222 char dex2oat_Xmx_flag[kPropertyValueMax];
223 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
224
225 char dex2oat_threads_buf[kPropertyValueMax];
226 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
227 ? "dalvik.vm.dex2oat-threads"
228 : "dalvik.vm.boot-dex2oat-threads",
229 dex2oat_threads_buf,
230 NULL) > 0;
231 char dex2oat_threads_arg[kPropertyValueMax + 2];
232 if (have_dex2oat_threads_flag) {
233 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
234 }
235
236 char dex2oat_isa_features_key[kPropertyKeyMax];
237 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
238 char dex2oat_isa_features[kPropertyValueMax];
239 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
240 dex2oat_isa_features, NULL) > 0;
241
242 char dex2oat_isa_variant_key[kPropertyKeyMax];
243 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
244 char dex2oat_isa_variant[kPropertyValueMax];
245 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
246 dex2oat_isa_variant, NULL) > 0;
247
248 const char *dex2oat_norelocation = "-Xnorelocate";
249 bool have_dex2oat_relocation_skip_flag = false;
250
251 char dex2oat_flags[kPropertyValueMax];
252 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
253 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
254 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
255
256 // If we booting without the real /data, don't spend time compiling.
257 char vold_decrypt[kPropertyValueMax];
258 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
259 bool skip_compilation = (have_vold_decrypt &&
260 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
261 (strcmp(vold_decrypt, "1") == 0)));
262
263 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
264
265 char app_image_format[kPropertyValueMax];
266 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
267 bool have_app_image_format =
268 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
269 if (have_app_image_format) {
270 sprintf(image_format_arg, "--image-format=%s", app_image_format);
271 }
272
273 char dex2oat_large_app_threshold[kPropertyValueMax];
274 bool have_dex2oat_large_app_threshold =
275 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
276 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
277 if (have_dex2oat_large_app_threshold) {
278 sprintf(dex2oat_large_app_threshold_arg,
279 "--very-large-app-threshold=%s",
280 dex2oat_large_app_threshold);
281 }
282
283 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
284
285 static const char* RUNTIME_ARG = "--runtime-arg";
286
287 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
288
289 char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
290 char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
291 char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
292 char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
293 char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
294 char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
295 char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
296 char instruction_set_variant_arg[strlen("--instruction-set-variant=") + kPropertyValueMax];
297 char instruction_set_features_arg[strlen("--instruction-set-features=") + kPropertyValueMax];
298 char dex2oat_Xms_arg[strlen("-Xms") + kPropertyValueMax];
299 char dex2oat_Xmx_arg[strlen("-Xmx") + kPropertyValueMax];
300 char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
301 bool have_dex2oat_swap_fd = false;
302 char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
303 bool have_dex2oat_image_fd = false;
304 char dex2oat_image_fd[strlen("--app-image-fd=") + MAX_INT_LEN];
305
306 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
307 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
308 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
309 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
310 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
311 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
312 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
313 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
314 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
315 if (swap_fd >= 0) {
316 have_dex2oat_swap_fd = true;
317 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
318 }
319 if (image_fd >= 0) {
320 have_dex2oat_image_fd = true;
321 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
322 }
323
324 if (have_dex2oat_Xms_flag) {
325 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
326 }
327 if (have_dex2oat_Xmx_flag) {
328 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
329 }
330
331 // Compute compiler filter.
332
333 bool have_dex2oat_compiler_filter_flag;
334 if (skip_compilation) {
335 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
336 have_dex2oat_compiler_filter_flag = true;
337 have_dex2oat_relocation_skip_flag = true;
338 } else if (vm_safe_mode) {
339 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
340 have_dex2oat_compiler_filter_flag = true;
341 } else if (compiler_filter != nullptr &&
342 strlen(compiler_filter) + strlen("--compiler-filter=") <
343 arraysize(dex2oat_compiler_filter_arg)) {
344 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
345 have_dex2oat_compiler_filter_flag = true;
346 } else {
347 char dex2oat_compiler_filter_flag[kPropertyValueMax];
348 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
349 dex2oat_compiler_filter_flag, NULL) > 0;
350 if (have_dex2oat_compiler_filter_flag) {
351 sprintf(dex2oat_compiler_filter_arg,
352 "--compiler-filter=%s",
353 dex2oat_compiler_filter_flag);
354 }
355 }
356
357 // Check whether all apps should be compiled debuggable.
358 if (!debuggable) {
359 char prop_buf[kPropertyValueMax];
360 debuggable =
361 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
362 (prop_buf[0] == '1');
363 }
364 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
365 if (profile_fd != -1) {
366 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
367 }
368
369
370 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
371
372 const char* argv[9 // program name, mandatory arguments and the final NULL
373 + (have_dex2oat_isa_variant ? 1 : 0)
374 + (have_dex2oat_isa_features ? 1 : 0)
375 + (have_dex2oat_Xms_flag ? 2 : 0)
376 + (have_dex2oat_Xmx_flag ? 2 : 0)
377 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
378 + (have_dex2oat_threads_flag ? 1 : 0)
379 + (have_dex2oat_swap_fd ? 1 : 0)
380 + (have_dex2oat_image_fd ? 1 : 0)
381 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
382 + (generate_debug_info ? 1 : 0)
383 + (debuggable ? 1 : 0)
384 + (have_app_image_format ? 1 : 0)
385 + dex2oat_flags_count
386 + (profile_fd == -1 ? 0 : 1)
387 + (shared_libraries != nullptr ? 4 : 0)
388 + (have_dex2oat_large_app_threshold ? 1 : 0)];
389 int i = 0;
390 argv[i++] = DEX2OAT_BIN;
391 argv[i++] = zip_fd_arg;
392 argv[i++] = zip_location_arg;
393 argv[i++] = input_vdex_fd_arg;
394 argv[i++] = output_vdex_fd_arg;
395 argv[i++] = oat_fd_arg;
396 argv[i++] = oat_location_arg;
397 argv[i++] = instruction_set_arg;
398 if (have_dex2oat_isa_variant) {
399 argv[i++] = instruction_set_variant_arg;
400 }
401 if (have_dex2oat_isa_features) {
402 argv[i++] = instruction_set_features_arg;
403 }
404 if (have_dex2oat_Xms_flag) {
405 argv[i++] = RUNTIME_ARG;
406 argv[i++] = dex2oat_Xms_arg;
407 }
408 if (have_dex2oat_Xmx_flag) {
409 argv[i++] = RUNTIME_ARG;
410 argv[i++] = dex2oat_Xmx_arg;
411 }
412 if (have_dex2oat_compiler_filter_flag) {
413 argv[i++] = dex2oat_compiler_filter_arg;
414 }
415 if (have_dex2oat_threads_flag) {
416 argv[i++] = dex2oat_threads_arg;
417 }
418 if (have_dex2oat_swap_fd) {
419 argv[i++] = dex2oat_swap_fd;
420 }
421 if (have_dex2oat_image_fd) {
422 argv[i++] = dex2oat_image_fd;
423 }
424 if (generate_debug_info) {
425 argv[i++] = "--generate-debug-info";
426 }
427 if (debuggable) {
428 argv[i++] = "--debuggable";
429 }
430 if (have_app_image_format) {
431 argv[i++] = image_format_arg;
432 }
433 if (have_dex2oat_large_app_threshold) {
434 argv[i++] = dex2oat_large_app_threshold_arg;
435 }
436 if (dex2oat_flags_count) {
437 i += split(dex2oat_flags, argv + i);
438 }
439 if (have_dex2oat_relocation_skip_flag) {
440 argv[i++] = RUNTIME_ARG;
441 argv[i++] = dex2oat_norelocation;
442 }
443 if (profile_fd != -1) {
444 argv[i++] = profile_arg;
445 }
446 if (shared_libraries != nullptr) {
447 argv[i++] = RUNTIME_ARG;
448 argv[i++] = "-classpath";
449 argv[i++] = RUNTIME_ARG;
450 argv[i++] = shared_libraries;
451 }
452 // Do not add after dex2oat_flags, they should override others for debugging.
453 argv[i] = NULL;
454
455 execv(DEX2OAT_BIN, (char * const *)argv);
456 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
457}
458
459/*
460 * Whether dexopt should use a swap file when compiling an APK.
461 *
462 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
463 * itself, anyways).
464 *
465 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
466 *
467 * Otherwise, return true if this is a low-mem device.
468 *
469 * Otherwise, return default value.
470 */
471static bool kAlwaysProvideSwapFile = false;
472static bool kDefaultProvideSwapFile = true;
473
474static bool ShouldUseSwapFileForDexopt() {
475 if (kAlwaysProvideSwapFile) {
476 return true;
477 }
478
479 // Check the "override" property. If it exists, return value == "true".
480 char dex2oat_prop_buf[kPropertyValueMax];
481 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
482 if (strcmp(dex2oat_prop_buf, "true") == 0) {
483 return true;
484 } else {
485 return false;
486 }
487 }
488
489 // Shortcut for default value. This is an implementation optimization for the process sketched
490 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
491 // as low-mem is never returning false. The compiler will optimize this away if it can.
492 if (kDefaultProvideSwapFile) {
493 return true;
494 }
495
496 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
497 if (is_low_mem) {
498 return true;
499 }
500
501 // Default value must be false here.
502 return kDefaultProvideSwapFile;
503}
504
505static void SetDex2OatAndPatchOatScheduling(bool set_to_bg) {
506 if (set_to_bg) {
507 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
508 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
509 exit(70);
510 }
511 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
512 ALOGE("setpriority failed: %s\n", strerror(errno));
513 exit(71);
514 }
515 }
516}
517
518static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
519 for (size_t i = 0; i < fds.size(); i++) {
520 if (close(fds[i]) != 0) {
521 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
522 }
523 }
524}
525
526static fd_t open_profile_dir(const std::string& profile_dir) {
527 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
528 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
529 if (profile_dir_fd < 0) {
530 // In a multi-user environment, these directories can be created at
531 // different points and it's possible we'll attempt to open a profile
532 // dir before it exists.
533 if (errno != ENOENT) {
534 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
535 }
536 }
537 return profile_dir_fd;
538}
539
540static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
541 fd_t profile_dir_fd = open_profile_dir(profile_dir);
542 if (profile_dir_fd < 0) {
543 return -1;
544 }
545
546 fd_t profile_fd = -1;
547 std::string profile_file = create_primary_profile(profile_dir);
548
549 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW));
550 if (profile_fd == -1) {
551 // It's not an error if the profile file does not exist.
552 if (errno != ENOENT) {
553 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
554 }
555 }
556 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
557 if (close(profile_dir_fd) != 0) {
558 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
559 }
560 return profile_fd;
561}
562
563static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
564 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
565 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
566}
567
568static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
569 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
570 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
571 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
572 if (fd < 0) {
573 return -1;
574 }
575 if (read_write) {
576 // Fix the owner.
577 if (fchown(fd, uid, uid) < 0) {
578 close(fd);
579 return -1;
580 }
581 }
582 return fd;
583}
584
585static void open_profile_files(uid_t uid, const char* pkgname,
586 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
587 // Open the reference profile in read-write mode as profman might need to save the merge.
588 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
589 if (*reference_profile_fd < 0) {
590 // We can't access the reference profile file.
591 return;
592 }
593
594 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
595 for (auto user : users) {
596 fd_t profile_fd = open_primary_profile_file(user, pkgname);
597 // Add to the lists only if both fds are valid.
598 if (profile_fd >= 0) {
599 profiles_fd->push_back(profile_fd);
600 }
601 }
602}
603
604static void drop_capabilities(uid_t uid) {
605 if (setgid(uid) != 0) {
606 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
607 exit(64);
608 }
609 if (setuid(uid) != 0) {
610 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
611 exit(65);
612 }
613 // drop capabilities
614 struct __user_cap_header_struct capheader;
615 struct __user_cap_data_struct capdata[2];
616 memset(&capheader, 0, sizeof(capheader));
617 memset(&capdata, 0, sizeof(capdata));
618 capheader.version = _LINUX_CAPABILITY_VERSION_3;
619 if (capset(&capheader, &capdata[0]) < 0) {
620 ALOGE("capset failed: %s\n", strerror(errno));
621 exit(66);
622 }
623}
624
625static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
626static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
627static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
628static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
629static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
630
631static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
632 static const size_t MAX_INT_LEN = 32;
633 static const char* PROFMAN_BIN = "/system/bin/profman";
634
635 std::vector<std::string> profile_args(profiles_fd.size());
636 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
637 for (size_t k = 0; k < profiles_fd.size(); k++) {
638 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
639 profile_args[k].assign(profile_buf);
640 }
641 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
642 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
643
644 // program name, reference profile fd, the final NULL and the profile fds
645 const char* argv[3 + profiles_fd.size()];
646 int i = 0;
647 argv[i++] = PROFMAN_BIN;
648 argv[i++] = reference_profile_arg;
649 for (size_t k = 0; k < profile_args.size(); k++) {
650 argv[i++] = profile_args[k].c_str();
651 }
652 // Do not add after dex2oat_flags, they should override others for debugging.
653 argv[i] = NULL;
654
655 execv(PROFMAN_BIN, (char * const *)argv);
656 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
657 exit(68); /* only get here on exec failure */
658}
659
660// Decides if profile guided compilation is needed or not based on existing profiles.
661// Returns true if there is enough information in the current profiles that worth
662// a re-compilation of the package.
663// If the return value is true all the current profiles would have been merged into
664// the reference profiles accessible with open_reference_profile().
665bool analyse_profiles(uid_t uid, const char* pkgname) {
666 std::vector<fd_t> profiles_fd;
667 fd_t reference_profile_fd = -1;
668 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
669 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
670 // Skip profile guided compilation because no profiles were found.
671 // Or if the reference profile info couldn't be opened.
672 close_all_fds(profiles_fd, "profiles_fd");
673 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
674 PLOG(WARNING) << "Failed to close fd for reference profile";
675 }
676 return false;
677 }
678
679 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
680
681 pid_t pid = fork();
682 if (pid == 0) {
683 /* child -- drop privileges before continuing */
684 drop_capabilities(uid);
685 run_profman_merge(profiles_fd, reference_profile_fd);
686 exit(68); /* only get here on exec failure */
687 }
688 /* parent */
689 int return_code = wait_child(pid);
690 bool need_to_compile = false;
691 bool should_clear_current_profiles = false;
692 bool should_clear_reference_profile = false;
693 if (!WIFEXITED(return_code)) {
694 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
695 } else {
696 return_code = WEXITSTATUS(return_code);
697 switch (return_code) {
698 case PROFMAN_BIN_RETURN_CODE_COMPILE:
699 need_to_compile = true;
700 should_clear_current_profiles = true;
701 should_clear_reference_profile = false;
702 break;
703 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
704 need_to_compile = false;
705 should_clear_current_profiles = false;
706 should_clear_reference_profile = false;
707 break;
708 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
709 LOG(WARNING) << "Bad profiles for package " << pkgname;
710 need_to_compile = false;
711 should_clear_current_profiles = true;
712 should_clear_reference_profile = true;
713 break;
714 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
715 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
716 // Temporary IO problem (e.g. locking). Ignore but log a warning.
717 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
718 need_to_compile = false;
719 should_clear_current_profiles = false;
720 should_clear_reference_profile = false;
721 break;
722 default:
723 // Unknown return code or error. Unlink profiles.
724 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
725 << ": " << return_code;
726 need_to_compile = false;
727 should_clear_current_profiles = true;
728 should_clear_reference_profile = true;
729 break;
730 }
731 }
732 close_all_fds(profiles_fd, "profiles_fd");
733 if (close(reference_profile_fd) != 0) {
734 PLOG(WARNING) << "Failed to close fd for reference profile";
735 }
736 if (should_clear_current_profiles) {
737 clear_current_profiles(pkgname);
738 }
739 if (should_clear_reference_profile) {
740 clear_reference_profile(pkgname);
741 }
742 return need_to_compile;
743}
744
745static void run_profman_dump(const std::vector<fd_t>& profile_fds,
746 fd_t reference_profile_fd,
747 const std::vector<std::string>& dex_locations,
748 const std::vector<fd_t>& apk_fds,
749 fd_t output_fd) {
750 std::vector<std::string> profman_args;
751 static const char* PROFMAN_BIN = "/system/bin/profman";
752 profman_args.push_back(PROFMAN_BIN);
753 profman_args.push_back("--dump-only");
754 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
755 if (reference_profile_fd != -1) {
756 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
757 reference_profile_fd));
758 }
759 for (fd_t profile_fd : profile_fds) {
760 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
761 }
762 for (const std::string& dex_location : dex_locations) {
763 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
764 }
765 for (fd_t apk_fd : apk_fds) {
766 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
767 }
768 const char **argv = new const char*[profman_args.size() + 1];
769 size_t i = 0;
770 for (const std::string& profman_arg : profman_args) {
771 argv[i++] = profman_arg.c_str();
772 }
773 argv[i] = NULL;
774
775 execv(PROFMAN_BIN, (char * const *)argv);
776 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
777 exit(68); /* only get here on exec failure */
778}
779
780static const char* get_location_from_path(const char* path) {
781 static constexpr char kLocationSeparator = '/';
782 const char *location = strrchr(path, kLocationSeparator);
783 if (location == NULL) {
784 return path;
785 } else {
786 // Skip the separator character.
787 return location + 1;
788 }
789}
790
791bool dump_profiles(int32_t uid, const char* pkgname, const char* code_paths) {
792 std::vector<fd_t> profile_fds;
793 fd_t reference_profile_fd = -1;
794 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
795
796 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
797
798 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
799
800 const bool has_reference_profile = (reference_profile_fd != -1);
801 const bool has_profiles = !profile_fds.empty();
802
803 if (!has_reference_profile && !has_profiles) {
804 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
805 return false;
806 }
807
808 fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
809 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
810 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
811 return false;
812 }
813 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
814 std::vector<std::string> dex_locations;
815 std::vector<fd_t> apk_fds;
816 for (const std::string& code_full_path : code_full_paths) {
817 const char* full_path = code_full_path.c_str();
818 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
819 if (apk_fd == -1) {
820 ALOGE("installd cannot open '%s'\n", full_path);
821 return false;
822 }
823 dex_locations.push_back(get_location_from_path(full_path));
824 apk_fds.push_back(apk_fd);
825 }
826
827 pid_t pid = fork();
828 if (pid == 0) {
829 /* child -- drop privileges before continuing */
830 drop_capabilities(uid);
831 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
832 apk_fds, output_fd);
833 exit(68); /* only get here on exec failure */
834 }
835 /* parent */
836 close_all_fds(apk_fds, "apk_fds");
837 close_all_fds(profile_fds, "profile_fds");
838 if (close(reference_profile_fd) != 0) {
839 PLOG(WARNING) << "Failed to close fd for reference profile";
840 }
841 int return_code = wait_child(pid);
842 if (!WIFEXITED(return_code)) {
843 LOG(WARNING) << "profman failed for package " << pkgname << ": "
844 << return_code;
845 return false;
846 }
847 return true;
848}
849
850static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
851 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
852 if (EndsWith(oat_path, ".dex")) {
853 std::string new_path = oat_path;
854 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
855 CHECK(EndsWith(new_path, new_ext.c_str()));
856 return new_path;
857 }
858
859 // An odex entry. Not that this may not be an extension, e.g., in the OTA
860 // case (where the base name will have an extension for the B artifact).
861 size_t odex_pos = oat_path.rfind(".odex");
862 if (odex_pos != std::string::npos) {
863 std::string new_path = oat_path;
864 new_path.replace(odex_pos, strlen(".odex"), new_ext);
865 CHECK_NE(new_path.find(new_ext), std::string::npos);
866 return new_path;
867 }
868
869 // Don't know how to handle this.
870 return "";
871}
872
873// Translate the given oat path to an art (app image) path. An empty string
874// denotes an error.
875static std::string create_image_filename(const std::string& oat_path) {
876 return replace_file_extension(oat_path, ".art");
877}
878
879// Translate the given oat path to a vdex path. An empty string denotes an error.
880static std::string create_vdex_filename(const std::string& oat_path) {
881 return replace_file_extension(oat_path, ".vdex");
882}
883
884static bool add_extension_to_file_name(char* file_name, const char* extension) {
885 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
886 return false;
887 }
888 strcat(file_name, extension);
889 return true;
890}
891
892static int open_output_file(const char* file_name, bool recreate, int permissions) {
893 int flags = O_RDWR | O_CREAT;
894 if (recreate) {
895 if (unlink(file_name) < 0) {
896 if (errno != ENOENT) {
897 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
898 }
899 }
900 flags |= O_EXCL;
901 }
902 return open(file_name, flags, permissions);
903}
904
905static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
906 if (fchmod(fd,
907 S_IRUSR|S_IWUSR|S_IRGRP |
908 (is_public ? S_IROTH : 0)) < 0) {
909 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
910 return false;
911 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
912 ALOGE("installd cannot chown '%s' during dexopt\n", path);
913 return false;
914 }
915 return true;
916}
917
918static bool IsOutputDalvikCache(const char* oat_dir) {
919 // InstallerConnection.java (which invokes installd) transforms Java null arguments
920 // into '!'. Play it safe by handling it both.
921 // TODO: ensure we never get null.
922 // TODO: pass a flag instead of inferring if the output is dalvik cache.
923 return oat_dir == nullptr || oat_dir[0] == '!';
924}
925
926static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
927 const char* oat_dir, /*out*/ char* out_oat_path) {
928 // Early best-effort check whether we can fit the the path into our buffers.
929 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
930 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
931 // extension to the cache path (5 bytes).
932 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
933 ALOGE("apk_path too long '%s'\n", apk_path);
934 return false;
935 }
936
937 if (!IsOutputDalvikCache(oat_dir)) {
938 if (validate_apk_path(oat_dir)) {
939 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
940 return false;
941 }
942 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
943 return false;
944 }
945 } else {
946 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
947 return false;
948 }
949 }
950 return true;
951}
952
953// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
954// on destruction. It will also run the given cleanup (unless told not to) after closing.
955//
956// Usage example:
957//
958// Dex2oatFileWrapper<std::function<void ()>> file(open(...),
959// [name]() {
960// unlink(name.c_str());
961// });
962// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
963// wrapper if captured as a reference.
964//
965// if (file.get() == -1) {
966// // Error opening...
967// }
968//
969// ...
970// if (error) {
971// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
972// // and delete the file (after the fd is closed).
973// return -1;
974// }
975//
976// (Success case)
977// file.SetCleanup(false);
978// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
979// // (leaving the file around; after the fd is closed).
980//
981template <typename Cleanup>
982class Dex2oatFileWrapper {
983 public:
984 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true) {
985 }
986
987 Dex2oatFileWrapper(int value, Cleanup cleanup)
988 : value_(value), cleanup_(cleanup), do_cleanup_(true) {}
989
990 ~Dex2oatFileWrapper() {
991 reset(-1);
992 }
993
994 int get() {
995 return value_;
996 }
997
998 void SetCleanup(bool cleanup) {
999 do_cleanup_ = cleanup;
1000 }
1001
1002 void reset(int new_value) {
1003 if (value_ >= 0) {
1004 close(value_);
1005 }
1006 if (do_cleanup_ && cleanup_ != nullptr) {
1007 cleanup_();
1008 }
1009
1010 value_ = new_value;
1011 }
1012
1013 void reset(int new_value, Cleanup new_cleanup) {
1014 if (value_ >= 0) {
1015 close(value_);
1016 }
1017 if (do_cleanup_ && cleanup_ != nullptr) {
1018 cleanup_();
1019 }
1020
1021 value_ = new_value;
1022 cleanup_ = new_cleanup;
1023 }
1024
1025 private:
1026 int value_;
1027 Cleanup cleanup_;
1028 bool do_cleanup_;
1029};
1030
1031int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1032 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1033 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
1034 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1035 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1036 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1037 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1038 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1039
1040 CHECK(pkgname != nullptr);
1041 CHECK(pkgname[0] != 0);
1042
1043 // Public apps should not be compiled with profile information ever. Same goes for the special
1044 // package '*' used for the system server.
1045 Dex2oatFileWrapper<std::function<void ()>> reference_profile_fd;
1046 if (!is_public && pkgname[0] != '*') {
1047 // Open reference profile in read only mode as dex2oat does not get write permissions.
1048 const std::string pkgname_str(pkgname);
1049 reference_profile_fd.reset(open_reference_profile(uid, pkgname, /*read_write*/ false),
1050 [pkgname_str]() {
1051 clear_reference_profile(pkgname_str.c_str());
1052 });
1053 // Note: it's OK to not find a profile here.
1054 }
1055
1056 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1057 LOG_FATAL("dexopt flags contains unknown fields\n");
1058 }
1059
1060 char out_oat_path[PKG_PATH_MAX];
1061 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
1062 return false;
1063 }
1064
1065 const char *input_file;
1066 char in_odex_path[PKG_PATH_MAX];
1067 int dexopt_action = abs(dexopt_needed);
1068 bool is_odex_location = dexopt_needed < 0;
1069 switch (dexopt_action) {
1070 case DEX2OAT_FROM_SCRATCH:
1071 case DEX2OAT_FOR_BOOT_IMAGE:
1072 case DEX2OAT_FOR_FILTER:
1073 case DEX2OAT_FOR_RELOCATION:
1074 input_file = apk_path;
1075 break;
1076
1077 case PATCHOAT_FOR_RELOCATION:
1078 if (is_odex_location) {
1079 if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1080 return -1;
1081 }
1082 input_file = in_odex_path;
1083 } else {
1084 input_file = out_oat_path;
1085 }
1086 break;
1087
1088 default:
1089 ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
1090 return 72;
1091 }
1092
1093 struct stat input_stat;
1094 memset(&input_stat, 0, sizeof(input_stat));
1095 stat(input_file, &input_stat);
1096
1097 // Open the input file. If running dex2oat, `input_file` is the APK. If running
1098 // patchoat, it is the OAT file to be relocated.
1099 base::unique_fd input_fd(open(input_file, O_RDONLY, 0));
1100 if (input_fd.get() < 0) {
1101 ALOGE("installd cannot open '%s' for input during dexopt\n", input_file);
1102 return -1;
1103 }
1104
1105 // Create the output OAT file.
1106 const std::string out_oat_path_str(out_oat_path);
1107 Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
1108 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1109 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1110 if (out_oat_fd.get() < 0) {
1111 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
1112 return -1;
1113 }
1114 if (!set_permissions_and_ownership(out_oat_fd.get(), is_public, uid, out_oat_path)) {
1115 return -1;
1116 }
1117
1118 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1119 // unlink the old one.
1120 base::unique_fd in_vdex_fd;
1121 std::string in_vdex_path_str;
1122 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
1123 // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
1124 in_vdex_path_str = create_vdex_filename(input_file);
1125 if (in_vdex_path_str.empty()) {
1126 ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
1127 return -1;
1128 }
1129 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1130 if (in_vdex_fd.get() < 0) {
1131 ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
1132 in_vdex_path_str.c_str(), strerror(errno));
1133 return -1;
1134 }
1135 } else if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
1136 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1137 const char* path = nullptr;
1138 if (is_odex_location) {
1139 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1140 path = in_odex_path;
1141 } else {
1142 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
1143 return -1;
1144 }
1145 } else {
1146 path = out_oat_path;
1147 }
1148 in_vdex_path_str = create_vdex_filename(path);
1149 if (in_vdex_path_str.empty()) {
1150 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
1151 return -1;
1152 }
1153 in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1154 }
1155
1156 // Infer the name of the output VDEX and create it.
1157 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
1158 if (out_vdex_path_str.empty()) {
1159 return -1;
1160 }
1161 Dex2oatFileWrapper<std::function<void ()>> out_vdex_fd(
1162 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1163 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1164 if (out_vdex_fd.get() < 0) {
1165 ALOGE("installd cannot open '%s' for output during dexopt\n", out_vdex_path_str.c_str());
1166 return -1;
1167 }
1168 if (!set_permissions_and_ownership(out_vdex_fd.get(), is_public,
1169 uid, out_vdex_path_str.c_str())) {
1170 return -1;
1171 }
1172
1173 // Create a swap file if necessary.
1174 base::unique_fd swap_fd;
1175 if (ShouldUseSwapFileForDexopt()) {
1176 // Make sure there really is enough space.
1177 char swap_file_name[PKG_PATH_MAX];
1178 strcpy(swap_file_name, out_oat_path);
1179 if (add_extension_to_file_name(swap_file_name, ".swap")) {
1180 swap_fd.reset(open_output_file(swap_file_name, /*recreate*/true, /*permissions*/0600));
1181 }
1182 if (swap_fd.get() < 0) {
1183 // Could not create swap file. Optimistically go on and hope that we can compile
1184 // without it.
1185 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1186 } else {
1187 // Immediately unlink. We don't really want to hit flash.
1188 if (unlink(swap_file_name) < 0) {
1189 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1190 }
1191 }
1192 }
1193
1194 // Avoid generating an app image for extract only since it will not contain any classes.
1195 Dex2oatFileWrapper<std::function<void ()>> image_fd;
1196 const std::string image_path = create_image_filename(out_oat_path);
1197 if (dexopt_action != PATCHOAT_FOR_RELOCATION && !image_path.empty()) {
1198 char app_image_format[kPropertyValueMax];
1199 bool have_app_image_format =
1200 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1201 // Use app images only if it is enabled (by a set image format) and we are compiling
1202 // profile-guided (so the app image doesn't conservatively contain all classes).
1203 if (profile_guided && have_app_image_format) {
1204 // Recreate is true since we do not want to modify a mapped image. If the app is
1205 // already running and we modify the image file, it can cause crashes (b/27493510).
1206 image_fd.reset(open_output_file(image_path.c_str(),
1207 true /*recreate*/,
1208 0600 /*permissions*/),
1209 [image_path]() { unlink(image_path.c_str()); }
1210 );
1211 if (image_fd.get() < 0) {
1212 // Could not create application image file. Go on since we can compile without
1213 // it.
1214 LOG(ERROR) << "installd could not create '"
1215 << image_path
1216 << "' for image file during dexopt";
1217 } else if (!set_permissions_and_ownership(image_fd.get(),
1218 is_public,
1219 uid,
1220 image_path.c_str())) {
1221 image_fd.reset(-1);
1222 }
1223 }
1224 // If we have a valid image file path but no image fd, explicitly erase the image file.
1225 if (image_fd.get() < 0) {
1226 if (unlink(image_path.c_str()) < 0) {
1227 if (errno != ENOENT) {
1228 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1229 }
1230 }
1231 }
1232 }
1233
1234 ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
1235
1236 pid_t pid = fork();
1237 if (pid == 0) {
1238 /* child -- drop privileges before continuing */
1239 drop_capabilities(uid);
1240
1241 SetDex2OatAndPatchOatScheduling(boot_complete);
1242 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1243 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1244 _exit(67);
1245 }
1246
1247 if (dexopt_action == PATCHOAT_FOR_RELOCATION) {
1248 run_patchoat(input_fd.get(),
1249 in_vdex_fd.get(),
1250 out_oat_fd.get(),
1251 out_vdex_fd.get(),
1252 input_file,
1253 in_vdex_path_str.c_str(),
1254 out_oat_path,
1255 out_vdex_path_str.c_str(),
1256 pkgname,
1257 instruction_set);
1258 } else {
1259 // Pass dex2oat the relative path to the input file.
1260 const char *input_file_name = get_location_from_path(input_file);
1261 run_dex2oat(input_fd.get(),
1262 out_oat_fd.get(),
1263 in_vdex_fd.get(),
1264 out_vdex_fd.get(),
1265 image_fd.get(),
1266 input_file_name,
1267 out_oat_path,
1268 swap_fd.get(),
1269 instruction_set,
1270 compiler_filter,
1271 vm_safe_mode,
1272 debuggable,
1273 boot_complete,
1274 reference_profile_fd.get(),
1275 shared_libraries);
1276 }
1277 _exit(68); /* only get here on exec failure */
1278 } else {
1279 int res = wait_child(pid);
1280 if (res == 0) {
1281 ALOGV("DexInv: --- END '%s' (success) ---\n", input_file);
1282 } else {
1283 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", input_file, res);
1284 return -1;
1285 }
1286 }
1287
1288 struct utimbuf ut;
1289 ut.actime = input_stat.st_atime;
1290 ut.modtime = input_stat.st_mtime;
1291 utime(out_oat_path, &ut);
1292
1293 // We've been successful, don't delete output.
1294 out_oat_fd.SetCleanup(false);
1295 out_vdex_fd.SetCleanup(false);
1296 image_fd.SetCleanup(false);
1297 reference_profile_fd.SetCleanup(false);
1298
1299 return 0;
1300}
1301
1302// Helper for move_ab, so that we can have common failure-case cleanup.
1303static bool unlink_and_rename(const char* from, const char* to) {
1304 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1305 // return a failure.
1306 struct stat s;
1307 if (stat(to, &s) == 0) {
1308 if (!S_ISREG(s.st_mode)) {
1309 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1310 return false;
1311 }
1312 if (unlink(to) != 0) {
1313 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1314 return false;
1315 }
1316 } else {
1317 // This may be a permission problem. We could investigate the error code, but we'll just
1318 // let the rename failure do the work for us.
1319 }
1320
1321 // Try to rename "to" to "from."
1322 if (rename(from, to) != 0) {
1323 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1324 return false;
1325 }
1326 return true;
1327}
1328
1329// Move/rename a B artifact (from) to an A artifact (to).
1330static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1331 // Check whether B exists.
1332 {
1333 struct stat s;
1334 if (stat(b_path.c_str(), &s) != 0) {
1335 // Silently ignore for now. The service calling this isn't smart enough to understand
1336 // lack of artifacts at the moment.
1337 return false;
1338 }
1339 if (!S_ISREG(s.st_mode)) {
1340 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1341 // Try to unlink, but swallow errors.
1342 unlink(b_path.c_str());
1343 return false;
1344 }
1345 }
1346
1347 // Rename B to A.
1348 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1349 // Delete the b_path so we don't try again (or fail earlier).
1350 if (unlink(b_path.c_str()) != 0) {
1351 PLOG(ERROR) << "Could not unlink " << b_path;
1352 }
1353
1354 return false;
1355 }
1356
1357 return true;
1358}
1359
1360bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1361 // Get the current slot suffix. No suffix, no A/B.
1362 std::string slot_suffix;
1363 {
1364 char buf[kPropertyValueMax];
1365 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1366 return false;
1367 }
1368 slot_suffix = buf;
1369
1370 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1371 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1372 return false;
1373 }
1374 }
1375
1376 // Validate other inputs.
1377 if (validate_apk_path(apk_path) != 0) {
1378 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1379 return false;
1380 }
1381 if (validate_apk_path(oat_dir) != 0) {
1382 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1383 return false;
1384 }
1385
1386 char a_path[PKG_PATH_MAX];
1387 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1388 return false;
1389 }
1390 const std::string a_vdex_path = create_vdex_filename(a_path);
1391 const std::string a_image_path = create_image_filename(a_path);
1392
1393 // B path = A path + slot suffix.
1394 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1395 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1396 const std::string b_image_path = StringPrintf("%s.%s",
1397 a_image_path.c_str(),
1398 slot_suffix.c_str());
1399
1400 bool success = true;
1401 if (move_ab_path(b_path, a_path)) {
1402 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1403 // Note: we can live without an app image. As such, ignore failure to move the image file.
1404 // If we decide to require the app image, or the app image being moved correctly,
1405 // then change accordingly.
1406 constexpr bool kIgnoreAppImageFailure = true;
1407
1408 if (!a_image_path.empty()) {
1409 if (!move_ab_path(b_image_path, a_image_path)) {
1410 unlink(a_image_path.c_str());
1411 if (!kIgnoreAppImageFailure) {
1412 success = false;
1413 }
1414 }
1415 }
1416 } else {
1417 // Cleanup: delete B image, ignore errors.
1418 unlink(b_image_path.c_str());
1419 success = false;
1420 }
1421 } else {
1422 // Cleanup: delete B image, ignore errors.
1423 unlink(b_vdex_path.c_str());
1424 unlink(b_image_path.c_str());
1425 success = false;
1426 }
1427 return success;
1428}
1429
1430bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1431 // Delete the oat/odex file.
1432 char out_path[PKG_PATH_MAX];
1433 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
1434 return false;
1435 }
1436
1437 // In case of a permission failure report the issue. Otherwise just print a warning.
1438 auto unlink_and_check = [](const char* path) -> bool {
1439 int result = unlink(path);
1440 if (result != 0) {
1441 if (errno == EACCES || errno == EPERM) {
1442 PLOG(ERROR) << "Could not unlink " << path;
1443 return false;
1444 }
1445 PLOG(WARNING) << "Could not unlink " << path;
1446 }
1447 return true;
1448 };
1449
1450 // Delete the oat/odex file.
1451 bool return_value_oat = unlink_and_check(out_path);
1452
1453 // Derive and delete the app image.
1454 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1455
1456 // Report success.
1457 return return_value_oat && return_value_art;
1458}
1459
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001460int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1461 return dexopt(params[0], // apk_path
1462 atoi(params[1]), // uid
1463 params[2], // pkgname
1464 params[3], // instruction_set
1465 atoi(params[4]), // dexopt_needed
1466 params[5], // oat_dir
1467 atoi(params[6]), // dexopt_flags
1468 params[7], // compiler_filter
1469 parse_null(params[8]), // volume_uuid
1470 parse_null(params[9])); // shared_libraries
1471 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1472}
1473
1474} // namespace installd
1475} // namespace android