blob: 1565d0dd30114242c49dcc450feee645cdb08eac [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
30#include <android-base/logging.h>
31#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070032#include <android-base/strings.h>
33#include <android-base/unique_fd.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070034#include <cutils/properties.h>
35#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070036#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#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//
Calin Juravle7a570e82017-01-14 16:23:30 -0800907// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700908// [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//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700930class Dex2oatFileWrapper {
931 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800932 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 }
934
Calin Juravle7a570e82017-01-14 16:23:30 -0800935 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
936 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
937
938 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
939 value_ = other.value_;
940 cleanup_ = other.cleanup_;
941 do_cleanup_ = other.do_cleanup_;
942 auto_close_ = other.auto_close_;
943 other.release();
944 }
945
946 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
947 value_ = other.value_;
948 cleanup_ = other.cleanup_;
949 do_cleanup_ = other.do_cleanup_;
950 auto_close_ = other.auto_close_;
951 other.release();
952 return *this;
953 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954
955 ~Dex2oatFileWrapper() {
956 reset(-1);
957 }
958
959 int get() {
960 return value_;
961 }
962
963 void SetCleanup(bool cleanup) {
964 do_cleanup_ = cleanup;
965 }
966
967 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800968 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700969 close(value_);
970 }
971 if (do_cleanup_ && cleanup_ != nullptr) {
972 cleanup_();
973 }
974
975 value_ = new_value;
976 }
977
Calin Juravle7a570e82017-01-14 16:23:30 -0800978 void reset(int new_value, std::function<void ()> new_cleanup) {
979 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700980 close(value_);
981 }
982 if (do_cleanup_ && cleanup_ != nullptr) {
983 cleanup_();
984 }
985
986 value_ = new_value;
987 cleanup_ = new_cleanup;
988 }
989
Calin Juravle7a570e82017-01-14 16:23:30 -0800990 void DisableAutoClose() {
991 auto_close_ = false;
992 }
993
Jeff Sharkey90aff262016-12-12 14:28:24 -0700994 private:
Calin Juravle7a570e82017-01-14 16:23:30 -0800995 void release() {
996 value_ = -1;
997 do_cleanup_ = false;
998 cleanup_ = nullptr;
999 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001000 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001001 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001003 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004};
1005
Calin Juravle7a570e82017-01-14 16:23:30 -08001006// (re)Creates the app image if needed.
1007Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
1008 bool is_public, int uid) {
1009 // Use app images only if it is enabled (by a set image format) and we are compiling
1010 // profile-guided (so the app image doesn't conservatively contain all classes).
1011 if (!profile_guided) {
1012 return Dex2oatFileWrapper();
1013 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001014
Calin Juravle7a570e82017-01-14 16:23:30 -08001015 const std::string image_path = create_image_filename(out_oat_path);
1016 if (image_path.empty()) {
1017 // Happens when the out_oat_path has an unknown extension.
1018 return Dex2oatFileWrapper();
1019 }
1020 char app_image_format[kPropertyValueMax];
1021 bool have_app_image_format =
1022 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1023 if (!have_app_image_format) {
1024 return Dex2oatFileWrapper();
1025 }
1026 // Recreate is true since we do not want to modify a mapped image. If the app is
1027 // already running and we modify the image file, it can cause crashes (b/27493510).
1028 Dex2oatFileWrapper wrapper_fd(
1029 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1030 [image_path]() { unlink(image_path.c_str()); });
1031 if (wrapper_fd.get() < 0) {
1032 // Could not create application image file. Go on since we can compile without it.
1033 LOG(ERROR) << "installd could not create '" << image_path
1034 << "' for image file during dexopt";
1035 // If we have a valid image file path but no image fd, explicitly erase the image file.
1036 if (unlink(image_path.c_str()) < 0) {
1037 if (errno != ENOENT) {
1038 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1039 }
1040 }
1041 } else if (!set_permissions_and_ownership(
1042 wrapper_fd.get(), is_public, uid, image_path.c_str())) {
1043 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1044 wrapper_fd.reset(-1);
1045 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001046
Calin Juravle7a570e82017-01-14 16:23:30 -08001047 return wrapper_fd;
1048}
1049
1050// Creates the dexopt swap file if necessary and return its fd.
1051// Returns -1 if there's no need for a swap or in case of errors.
1052base::unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
1053 if (!ShouldUseSwapFileForDexopt()) {
1054 return base::unique_fd();
1055 }
1056 // Make sure there really is enough space.
1057 char swap_file_name[PKG_PATH_MAX];
1058 strcpy(swap_file_name, out_oat_path);
1059 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
1060 return base::unique_fd();
1061 }
1062 base::unique_fd swap_fd(open_output_file(
1063 swap_file_name, /*recreate*/true, /*permissions*/0600));
1064 if (swap_fd.get() < 0) {
1065 // Could not create swap file. Optimistically go on and hope that we can compile
1066 // without it.
1067 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1068 } else {
1069 // Immediately unlink. We don't really want to hit flash.
1070 if (unlink(swap_file_name) < 0) {
1071 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1072 }
1073 }
1074 return swap_fd;
1075}
1076
1077// Opens the reference profiles if needed.
1078// Note that the reference profile might not exist so it's OK if the fd will be -1.
1079Dex2oatFileWrapper maybe_open_reference_profile(const char* pkgname, bool profile_guided,
1080 bool is_public, int uid) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001081 // Public apps should not be compiled with profile information ever. Same goes for the special
1082 // package '*' used for the system server.
Calin Juravle7a570e82017-01-14 16:23:30 -08001083 if (profile_guided && !is_public && (pkgname[0] != '*')) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001084 // Open reference profile in read only mode as dex2oat does not get write permissions.
1085 const std::string pkgname_str(pkgname);
Calin Juravle7a570e82017-01-14 16:23:30 -08001086 return Dex2oatFileWrapper(
1087 open_reference_profile(uid, pkgname, /*read_write*/ false),
1088 [pkgname_str]() {
1089 clear_reference_profile(pkgname_str.c_str());
1090 });
1091 } else {
1092 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001093 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001094}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001095
Calin Juravle7a570e82017-01-14 16:23:30 -08001096// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1097// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1098bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
1099 const char* instruction_set, bool is_public, int uid,
1100 Dex2oatFileWrapper* in_vdex_wrapper_fd,
1101 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1102 CHECK(in_vdex_wrapper_fd != nullptr);
1103 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1105 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001106 char in_odex_path[PKG_PATH_MAX];
1107 int dexopt_action = abs(dexopt_needed);
1108 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001109 std::string in_vdex_path_str;
Richard Uhler76cc0272016-12-08 10:46:35 +00001110 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001111 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1112 const char* path = nullptr;
1113 if (is_odex_location) {
1114 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1115 path = in_odex_path;
1116 } else {
1117 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001118 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001119 }
1120 } else {
1121 path = out_oat_path;
1122 }
1123 in_vdex_path_str = create_vdex_filename(path);
1124 if (in_vdex_path_str.empty()) {
1125 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001126 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001128 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
1129 // When we dex2oat because iof boot image change, we are going to update
1130 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001131 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001132 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001133 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001134 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135 }
1136
1137 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001138 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001139 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001141 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001142
1143 // If we are compiling because the boot image is out of date, we do not
1144 // need to recreate a vdex, and can use the same existing one.
1145 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001146 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001147 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001148 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1149 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1150 // wrapper).
1151 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001152 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001153 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001154 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1155 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 if (out_vdex_wrapper_fd->get() < 0) {
1157 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1158 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001159 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001160 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001161 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
1162 out_vdex_path_str.c_str())) {
1163 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1164 return false;
1165 }
1166
1167 // If we got here we successfully opened the vdex files.
1168 return true;
1169}
1170
1171// Opens the output oat file for the given apk.
1172// If successful it stores the output path into out_oat_path and returns true.
1173Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
1174 bool is_public, int uid, const char* instruction_set, char* out_oat_path) {
1175 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
1176 return Dex2oatFileWrapper();
1177 }
1178 const std::string out_oat_path_str(out_oat_path);
1179 Dex2oatFileWrapper wrapper_fd(
1180 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1181 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1182 if (wrapper_fd.get() < 0) {
1183 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
1184 } else if (!set_permissions_and_ownership(wrapper_fd.get(), is_public, uid, out_oat_path)) {
1185 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1186 wrapper_fd.reset(-1);
1187 }
1188 return wrapper_fd;
1189}
1190
1191// Updates the access times of out_oat_path based on those from apk_path.
1192void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1193 struct stat input_stat;
1194 memset(&input_stat, 0, sizeof(input_stat));
1195 if (stat(apk_path, &input_stat) != 0) {
1196 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1197 return;
1198 }
1199
1200 struct utimbuf ut;
1201 ut.actime = input_stat.st_atime;
1202 ut.modtime = input_stat.st_mtime;
1203 if (utime(out_oat_path, &ut) != 0) {
1204 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1205 }
1206}
1207
1208int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1209 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1210 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
1211 CHECK(pkgname != nullptr);
1212 CHECK(pkgname[0] != 0);
1213 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1214 LOG_FATAL("dexopt flags contains unknown fields\n");
1215 }
1216
1217 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1218 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1219 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1220 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1221 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1222
1223 // Open the input file.
1224 base::unique_fd input_fd(open(apk_path, O_RDONLY, 0));
1225 if (input_fd.get() < 0) {
1226 ALOGE("installd cannot open '%s' for input during dexopt\n", apk_path);
1227 return -1;
1228 }
1229
1230 // Create the output OAT file.
1231 char out_oat_path[PKG_PATH_MAX];
1232 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(apk_path, oat_dir, is_public, uid,
1233 instruction_set, out_oat_path);
1234 if (out_oat_fd.get() < 0) {
1235 return -1;
1236 }
1237
1238 // Open vdex files.
1239 Dex2oatFileWrapper in_vdex_fd;
1240 Dex2oatFileWrapper out_vdex_fd;
1241 if (!open_vdex_files(apk_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
1242 &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001243 return -1;
1244 }
1245
1246 // Create a swap file if necessary.
Calin Juravle7a570e82017-01-14 16:23:30 -08001247 base::unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001248
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 // Create the app image file if needed.
1250 Dex2oatFileWrapper image_fd =
1251 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001252
Calin Juravle7a570e82017-01-14 16:23:30 -08001253 // Open the reference profile if needed.
1254 Dex2oatFileWrapper reference_profile_fd =
1255 maybe_open_reference_profile(pkgname, profile_guided, is_public, uid);
1256
1257 ALOGV("DexInv: --- BEGIN '%s' ---\n", apk_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001258
1259 pid_t pid = fork();
1260 if (pid == 0) {
1261 /* child -- drop privileges before continuing */
1262 drop_capabilities(uid);
1263
Richard Uhler76cc0272016-12-08 10:46:35 +00001264 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001265 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1266 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1267 _exit(67);
1268 }
1269
Richard Uhler76cc0272016-12-08 10:46:35 +00001270 // Pass dex2oat the relative path to the input file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001271 const char *input_file_name = get_location_from_path(apk_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001272 run_dex2oat(input_fd.get(),
1273 out_oat_fd.get(),
1274 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001275 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001276 image_fd.get(),
1277 input_file_name,
1278 out_oat_path,
1279 swap_fd.get(),
1280 instruction_set,
1281 compiler_filter,
1282 vm_safe_mode,
1283 debuggable,
1284 boot_complete,
1285 reference_profile_fd.get(),
1286 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001287 _exit(68); /* only get here on exec failure */
1288 } else {
1289 int res = wait_child(pid);
1290 if (res == 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 ALOGV("DexInv: --- END '%s' (success) ---\n", apk_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", apk_path, res);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001294 return -1;
1295 }
1296 }
1297
Calin Juravle7a570e82017-01-14 16:23:30 -08001298 update_out_oat_access_times(apk_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001299
1300 // We've been successful, don't delete output.
1301 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001302 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001303 image_fd.SetCleanup(false);
1304 reference_profile_fd.SetCleanup(false);
1305
1306 return 0;
1307}
1308
1309// Helper for move_ab, so that we can have common failure-case cleanup.
1310static bool unlink_and_rename(const char* from, const char* to) {
1311 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1312 // return a failure.
1313 struct stat s;
1314 if (stat(to, &s) == 0) {
1315 if (!S_ISREG(s.st_mode)) {
1316 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1317 return false;
1318 }
1319 if (unlink(to) != 0) {
1320 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1321 return false;
1322 }
1323 } else {
1324 // This may be a permission problem. We could investigate the error code, but we'll just
1325 // let the rename failure do the work for us.
1326 }
1327
1328 // Try to rename "to" to "from."
1329 if (rename(from, to) != 0) {
1330 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1331 return false;
1332 }
1333 return true;
1334}
1335
1336// Move/rename a B artifact (from) to an A artifact (to).
1337static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1338 // Check whether B exists.
1339 {
1340 struct stat s;
1341 if (stat(b_path.c_str(), &s) != 0) {
1342 // Silently ignore for now. The service calling this isn't smart enough to understand
1343 // lack of artifacts at the moment.
1344 return false;
1345 }
1346 if (!S_ISREG(s.st_mode)) {
1347 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1348 // Try to unlink, but swallow errors.
1349 unlink(b_path.c_str());
1350 return false;
1351 }
1352 }
1353
1354 // Rename B to A.
1355 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1356 // Delete the b_path so we don't try again (or fail earlier).
1357 if (unlink(b_path.c_str()) != 0) {
1358 PLOG(ERROR) << "Could not unlink " << b_path;
1359 }
1360
1361 return false;
1362 }
1363
1364 return true;
1365}
1366
1367bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1368 // Get the current slot suffix. No suffix, no A/B.
1369 std::string slot_suffix;
1370 {
1371 char buf[kPropertyValueMax];
1372 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1373 return false;
1374 }
1375 slot_suffix = buf;
1376
1377 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1378 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1379 return false;
1380 }
1381 }
1382
1383 // Validate other inputs.
1384 if (validate_apk_path(apk_path) != 0) {
1385 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1386 return false;
1387 }
1388 if (validate_apk_path(oat_dir) != 0) {
1389 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1390 return false;
1391 }
1392
1393 char a_path[PKG_PATH_MAX];
1394 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1395 return false;
1396 }
1397 const std::string a_vdex_path = create_vdex_filename(a_path);
1398 const std::string a_image_path = create_image_filename(a_path);
1399
1400 // B path = A path + slot suffix.
1401 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1402 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1403 const std::string b_image_path = StringPrintf("%s.%s",
1404 a_image_path.c_str(),
1405 slot_suffix.c_str());
1406
1407 bool success = true;
1408 if (move_ab_path(b_path, a_path)) {
1409 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1410 // Note: we can live without an app image. As such, ignore failure to move the image file.
1411 // If we decide to require the app image, or the app image being moved correctly,
1412 // then change accordingly.
1413 constexpr bool kIgnoreAppImageFailure = true;
1414
1415 if (!a_image_path.empty()) {
1416 if (!move_ab_path(b_image_path, a_image_path)) {
1417 unlink(a_image_path.c_str());
1418 if (!kIgnoreAppImageFailure) {
1419 success = false;
1420 }
1421 }
1422 }
1423 } else {
1424 // Cleanup: delete B image, ignore errors.
1425 unlink(b_image_path.c_str());
1426 success = false;
1427 }
1428 } else {
1429 // Cleanup: delete B image, ignore errors.
1430 unlink(b_vdex_path.c_str());
1431 unlink(b_image_path.c_str());
1432 success = false;
1433 }
1434 return success;
1435}
1436
1437bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1438 // Delete the oat/odex file.
1439 char out_path[PKG_PATH_MAX];
1440 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
1441 return false;
1442 }
1443
1444 // In case of a permission failure report the issue. Otherwise just print a warning.
1445 auto unlink_and_check = [](const char* path) -> bool {
1446 int result = unlink(path);
1447 if (result != 0) {
1448 if (errno == EACCES || errno == EPERM) {
1449 PLOG(ERROR) << "Could not unlink " << path;
1450 return false;
1451 }
1452 PLOG(WARNING) << "Could not unlink " << path;
1453 }
1454 return true;
1455 };
1456
1457 // Delete the oat/odex file.
1458 bool return_value_oat = unlink_and_check(out_path);
1459
1460 // Derive and delete the app image.
1461 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1462
1463 // Report success.
1464 return return_value_oat && return_value_art;
1465}
1466
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001467int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1468 return dexopt(params[0], // apk_path
1469 atoi(params[1]), // uid
1470 params[2], // pkgname
1471 params[3], // instruction_set
1472 atoi(params[4]), // dexopt_needed
1473 params[5], // oat_dir
1474 atoi(params[6]), // dexopt_flags
1475 params[7], // compiler_filter
1476 parse_null(params[8]), // volume_uuid
1477 parse_null(params[9])); // shared_libraries
1478 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1479}
1480
1481} // namespace installd
1482} // namespace android