blob: 5d841574362396f3ef56f6eae3d906743fcdeb31 [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
George Burgess IV36cebe772017-01-25 11:52:01 -0800238 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
239 // use arraysize instead.
240 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
241 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
242 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
243 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
244 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
245 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
246 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
247 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
248 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
249 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
250 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
251 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700252 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800253 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700254 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800255 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700256
257 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
258 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
259 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
260 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
261 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
262 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
263 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
264 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
265 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
266 if (swap_fd >= 0) {
267 have_dex2oat_swap_fd = true;
268 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
269 }
270 if (image_fd >= 0) {
271 have_dex2oat_image_fd = true;
272 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
273 }
274
275 if (have_dex2oat_Xms_flag) {
276 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
277 }
278 if (have_dex2oat_Xmx_flag) {
279 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
280 }
281
282 // Compute compiler filter.
283
284 bool have_dex2oat_compiler_filter_flag;
285 if (skip_compilation) {
286 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
287 have_dex2oat_compiler_filter_flag = true;
288 have_dex2oat_relocation_skip_flag = true;
289 } else if (vm_safe_mode) {
290 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
291 have_dex2oat_compiler_filter_flag = true;
292 } else if (compiler_filter != nullptr &&
293 strlen(compiler_filter) + strlen("--compiler-filter=") <
294 arraysize(dex2oat_compiler_filter_arg)) {
295 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
296 have_dex2oat_compiler_filter_flag = true;
297 } else {
298 char dex2oat_compiler_filter_flag[kPropertyValueMax];
299 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
300 dex2oat_compiler_filter_flag, NULL) > 0;
301 if (have_dex2oat_compiler_filter_flag) {
302 sprintf(dex2oat_compiler_filter_arg,
303 "--compiler-filter=%s",
304 dex2oat_compiler_filter_flag);
305 }
306 }
307
308 // Check whether all apps should be compiled debuggable.
309 if (!debuggable) {
310 char prop_buf[kPropertyValueMax];
311 debuggable =
312 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
313 (prop_buf[0] == '1');
314 }
315 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
316 if (profile_fd != -1) {
317 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
318 }
319
320
321 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
322
323 const char* argv[9 // program name, mandatory arguments and the final NULL
324 + (have_dex2oat_isa_variant ? 1 : 0)
325 + (have_dex2oat_isa_features ? 1 : 0)
326 + (have_dex2oat_Xms_flag ? 2 : 0)
327 + (have_dex2oat_Xmx_flag ? 2 : 0)
328 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
329 + (have_dex2oat_threads_flag ? 1 : 0)
330 + (have_dex2oat_swap_fd ? 1 : 0)
331 + (have_dex2oat_image_fd ? 1 : 0)
332 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
333 + (generate_debug_info ? 1 : 0)
334 + (debuggable ? 1 : 0)
335 + (have_app_image_format ? 1 : 0)
336 + dex2oat_flags_count
337 + (profile_fd == -1 ? 0 : 1)
338 + (shared_libraries != nullptr ? 4 : 0)
339 + (have_dex2oat_large_app_threshold ? 1 : 0)];
340 int i = 0;
341 argv[i++] = DEX2OAT_BIN;
342 argv[i++] = zip_fd_arg;
343 argv[i++] = zip_location_arg;
344 argv[i++] = input_vdex_fd_arg;
345 argv[i++] = output_vdex_fd_arg;
346 argv[i++] = oat_fd_arg;
347 argv[i++] = oat_location_arg;
348 argv[i++] = instruction_set_arg;
349 if (have_dex2oat_isa_variant) {
350 argv[i++] = instruction_set_variant_arg;
351 }
352 if (have_dex2oat_isa_features) {
353 argv[i++] = instruction_set_features_arg;
354 }
355 if (have_dex2oat_Xms_flag) {
356 argv[i++] = RUNTIME_ARG;
357 argv[i++] = dex2oat_Xms_arg;
358 }
359 if (have_dex2oat_Xmx_flag) {
360 argv[i++] = RUNTIME_ARG;
361 argv[i++] = dex2oat_Xmx_arg;
362 }
363 if (have_dex2oat_compiler_filter_flag) {
364 argv[i++] = dex2oat_compiler_filter_arg;
365 }
366 if (have_dex2oat_threads_flag) {
367 argv[i++] = dex2oat_threads_arg;
368 }
369 if (have_dex2oat_swap_fd) {
370 argv[i++] = dex2oat_swap_fd;
371 }
372 if (have_dex2oat_image_fd) {
373 argv[i++] = dex2oat_image_fd;
374 }
375 if (generate_debug_info) {
376 argv[i++] = "--generate-debug-info";
377 }
378 if (debuggable) {
379 argv[i++] = "--debuggable";
380 }
381 if (have_app_image_format) {
382 argv[i++] = image_format_arg;
383 }
384 if (have_dex2oat_large_app_threshold) {
385 argv[i++] = dex2oat_large_app_threshold_arg;
386 }
387 if (dex2oat_flags_count) {
388 i += split(dex2oat_flags, argv + i);
389 }
390 if (have_dex2oat_relocation_skip_flag) {
391 argv[i++] = RUNTIME_ARG;
392 argv[i++] = dex2oat_norelocation;
393 }
394 if (profile_fd != -1) {
395 argv[i++] = profile_arg;
396 }
397 if (shared_libraries != nullptr) {
398 argv[i++] = RUNTIME_ARG;
399 argv[i++] = "-classpath";
400 argv[i++] = RUNTIME_ARG;
401 argv[i++] = shared_libraries;
402 }
403 // Do not add after dex2oat_flags, they should override others for debugging.
404 argv[i] = NULL;
405
406 execv(DEX2OAT_BIN, (char * const *)argv);
407 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
408}
409
410/*
411 * Whether dexopt should use a swap file when compiling an APK.
412 *
413 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
414 * itself, anyways).
415 *
416 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
417 *
418 * Otherwise, return true if this is a low-mem device.
419 *
420 * Otherwise, return default value.
421 */
422static bool kAlwaysProvideSwapFile = false;
423static bool kDefaultProvideSwapFile = true;
424
425static bool ShouldUseSwapFileForDexopt() {
426 if (kAlwaysProvideSwapFile) {
427 return true;
428 }
429
430 // Check the "override" property. If it exists, return value == "true".
431 char dex2oat_prop_buf[kPropertyValueMax];
432 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
433 if (strcmp(dex2oat_prop_buf, "true") == 0) {
434 return true;
435 } else {
436 return false;
437 }
438 }
439
440 // Shortcut for default value. This is an implementation optimization for the process sketched
441 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
442 // as low-mem is never returning false. The compiler will optimize this away if it can.
443 if (kDefaultProvideSwapFile) {
444 return true;
445 }
446
447 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
448 if (is_low_mem) {
449 return true;
450 }
451
452 // Default value must be false here.
453 return kDefaultProvideSwapFile;
454}
455
Richard Uhler76cc0272016-12-08 10:46:35 +0000456static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700457 if (set_to_bg) {
458 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
459 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
460 exit(70);
461 }
462 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
463 ALOGE("setpriority failed: %s\n", strerror(errno));
464 exit(71);
465 }
466 }
467}
468
469static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
470 for (size_t i = 0; i < fds.size(); i++) {
471 if (close(fds[i]) != 0) {
472 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
473 }
474 }
475}
476
477static fd_t open_profile_dir(const std::string& profile_dir) {
478 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
479 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
480 if (profile_dir_fd < 0) {
481 // In a multi-user environment, these directories can be created at
482 // different points and it's possible we'll attempt to open a profile
483 // dir before it exists.
484 if (errno != ENOENT) {
485 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
486 }
487 }
488 return profile_dir_fd;
489}
490
491static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
492 fd_t profile_dir_fd = open_profile_dir(profile_dir);
493 if (profile_dir_fd < 0) {
494 return -1;
495 }
496
497 fd_t profile_fd = -1;
498 std::string profile_file = create_primary_profile(profile_dir);
499
George Burgess IV3ef54f22017-01-25 11:36:12 -0800500 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW, 0600));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700501 if (profile_fd == -1) {
502 // It's not an error if the profile file does not exist.
503 if (errno != ENOENT) {
504 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
505 }
506 }
507 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
508 if (close(profile_dir_fd) != 0) {
509 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
510 }
511 return profile_fd;
512}
513
514static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
515 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
516 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
517}
518
519static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
520 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
521 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
522 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
523 if (fd < 0) {
524 return -1;
525 }
526 if (read_write) {
527 // Fix the owner.
528 if (fchown(fd, uid, uid) < 0) {
529 close(fd);
530 return -1;
531 }
532 }
533 return fd;
534}
535
536static void open_profile_files(uid_t uid, const char* pkgname,
537 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
538 // Open the reference profile in read-write mode as profman might need to save the merge.
539 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
540 if (*reference_profile_fd < 0) {
541 // We can't access the reference profile file.
542 return;
543 }
544
545 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
546 for (auto user : users) {
547 fd_t profile_fd = open_primary_profile_file(user, pkgname);
548 // Add to the lists only if both fds are valid.
549 if (profile_fd >= 0) {
550 profiles_fd->push_back(profile_fd);
551 }
552 }
553}
554
555static void drop_capabilities(uid_t uid) {
556 if (setgid(uid) != 0) {
557 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
558 exit(64);
559 }
560 if (setuid(uid) != 0) {
561 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
562 exit(65);
563 }
564 // drop capabilities
565 struct __user_cap_header_struct capheader;
566 struct __user_cap_data_struct capdata[2];
567 memset(&capheader, 0, sizeof(capheader));
568 memset(&capdata, 0, sizeof(capdata));
569 capheader.version = _LINUX_CAPABILITY_VERSION_3;
570 if (capset(&capheader, &capdata[0]) < 0) {
571 ALOGE("capset failed: %s\n", strerror(errno));
572 exit(66);
573 }
574}
575
576static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
577static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
578static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
579static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
580static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
581
582static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
583 static const size_t MAX_INT_LEN = 32;
584 static const char* PROFMAN_BIN = "/system/bin/profman";
585
586 std::vector<std::string> profile_args(profiles_fd.size());
587 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
588 for (size_t k = 0; k < profiles_fd.size(); k++) {
589 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
590 profile_args[k].assign(profile_buf);
591 }
592 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
593 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
594
595 // program name, reference profile fd, the final NULL and the profile fds
596 const char* argv[3 + profiles_fd.size()];
597 int i = 0;
598 argv[i++] = PROFMAN_BIN;
599 argv[i++] = reference_profile_arg;
600 for (size_t k = 0; k < profile_args.size(); k++) {
601 argv[i++] = profile_args[k].c_str();
602 }
603 // Do not add after dex2oat_flags, they should override others for debugging.
604 argv[i] = NULL;
605
606 execv(PROFMAN_BIN, (char * const *)argv);
607 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
608 exit(68); /* only get here on exec failure */
609}
610
611// Decides if profile guided compilation is needed or not based on existing profiles.
612// Returns true if there is enough information in the current profiles that worth
613// a re-compilation of the package.
614// If the return value is true all the current profiles would have been merged into
615// the reference profiles accessible with open_reference_profile().
616bool analyse_profiles(uid_t uid, const char* pkgname) {
617 std::vector<fd_t> profiles_fd;
618 fd_t reference_profile_fd = -1;
619 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
620 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
621 // Skip profile guided compilation because no profiles were found.
622 // Or if the reference profile info couldn't be opened.
623 close_all_fds(profiles_fd, "profiles_fd");
624 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
625 PLOG(WARNING) << "Failed to close fd for reference profile";
626 }
627 return false;
628 }
629
630 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
631
632 pid_t pid = fork();
633 if (pid == 0) {
634 /* child -- drop privileges before continuing */
635 drop_capabilities(uid);
636 run_profman_merge(profiles_fd, reference_profile_fd);
637 exit(68); /* only get here on exec failure */
638 }
639 /* parent */
640 int return_code = wait_child(pid);
641 bool need_to_compile = false;
642 bool should_clear_current_profiles = false;
643 bool should_clear_reference_profile = false;
644 if (!WIFEXITED(return_code)) {
645 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
646 } else {
647 return_code = WEXITSTATUS(return_code);
648 switch (return_code) {
649 case PROFMAN_BIN_RETURN_CODE_COMPILE:
650 need_to_compile = true;
651 should_clear_current_profiles = true;
652 should_clear_reference_profile = false;
653 break;
654 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
655 need_to_compile = false;
656 should_clear_current_profiles = false;
657 should_clear_reference_profile = false;
658 break;
659 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
660 LOG(WARNING) << "Bad profiles for package " << pkgname;
661 need_to_compile = false;
662 should_clear_current_profiles = true;
663 should_clear_reference_profile = true;
664 break;
665 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
666 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
667 // Temporary IO problem (e.g. locking). Ignore but log a warning.
668 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
669 need_to_compile = false;
670 should_clear_current_profiles = false;
671 should_clear_reference_profile = false;
672 break;
673 default:
674 // Unknown return code or error. Unlink profiles.
675 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
676 << ": " << return_code;
677 need_to_compile = false;
678 should_clear_current_profiles = true;
679 should_clear_reference_profile = true;
680 break;
681 }
682 }
683 close_all_fds(profiles_fd, "profiles_fd");
684 if (close(reference_profile_fd) != 0) {
685 PLOG(WARNING) << "Failed to close fd for reference profile";
686 }
687 if (should_clear_current_profiles) {
688 clear_current_profiles(pkgname);
689 }
690 if (should_clear_reference_profile) {
691 clear_reference_profile(pkgname);
692 }
693 return need_to_compile;
694}
695
696static void run_profman_dump(const std::vector<fd_t>& profile_fds,
697 fd_t reference_profile_fd,
698 const std::vector<std::string>& dex_locations,
699 const std::vector<fd_t>& apk_fds,
700 fd_t output_fd) {
701 std::vector<std::string> profman_args;
702 static const char* PROFMAN_BIN = "/system/bin/profman";
703 profman_args.push_back(PROFMAN_BIN);
704 profman_args.push_back("--dump-only");
705 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
706 if (reference_profile_fd != -1) {
707 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
708 reference_profile_fd));
709 }
710 for (fd_t profile_fd : profile_fds) {
711 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
712 }
713 for (const std::string& dex_location : dex_locations) {
714 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
715 }
716 for (fd_t apk_fd : apk_fds) {
717 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
718 }
719 const char **argv = new const char*[profman_args.size() + 1];
720 size_t i = 0;
721 for (const std::string& profman_arg : profman_args) {
722 argv[i++] = profman_arg.c_str();
723 }
724 argv[i] = NULL;
725
726 execv(PROFMAN_BIN, (char * const *)argv);
727 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
728 exit(68); /* only get here on exec failure */
729}
730
731static const char* get_location_from_path(const char* path) {
732 static constexpr char kLocationSeparator = '/';
733 const char *location = strrchr(path, kLocationSeparator);
734 if (location == NULL) {
735 return path;
736 } else {
737 // Skip the separator character.
738 return location + 1;
739 }
740}
741
742bool dump_profiles(int32_t uid, const char* pkgname, const char* code_paths) {
743 std::vector<fd_t> profile_fds;
744 fd_t reference_profile_fd = -1;
745 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
746
747 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
748
749 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
750
751 const bool has_reference_profile = (reference_profile_fd != -1);
752 const bool has_profiles = !profile_fds.empty();
753
754 if (!has_reference_profile && !has_profiles) {
755 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
756 return false;
757 }
758
George Burgess IV3ef54f22017-01-25 11:36:12 -0800759 fd_t output_fd = open(out_file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700760 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
761 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
762 return false;
763 }
764 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
765 std::vector<std::string> dex_locations;
766 std::vector<fd_t> apk_fds;
767 for (const std::string& code_full_path : code_full_paths) {
768 const char* full_path = code_full_path.c_str();
769 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
770 if (apk_fd == -1) {
771 ALOGE("installd cannot open '%s'\n", full_path);
772 return false;
773 }
774 dex_locations.push_back(get_location_from_path(full_path));
775 apk_fds.push_back(apk_fd);
776 }
777
778 pid_t pid = fork();
779 if (pid == 0) {
780 /* child -- drop privileges before continuing */
781 drop_capabilities(uid);
782 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
783 apk_fds, output_fd);
784 exit(68); /* only get here on exec failure */
785 }
786 /* parent */
787 close_all_fds(apk_fds, "apk_fds");
788 close_all_fds(profile_fds, "profile_fds");
789 if (close(reference_profile_fd) != 0) {
790 PLOG(WARNING) << "Failed to close fd for reference profile";
791 }
792 int return_code = wait_child(pid);
793 if (!WIFEXITED(return_code)) {
794 LOG(WARNING) << "profman failed for package " << pkgname << ": "
795 << return_code;
796 return false;
797 }
798 return true;
799}
800
801static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
802 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
803 if (EndsWith(oat_path, ".dex")) {
804 std::string new_path = oat_path;
805 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
806 CHECK(EndsWith(new_path, new_ext.c_str()));
807 return new_path;
808 }
809
810 // An odex entry. Not that this may not be an extension, e.g., in the OTA
811 // case (where the base name will have an extension for the B artifact).
812 size_t odex_pos = oat_path.rfind(".odex");
813 if (odex_pos != std::string::npos) {
814 std::string new_path = oat_path;
815 new_path.replace(odex_pos, strlen(".odex"), new_ext);
816 CHECK_NE(new_path.find(new_ext), std::string::npos);
817 return new_path;
818 }
819
820 // Don't know how to handle this.
821 return "";
822}
823
824// Translate the given oat path to an art (app image) path. An empty string
825// denotes an error.
826static std::string create_image_filename(const std::string& oat_path) {
827 return replace_file_extension(oat_path, ".art");
828}
829
830// Translate the given oat path to a vdex path. An empty string denotes an error.
831static std::string create_vdex_filename(const std::string& oat_path) {
832 return replace_file_extension(oat_path, ".vdex");
833}
834
835static bool add_extension_to_file_name(char* file_name, const char* extension) {
836 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
837 return false;
838 }
839 strcat(file_name, extension);
840 return true;
841}
842
843static int open_output_file(const char* file_name, bool recreate, int permissions) {
844 int flags = O_RDWR | O_CREAT;
845 if (recreate) {
846 if (unlink(file_name) < 0) {
847 if (errno != ENOENT) {
848 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
849 }
850 }
851 flags |= O_EXCL;
852 }
853 return open(file_name, flags, permissions);
854}
855
856static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
857 if (fchmod(fd,
858 S_IRUSR|S_IWUSR|S_IRGRP |
859 (is_public ? S_IROTH : 0)) < 0) {
860 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
861 return false;
862 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
863 ALOGE("installd cannot chown '%s' during dexopt\n", path);
864 return false;
865 }
866 return true;
867}
868
869static bool IsOutputDalvikCache(const char* oat_dir) {
870 // InstallerConnection.java (which invokes installd) transforms Java null arguments
871 // into '!'. Play it safe by handling it both.
872 // TODO: ensure we never get null.
873 // TODO: pass a flag instead of inferring if the output is dalvik cache.
874 return oat_dir == nullptr || oat_dir[0] == '!';
875}
876
877static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
878 const char* oat_dir, /*out*/ char* out_oat_path) {
879 // Early best-effort check whether we can fit the the path into our buffers.
880 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
881 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
882 // extension to the cache path (5 bytes).
883 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
884 ALOGE("apk_path too long '%s'\n", apk_path);
885 return false;
886 }
887
888 if (!IsOutputDalvikCache(oat_dir)) {
889 if (validate_apk_path(oat_dir)) {
890 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
891 return false;
892 }
893 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
894 return false;
895 }
896 } else {
897 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
898 return false;
899 }
900 }
901 return true;
902}
903
904// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
905// on destruction. It will also run the given cleanup (unless told not to) after closing.
906//
907// Usage example:
908//
Calin Juravle7a570e82017-01-14 16:23:30 -0800909// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910// [name]() {
911// unlink(name.c_str());
912// });
913// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
914// wrapper if captured as a reference.
915//
916// if (file.get() == -1) {
917// // Error opening...
918// }
919//
920// ...
921// if (error) {
922// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
923// // and delete the file (after the fd is closed).
924// return -1;
925// }
926//
927// (Success case)
928// file.SetCleanup(false);
929// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
930// // (leaving the file around; after the fd is closed).
931//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700932class Dex2oatFileWrapper {
933 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800934 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700935 }
936
Calin Juravle7a570e82017-01-14 16:23:30 -0800937 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
938 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
939
940 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
941 value_ = other.value_;
942 cleanup_ = other.cleanup_;
943 do_cleanup_ = other.do_cleanup_;
944 auto_close_ = other.auto_close_;
945 other.release();
946 }
947
948 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
949 value_ = other.value_;
950 cleanup_ = other.cleanup_;
951 do_cleanup_ = other.do_cleanup_;
952 auto_close_ = other.auto_close_;
953 other.release();
954 return *this;
955 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956
957 ~Dex2oatFileWrapper() {
958 reset(-1);
959 }
960
961 int get() {
962 return value_;
963 }
964
965 void SetCleanup(bool cleanup) {
966 do_cleanup_ = cleanup;
967 }
968
969 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800970 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700971 close(value_);
972 }
973 if (do_cleanup_ && cleanup_ != nullptr) {
974 cleanup_();
975 }
976
977 value_ = new_value;
978 }
979
Calin Juravle7a570e82017-01-14 16:23:30 -0800980 void reset(int new_value, std::function<void ()> new_cleanup) {
981 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700982 close(value_);
983 }
984 if (do_cleanup_ && cleanup_ != nullptr) {
985 cleanup_();
986 }
987
988 value_ = new_value;
989 cleanup_ = new_cleanup;
990 }
991
Calin Juravle7a570e82017-01-14 16:23:30 -0800992 void DisableAutoClose() {
993 auto_close_ = false;
994 }
995
Jeff Sharkey90aff262016-12-12 14:28:24 -0700996 private:
Calin Juravle7a570e82017-01-14 16:23:30 -0800997 void release() {
998 value_ = -1;
999 do_cleanup_ = false;
1000 cleanup_ = nullptr;
1001 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001003 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001005 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001006};
1007
Calin Juravle7a570e82017-01-14 16:23:30 -08001008// (re)Creates the app image if needed.
1009Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
1010 bool is_public, int uid) {
1011 // Use app images only if it is enabled (by a set image format) and we are compiling
1012 // profile-guided (so the app image doesn't conservatively contain all classes).
1013 if (!profile_guided) {
1014 return Dex2oatFileWrapper();
1015 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001016
Calin Juravle7a570e82017-01-14 16:23:30 -08001017 const std::string image_path = create_image_filename(out_oat_path);
1018 if (image_path.empty()) {
1019 // Happens when the out_oat_path has an unknown extension.
1020 return Dex2oatFileWrapper();
1021 }
1022 char app_image_format[kPropertyValueMax];
1023 bool have_app_image_format =
1024 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1025 if (!have_app_image_format) {
1026 return Dex2oatFileWrapper();
1027 }
1028 // Recreate is true since we do not want to modify a mapped image. If the app is
1029 // already running and we modify the image file, it can cause crashes (b/27493510).
1030 Dex2oatFileWrapper wrapper_fd(
1031 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1032 [image_path]() { unlink(image_path.c_str()); });
1033 if (wrapper_fd.get() < 0) {
1034 // Could not create application image file. Go on since we can compile without it.
1035 LOG(ERROR) << "installd could not create '" << image_path
1036 << "' for image file during dexopt";
1037 // If we have a valid image file path but no image fd, explicitly erase the image file.
1038 if (unlink(image_path.c_str()) < 0) {
1039 if (errno != ENOENT) {
1040 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1041 }
1042 }
1043 } else if (!set_permissions_and_ownership(
1044 wrapper_fd.get(), is_public, uid, image_path.c_str())) {
1045 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1046 wrapper_fd.reset(-1);
1047 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001048
Calin Juravle7a570e82017-01-14 16:23:30 -08001049 return wrapper_fd;
1050}
1051
1052// Creates the dexopt swap file if necessary and return its fd.
1053// Returns -1 if there's no need for a swap or in case of errors.
1054base::unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
1055 if (!ShouldUseSwapFileForDexopt()) {
1056 return base::unique_fd();
1057 }
1058 // Make sure there really is enough space.
1059 char swap_file_name[PKG_PATH_MAX];
1060 strcpy(swap_file_name, out_oat_path);
1061 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
1062 return base::unique_fd();
1063 }
1064 base::unique_fd swap_fd(open_output_file(
1065 swap_file_name, /*recreate*/true, /*permissions*/0600));
1066 if (swap_fd.get() < 0) {
1067 // Could not create swap file. Optimistically go on and hope that we can compile
1068 // without it.
1069 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1070 } else {
1071 // Immediately unlink. We don't really want to hit flash.
1072 if (unlink(swap_file_name) < 0) {
1073 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1074 }
1075 }
1076 return swap_fd;
1077}
1078
1079// Opens the reference profiles if needed.
1080// Note that the reference profile might not exist so it's OK if the fd will be -1.
1081Dex2oatFileWrapper maybe_open_reference_profile(const char* pkgname, bool profile_guided,
1082 bool is_public, int uid) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001083 // Public apps should not be compiled with profile information ever. Same goes for the special
1084 // package '*' used for the system server.
Calin Juravle7a570e82017-01-14 16:23:30 -08001085 if (profile_guided && !is_public && (pkgname[0] != '*')) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001086 // Open reference profile in read only mode as dex2oat does not get write permissions.
1087 const std::string pkgname_str(pkgname);
Calin Juravle7a570e82017-01-14 16:23:30 -08001088 return Dex2oatFileWrapper(
1089 open_reference_profile(uid, pkgname, /*read_write*/ false),
1090 [pkgname_str]() {
1091 clear_reference_profile(pkgname_str.c_str());
1092 });
1093 } else {
1094 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001095 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001096}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001097
Calin Juravle7a570e82017-01-14 16:23:30 -08001098// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1099// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1100bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
1101 const char* instruction_set, bool is_public, int uid,
1102 Dex2oatFileWrapper* in_vdex_wrapper_fd,
1103 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1104 CHECK(in_vdex_wrapper_fd != nullptr);
1105 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001106 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1107 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001108 char in_odex_path[PKG_PATH_MAX];
1109 int dexopt_action = abs(dexopt_needed);
1110 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001111 std::string in_vdex_path_str;
Richard Uhler76cc0272016-12-08 10:46:35 +00001112 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001113 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1114 const char* path = nullptr;
1115 if (is_odex_location) {
1116 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1117 path = in_odex_path;
1118 } else {
1119 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001120 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 }
1122 } else {
1123 path = out_oat_path;
1124 }
1125 in_vdex_path_str = create_vdex_filename(path);
1126 if (in_vdex_path_str.empty()) {
1127 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001128 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001129 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001130 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
1131 // When we dex2oat because iof boot image change, we are going to update
1132 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001133 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001134 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001135 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001136 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001137 }
1138
1139 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001141 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001142 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001143 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001144
1145 // If we are compiling because the boot image is out of date, we do not
1146 // need to recreate a vdex, and can use the same existing one.
1147 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001148 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001149 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001150 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1151 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1152 // wrapper).
1153 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001154 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001155 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001156 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1157 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 if (out_vdex_wrapper_fd->get() < 0) {
1159 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1160 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001161 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001162 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001163 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
1164 out_vdex_path_str.c_str())) {
1165 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1166 return false;
1167 }
1168
1169 // If we got here we successfully opened the vdex files.
1170 return true;
1171}
1172
1173// Opens the output oat file for the given apk.
1174// If successful it stores the output path into out_oat_path and returns true.
1175Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
1176 bool is_public, int uid, const char* instruction_set, char* out_oat_path) {
1177 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_oat_path)) {
1178 return Dex2oatFileWrapper();
1179 }
1180 const std::string out_oat_path_str(out_oat_path);
1181 Dex2oatFileWrapper wrapper_fd(
1182 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1183 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1184 if (wrapper_fd.get() < 0) {
1185 ALOGE("installd cannot open '%s' for output during dexopt\n", out_oat_path);
1186 } else if (!set_permissions_and_ownership(wrapper_fd.get(), is_public, uid, out_oat_path)) {
1187 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1188 wrapper_fd.reset(-1);
1189 }
1190 return wrapper_fd;
1191}
1192
1193// Updates the access times of out_oat_path based on those from apk_path.
1194void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1195 struct stat input_stat;
1196 memset(&input_stat, 0, sizeof(input_stat));
1197 if (stat(apk_path, &input_stat) != 0) {
1198 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1199 return;
1200 }
1201
1202 struct utimbuf ut;
1203 ut.actime = input_stat.st_atime;
1204 ut.modtime = input_stat.st_mtime;
1205 if (utime(out_oat_path, &ut) != 0) {
1206 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1207 }
1208}
1209
1210int dexopt(const char* apk_path, uid_t uid, const char* pkgname, const char* instruction_set,
1211 int dexopt_needed, const char* oat_dir, int dexopt_flags,const char* compiler_filter,
1212 const char* volume_uuid ATTRIBUTE_UNUSED, const char* shared_libraries) {
1213 CHECK(pkgname != nullptr);
1214 CHECK(pkgname[0] != 0);
1215 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1216 LOG_FATAL("dexopt flags contains unknown fields\n");
1217 }
1218
1219 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1220 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1221 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1222 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1223 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1224
1225 // Open the input file.
1226 base::unique_fd input_fd(open(apk_path, O_RDONLY, 0));
1227 if (input_fd.get() < 0) {
1228 ALOGE("installd cannot open '%s' for input during dexopt\n", apk_path);
1229 return -1;
1230 }
1231
1232 // Create the output OAT file.
1233 char out_oat_path[PKG_PATH_MAX];
1234 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(apk_path, oat_dir, is_public, uid,
1235 instruction_set, out_oat_path);
1236 if (out_oat_fd.get() < 0) {
1237 return -1;
1238 }
1239
1240 // Open vdex files.
1241 Dex2oatFileWrapper in_vdex_fd;
1242 Dex2oatFileWrapper out_vdex_fd;
1243 if (!open_vdex_files(apk_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
1244 &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001245 return -1;
1246 }
1247
1248 // Create a swap file if necessary.
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 base::unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001250
Calin Juravle7a570e82017-01-14 16:23:30 -08001251 // Create the app image file if needed.
1252 Dex2oatFileWrapper image_fd =
1253 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001254
Calin Juravle7a570e82017-01-14 16:23:30 -08001255 // Open the reference profile if needed.
1256 Dex2oatFileWrapper reference_profile_fd =
1257 maybe_open_reference_profile(pkgname, profile_guided, is_public, uid);
1258
1259 ALOGV("DexInv: --- BEGIN '%s' ---\n", apk_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260
1261 pid_t pid = fork();
1262 if (pid == 0) {
1263 /* child -- drop privileges before continuing */
1264 drop_capabilities(uid);
1265
Richard Uhler76cc0272016-12-08 10:46:35 +00001266 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001267 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1268 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1269 _exit(67);
1270 }
1271
Richard Uhler76cc0272016-12-08 10:46:35 +00001272 // Pass dex2oat the relative path to the input file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001273 const char *input_file_name = get_location_from_path(apk_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001274 run_dex2oat(input_fd.get(),
1275 out_oat_fd.get(),
1276 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001277 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001278 image_fd.get(),
1279 input_file_name,
1280 out_oat_path,
1281 swap_fd.get(),
1282 instruction_set,
1283 compiler_filter,
1284 vm_safe_mode,
1285 debuggable,
1286 boot_complete,
1287 reference_profile_fd.get(),
1288 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001289 _exit(68); /* only get here on exec failure */
1290 } else {
1291 int res = wait_child(pid);
1292 if (res == 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 ALOGV("DexInv: --- END '%s' (success) ---\n", apk_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001294 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001295 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", apk_path, res);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001296 return -1;
1297 }
1298 }
1299
Calin Juravle7a570e82017-01-14 16:23:30 -08001300 update_out_oat_access_times(apk_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001301
1302 // We've been successful, don't delete output.
1303 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001304 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001305 image_fd.SetCleanup(false);
1306 reference_profile_fd.SetCleanup(false);
1307
1308 return 0;
1309}
1310
1311// Helper for move_ab, so that we can have common failure-case cleanup.
1312static bool unlink_and_rename(const char* from, const char* to) {
1313 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1314 // return a failure.
1315 struct stat s;
1316 if (stat(to, &s) == 0) {
1317 if (!S_ISREG(s.st_mode)) {
1318 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1319 return false;
1320 }
1321 if (unlink(to) != 0) {
1322 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1323 return false;
1324 }
1325 } else {
1326 // This may be a permission problem. We could investigate the error code, but we'll just
1327 // let the rename failure do the work for us.
1328 }
1329
1330 // Try to rename "to" to "from."
1331 if (rename(from, to) != 0) {
1332 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1333 return false;
1334 }
1335 return true;
1336}
1337
1338// Move/rename a B artifact (from) to an A artifact (to).
1339static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1340 // Check whether B exists.
1341 {
1342 struct stat s;
1343 if (stat(b_path.c_str(), &s) != 0) {
1344 // Silently ignore for now. The service calling this isn't smart enough to understand
1345 // lack of artifacts at the moment.
1346 return false;
1347 }
1348 if (!S_ISREG(s.st_mode)) {
1349 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1350 // Try to unlink, but swallow errors.
1351 unlink(b_path.c_str());
1352 return false;
1353 }
1354 }
1355
1356 // Rename B to A.
1357 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1358 // Delete the b_path so we don't try again (or fail earlier).
1359 if (unlink(b_path.c_str()) != 0) {
1360 PLOG(ERROR) << "Could not unlink " << b_path;
1361 }
1362
1363 return false;
1364 }
1365
1366 return true;
1367}
1368
1369bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1370 // Get the current slot suffix. No suffix, no A/B.
1371 std::string slot_suffix;
1372 {
1373 char buf[kPropertyValueMax];
1374 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1375 return false;
1376 }
1377 slot_suffix = buf;
1378
1379 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1380 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1381 return false;
1382 }
1383 }
1384
1385 // Validate other inputs.
1386 if (validate_apk_path(apk_path) != 0) {
1387 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1388 return false;
1389 }
1390 if (validate_apk_path(oat_dir) != 0) {
1391 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1392 return false;
1393 }
1394
1395 char a_path[PKG_PATH_MAX];
1396 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1397 return false;
1398 }
1399 const std::string a_vdex_path = create_vdex_filename(a_path);
1400 const std::string a_image_path = create_image_filename(a_path);
1401
1402 // B path = A path + slot suffix.
1403 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1404 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1405 const std::string b_image_path = StringPrintf("%s.%s",
1406 a_image_path.c_str(),
1407 slot_suffix.c_str());
1408
1409 bool success = true;
1410 if (move_ab_path(b_path, a_path)) {
1411 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1412 // Note: we can live without an app image. As such, ignore failure to move the image file.
1413 // If we decide to require the app image, or the app image being moved correctly,
1414 // then change accordingly.
1415 constexpr bool kIgnoreAppImageFailure = true;
1416
1417 if (!a_image_path.empty()) {
1418 if (!move_ab_path(b_image_path, a_image_path)) {
1419 unlink(a_image_path.c_str());
1420 if (!kIgnoreAppImageFailure) {
1421 success = false;
1422 }
1423 }
1424 }
1425 } else {
1426 // Cleanup: delete B image, ignore errors.
1427 unlink(b_image_path.c_str());
1428 success = false;
1429 }
1430 } else {
1431 // Cleanup: delete B image, ignore errors.
1432 unlink(b_vdex_path.c_str());
1433 unlink(b_image_path.c_str());
1434 success = false;
1435 }
1436 return success;
1437}
1438
1439bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1440 // Delete the oat/odex file.
1441 char out_path[PKG_PATH_MAX];
1442 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, out_path)) {
1443 return false;
1444 }
1445
1446 // In case of a permission failure report the issue. Otherwise just print a warning.
1447 auto unlink_and_check = [](const char* path) -> bool {
1448 int result = unlink(path);
1449 if (result != 0) {
1450 if (errno == EACCES || errno == EPERM) {
1451 PLOG(ERROR) << "Could not unlink " << path;
1452 return false;
1453 }
1454 PLOG(WARNING) << "Could not unlink " << path;
1455 }
1456 return true;
1457 };
1458
1459 // Delete the oat/odex file.
1460 bool return_value_oat = unlink_and_check(out_path);
1461
1462 // Derive and delete the app image.
1463 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1464
1465 // Report success.
1466 return return_value_oat && return_value_art;
1467}
1468
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001469int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1470 return dexopt(params[0], // apk_path
1471 atoi(params[1]), // uid
1472 params[2], // pkgname
1473 params[3], // instruction_set
1474 atoi(params[4]), // dexopt_needed
1475 params[5], // oat_dir
1476 atoi(params[6]), // dexopt_flags
1477 params[7], // compiler_filter
1478 parse_null(params[8]), // volume_uuid
1479 parse_null(params[9])); // shared_libraries
1480 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1481}
1482
1483} // namespace installd
1484} // namespace android