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