blob: 618884b33045b9593877f4c77b8991305c650057 [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>
Calin Juravle80a21252017-01-17 14:43:25 -080034#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070035#include <cutils/properties.h>
36#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070037#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkey90aff262016-12-12 14:28:24 -070038#include <private/android_filesystem_config.h>
39#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070040
41#include "dexopt.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070042#include "installd_deps.h"
43#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070044#include "utils.h"
45
46using android::base::StringPrintf;
Jeff Sharkey90aff262016-12-12 14:28:24 -070047using android::base::EndsWith;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070048
49namespace android {
50namespace installd {
51
52static const char* parse_null(const char* arg) {
53 if (strcmp(arg, "!") == 0) {
54 return nullptr;
55 } else {
56 return arg;
57 }
58}
59
Jeff Sharkey90aff262016-12-12 14:28:24 -070060static bool clear_profile(const std::string& profile) {
61 base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
62 if (ufd.get() < 0) {
63 if (errno != ENOENT) {
64 PLOG(WARNING) << "Could not open profile " << profile;
65 return false;
66 } else {
67 // Nothing to clear. That's ok.
68 return true;
69 }
70 }
71
72 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
73 if (errno != EWOULDBLOCK) {
74 PLOG(WARNING) << "Error locking profile " << profile;
75 }
76 // This implies that the app owning this profile is running
77 // (and has acquired the lock).
78 //
79 // If we can't acquire the lock bail out since clearing is useless anyway
80 // (the app will write again to the profile).
81 //
82 // Note:
83 // This does not impact the this is not an issue for the profiling correctness.
84 // In case this is needed because of an app upgrade, profiles will still be
85 // eventually cleared by the app itself due to checksum mismatch.
86 // If this is needed because profman advised, then keeping the data around
87 // until the next run is again not an issue.
88 //
89 // If the app attempts to acquire a lock while we've held one here,
90 // it will simply skip the current write cycle.
91 return false;
92 }
93
94 bool truncated = ftruncate(ufd.get(), 0) == 0;
95 if (!truncated) {
96 PLOG(WARNING) << "Could not truncate " << profile;
97 }
98 if (flock(ufd.get(), LOCK_UN) != 0) {
99 PLOG(WARNING) << "Error unlocking profile " << profile;
100 }
101 return truncated;
102}
103
104bool clear_reference_profile(const char* pkgname) {
105 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
106 std::string reference_profile = create_primary_profile(reference_profile_dir);
107 return clear_profile(reference_profile);
108}
109
110bool clear_current_profile(const char* pkgname, userid_t user) {
111 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
112 std::string profile = create_primary_profile(profile_dir);
113 return clear_profile(profile);
114}
115
116bool clear_current_profiles(const char* pkgname) {
117 bool success = true;
118 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
119 for (auto user : users) {
120 success &= clear_current_profile(pkgname, user);
121 }
122 return success;
123}
124
125static int split_count(const char *str)
126{
127 char *ctx;
128 int count = 0;
129 char buf[kPropertyValueMax];
130
131 strncpy(buf, str, sizeof(buf));
132 char *pBuf = buf;
133
134 while(strtok_r(pBuf, " ", &ctx) != NULL) {
135 count++;
136 pBuf = NULL;
137 }
138
139 return count;
140}
141
142static int split(char *buf, const char **argv)
143{
144 char *ctx;
145 int count = 0;
146 char *tok;
147 char *pBuf = buf;
148
149 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
150 argv[count++] = tok;
151 pBuf = NULL;
152 }
153
154 return count;
155}
156
Jeff Sharkey90aff262016-12-12 14:28:24 -0700157static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
158 const char* input_file_name, const char* output_file_name, int swap_fd,
159 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
160 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
161 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
162
163 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
164 ALOGE("Instruction set %s longer than max length of %d",
165 instruction_set, MAX_INSTRUCTION_SET_LEN);
166 return;
167 }
168
169 char dex2oat_Xms_flag[kPropertyValueMax];
170 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
171
172 char dex2oat_Xmx_flag[kPropertyValueMax];
173 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
174
175 char dex2oat_threads_buf[kPropertyValueMax];
176 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
177 ? "dalvik.vm.dex2oat-threads"
178 : "dalvik.vm.boot-dex2oat-threads",
179 dex2oat_threads_buf,
180 NULL) > 0;
181 char dex2oat_threads_arg[kPropertyValueMax + 2];
182 if (have_dex2oat_threads_flag) {
183 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
184 }
185
186 char dex2oat_isa_features_key[kPropertyKeyMax];
187 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
188 char dex2oat_isa_features[kPropertyValueMax];
189 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
190 dex2oat_isa_features, NULL) > 0;
191
192 char dex2oat_isa_variant_key[kPropertyKeyMax];
193 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
194 char dex2oat_isa_variant[kPropertyValueMax];
195 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
196 dex2oat_isa_variant, NULL) > 0;
197
198 const char *dex2oat_norelocation = "-Xnorelocate";
199 bool have_dex2oat_relocation_skip_flag = false;
200
201 char dex2oat_flags[kPropertyValueMax];
202 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
203 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
204 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
205
206 // If we booting without the real /data, don't spend time compiling.
207 char vold_decrypt[kPropertyValueMax];
208 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
209 bool skip_compilation = (have_vold_decrypt &&
210 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
211 (strcmp(vold_decrypt, "1") == 0)));
212
213 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
214
215 char app_image_format[kPropertyValueMax];
216 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
217 bool have_app_image_format =
218 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
219 if (have_app_image_format) {
220 sprintf(image_format_arg, "--image-format=%s", app_image_format);
221 }
222
223 char dex2oat_large_app_threshold[kPropertyValueMax];
224 bool have_dex2oat_large_app_threshold =
225 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
226 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
227 if (have_dex2oat_large_app_threshold) {
228 sprintf(dex2oat_large_app_threshold_arg,
229 "--very-large-app-threshold=%s",
230 dex2oat_large_app_threshold);
231 }
232
233 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
234
235 static const char* RUNTIME_ARG = "--runtime-arg";
236
237 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
238
George Burgess IV36cebe772017-01-25 11:52:01 -0800239 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
240 // use arraysize instead.
241 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
242 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
243 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
244 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
245 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
246 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
247 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
248 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
249 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
250 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
251 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
252 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700253 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800254 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700255 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800256 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700257
258 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
259 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
260 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
261 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
262 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
263 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
264 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
265 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
266 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
267 if (swap_fd >= 0) {
268 have_dex2oat_swap_fd = true;
269 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
270 }
271 if (image_fd >= 0) {
272 have_dex2oat_image_fd = true;
273 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
274 }
275
276 if (have_dex2oat_Xms_flag) {
277 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
278 }
279 if (have_dex2oat_Xmx_flag) {
280 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
281 }
282
283 // Compute compiler filter.
284
285 bool have_dex2oat_compiler_filter_flag;
286 if (skip_compilation) {
287 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
288 have_dex2oat_compiler_filter_flag = true;
289 have_dex2oat_relocation_skip_flag = true;
290 } else if (vm_safe_mode) {
291 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
292 have_dex2oat_compiler_filter_flag = true;
293 } else if (compiler_filter != nullptr &&
294 strlen(compiler_filter) + strlen("--compiler-filter=") <
295 arraysize(dex2oat_compiler_filter_arg)) {
296 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
297 have_dex2oat_compiler_filter_flag = true;
298 } else {
299 char dex2oat_compiler_filter_flag[kPropertyValueMax];
300 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
301 dex2oat_compiler_filter_flag, NULL) > 0;
302 if (have_dex2oat_compiler_filter_flag) {
303 sprintf(dex2oat_compiler_filter_arg,
304 "--compiler-filter=%s",
305 dex2oat_compiler_filter_flag);
306 }
307 }
308
309 // Check whether all apps should be compiled debuggable.
310 if (!debuggable) {
311 char prop_buf[kPropertyValueMax];
312 debuggable =
313 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
314 (prop_buf[0] == '1');
315 }
316 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
317 if (profile_fd != -1) {
318 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
319 }
320
321
322 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
323
324 const char* argv[9 // program name, mandatory arguments and the final NULL
325 + (have_dex2oat_isa_variant ? 1 : 0)
326 + (have_dex2oat_isa_features ? 1 : 0)
327 + (have_dex2oat_Xms_flag ? 2 : 0)
328 + (have_dex2oat_Xmx_flag ? 2 : 0)
329 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
330 + (have_dex2oat_threads_flag ? 1 : 0)
331 + (have_dex2oat_swap_fd ? 1 : 0)
332 + (have_dex2oat_image_fd ? 1 : 0)
333 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
334 + (generate_debug_info ? 1 : 0)
335 + (debuggable ? 1 : 0)
336 + (have_app_image_format ? 1 : 0)
337 + dex2oat_flags_count
338 + (profile_fd == -1 ? 0 : 1)
339 + (shared_libraries != nullptr ? 4 : 0)
340 + (have_dex2oat_large_app_threshold ? 1 : 0)];
341 int i = 0;
342 argv[i++] = DEX2OAT_BIN;
343 argv[i++] = zip_fd_arg;
344 argv[i++] = zip_location_arg;
345 argv[i++] = input_vdex_fd_arg;
346 argv[i++] = output_vdex_fd_arg;
347 argv[i++] = oat_fd_arg;
348 argv[i++] = oat_location_arg;
349 argv[i++] = instruction_set_arg;
350 if (have_dex2oat_isa_variant) {
351 argv[i++] = instruction_set_variant_arg;
352 }
353 if (have_dex2oat_isa_features) {
354 argv[i++] = instruction_set_features_arg;
355 }
356 if (have_dex2oat_Xms_flag) {
357 argv[i++] = RUNTIME_ARG;
358 argv[i++] = dex2oat_Xms_arg;
359 }
360 if (have_dex2oat_Xmx_flag) {
361 argv[i++] = RUNTIME_ARG;
362 argv[i++] = dex2oat_Xmx_arg;
363 }
364 if (have_dex2oat_compiler_filter_flag) {
365 argv[i++] = dex2oat_compiler_filter_arg;
366 }
367 if (have_dex2oat_threads_flag) {
368 argv[i++] = dex2oat_threads_arg;
369 }
370 if (have_dex2oat_swap_fd) {
371 argv[i++] = dex2oat_swap_fd;
372 }
373 if (have_dex2oat_image_fd) {
374 argv[i++] = dex2oat_image_fd;
375 }
376 if (generate_debug_info) {
377 argv[i++] = "--generate-debug-info";
378 }
379 if (debuggable) {
380 argv[i++] = "--debuggable";
381 }
382 if (have_app_image_format) {
383 argv[i++] = image_format_arg;
384 }
385 if (have_dex2oat_large_app_threshold) {
386 argv[i++] = dex2oat_large_app_threshold_arg;
387 }
388 if (dex2oat_flags_count) {
389 i += split(dex2oat_flags, argv + i);
390 }
391 if (have_dex2oat_relocation_skip_flag) {
392 argv[i++] = RUNTIME_ARG;
393 argv[i++] = dex2oat_norelocation;
394 }
395 if (profile_fd != -1) {
396 argv[i++] = profile_arg;
397 }
398 if (shared_libraries != nullptr) {
399 argv[i++] = RUNTIME_ARG;
400 argv[i++] = "-classpath";
401 argv[i++] = RUNTIME_ARG;
402 argv[i++] = shared_libraries;
403 }
404 // Do not add after dex2oat_flags, they should override others for debugging.
405 argv[i] = NULL;
406
407 execv(DEX2OAT_BIN, (char * const *)argv);
408 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
409}
410
411/*
412 * Whether dexopt should use a swap file when compiling an APK.
413 *
414 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
415 * itself, anyways).
416 *
417 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
418 *
419 * Otherwise, return true if this is a low-mem device.
420 *
421 * Otherwise, return default value.
422 */
423static bool kAlwaysProvideSwapFile = false;
424static bool kDefaultProvideSwapFile = true;
425
426static bool ShouldUseSwapFileForDexopt() {
427 if (kAlwaysProvideSwapFile) {
428 return true;
429 }
430
431 // Check the "override" property. If it exists, return value == "true".
432 char dex2oat_prop_buf[kPropertyValueMax];
433 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
434 if (strcmp(dex2oat_prop_buf, "true") == 0) {
435 return true;
436 } else {
437 return false;
438 }
439 }
440
441 // Shortcut for default value. This is an implementation optimization for the process sketched
442 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
443 // as low-mem is never returning false. The compiler will optimize this away if it can.
444 if (kDefaultProvideSwapFile) {
445 return true;
446 }
447
448 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
449 if (is_low_mem) {
450 return true;
451 }
452
453 // Default value must be false here.
454 return kDefaultProvideSwapFile;
455}
456
Richard Uhler76cc0272016-12-08 10:46:35 +0000457static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700458 if (set_to_bg) {
459 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
460 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
461 exit(70);
462 }
463 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
464 ALOGE("setpriority failed: %s\n", strerror(errno));
465 exit(71);
466 }
467 }
468}
469
470static void close_all_fds(const std::vector<fd_t>& fds, const char* description) {
471 for (size_t i = 0; i < fds.size(); i++) {
472 if (close(fds[i]) != 0) {
473 PLOG(WARNING) << "Failed to close fd for " << description << " at index " << i;
474 }
475 }
476}
477
478static fd_t open_profile_dir(const std::string& profile_dir) {
479 fd_t profile_dir_fd = TEMP_FAILURE_RETRY(open(profile_dir.c_str(),
480 O_PATH | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW));
481 if (profile_dir_fd < 0) {
482 // In a multi-user environment, these directories can be created at
483 // different points and it's possible we'll attempt to open a profile
484 // dir before it exists.
485 if (errno != ENOENT) {
486 PLOG(ERROR) << "Failed to open profile_dir: " << profile_dir;
487 }
488 }
489 return profile_dir_fd;
490}
491
492static fd_t open_primary_profile_file_from_dir(const std::string& profile_dir, mode_t open_mode) {
493 fd_t profile_dir_fd = open_profile_dir(profile_dir);
494 if (profile_dir_fd < 0) {
495 return -1;
496 }
497
498 fd_t profile_fd = -1;
499 std::string profile_file = create_primary_profile(profile_dir);
500
George Burgess IV3ef54f22017-01-25 11:36:12 -0800501 profile_fd = TEMP_FAILURE_RETRY(open(profile_file.c_str(), open_mode | O_NOFOLLOW, 0600));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700502 if (profile_fd == -1) {
503 // It's not an error if the profile file does not exist.
504 if (errno != ENOENT) {
505 PLOG(ERROR) << "Failed to lstat profile_dir: " << profile_dir;
506 }
507 }
508 // TODO(calin): use AutoCloseFD instead of closing the fd manually.
509 if (close(profile_dir_fd) != 0) {
510 PLOG(WARNING) << "Could not close profile dir " << profile_dir;
511 }
512 return profile_fd;
513}
514
515static fd_t open_primary_profile_file(userid_t user, const char* pkgname) {
516 std::string profile_dir = create_data_user_profile_package_path(user, pkgname);
517 return open_primary_profile_file_from_dir(profile_dir, O_RDONLY);
518}
519
520static fd_t open_reference_profile(uid_t uid, const char* pkgname, bool read_write) {
521 std::string reference_profile_dir = create_data_ref_profile_package_path(pkgname);
522 int flags = read_write ? O_RDWR | O_CREAT : O_RDONLY;
523 fd_t fd = open_primary_profile_file_from_dir(reference_profile_dir, flags);
524 if (fd < 0) {
525 return -1;
526 }
527 if (read_write) {
528 // Fix the owner.
529 if (fchown(fd, uid, uid) < 0) {
530 close(fd);
531 return -1;
532 }
533 }
534 return fd;
535}
536
537static void open_profile_files(uid_t uid, const char* pkgname,
538 /*out*/ std::vector<fd_t>* profiles_fd, /*out*/ fd_t* reference_profile_fd) {
539 // Open the reference profile in read-write mode as profman might need to save the merge.
540 *reference_profile_fd = open_reference_profile(uid, pkgname, /*read_write*/ true);
541 if (*reference_profile_fd < 0) {
542 // We can't access the reference profile file.
543 return;
544 }
545
546 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
547 for (auto user : users) {
548 fd_t profile_fd = open_primary_profile_file(user, pkgname);
549 // Add to the lists only if both fds are valid.
550 if (profile_fd >= 0) {
551 profiles_fd->push_back(profile_fd);
552 }
553 }
554}
555
556static void drop_capabilities(uid_t uid) {
557 if (setgid(uid) != 0) {
558 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
559 exit(64);
560 }
561 if (setuid(uid) != 0) {
562 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
563 exit(65);
564 }
565 // drop capabilities
566 struct __user_cap_header_struct capheader;
567 struct __user_cap_data_struct capdata[2];
568 memset(&capheader, 0, sizeof(capheader));
569 memset(&capdata, 0, sizeof(capdata));
570 capheader.version = _LINUX_CAPABILITY_VERSION_3;
571 if (capset(&capheader, &capdata[0]) < 0) {
572 ALOGE("capset failed: %s\n", strerror(errno));
573 exit(66);
574 }
575}
576
577static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
578static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
579static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
580static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
581static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
582
583static void run_profman_merge(const std::vector<fd_t>& profiles_fd, fd_t reference_profile_fd) {
584 static const size_t MAX_INT_LEN = 32;
585 static const char* PROFMAN_BIN = "/system/bin/profman";
586
587 std::vector<std::string> profile_args(profiles_fd.size());
588 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
589 for (size_t k = 0; k < profiles_fd.size(); k++) {
590 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k]);
591 profile_args[k].assign(profile_buf);
592 }
593 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
594 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd);
595
596 // program name, reference profile fd, the final NULL and the profile fds
597 const char* argv[3 + profiles_fd.size()];
598 int i = 0;
599 argv[i++] = PROFMAN_BIN;
600 argv[i++] = reference_profile_arg;
601 for (size_t k = 0; k < profile_args.size(); k++) {
602 argv[i++] = profile_args[k].c_str();
603 }
604 // Do not add after dex2oat_flags, they should override others for debugging.
605 argv[i] = NULL;
606
607 execv(PROFMAN_BIN, (char * const *)argv);
608 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
609 exit(68); /* only get here on exec failure */
610}
611
612// Decides if profile guided compilation is needed or not based on existing profiles.
613// Returns true if there is enough information in the current profiles that worth
614// a re-compilation of the package.
615// If the return value is true all the current profiles would have been merged into
616// the reference profiles accessible with open_reference_profile().
617bool analyse_profiles(uid_t uid, const char* pkgname) {
618 std::vector<fd_t> profiles_fd;
619 fd_t reference_profile_fd = -1;
620 open_profile_files(uid, pkgname, &profiles_fd, &reference_profile_fd);
621 if (profiles_fd.empty() || (reference_profile_fd == -1)) {
622 // Skip profile guided compilation because no profiles were found.
623 // Or if the reference profile info couldn't be opened.
624 close_all_fds(profiles_fd, "profiles_fd");
625 if ((reference_profile_fd != - 1) && (close(reference_profile_fd) != 0)) {
626 PLOG(WARNING) << "Failed to close fd for reference profile";
627 }
628 return false;
629 }
630
631 ALOGV("PROFMAN (MERGE): --- BEGIN '%s' ---\n", pkgname);
632
633 pid_t pid = fork();
634 if (pid == 0) {
635 /* child -- drop privileges before continuing */
636 drop_capabilities(uid);
637 run_profman_merge(profiles_fd, reference_profile_fd);
638 exit(68); /* only get here on exec failure */
639 }
640 /* parent */
641 int return_code = wait_child(pid);
642 bool need_to_compile = false;
643 bool should_clear_current_profiles = false;
644 bool should_clear_reference_profile = false;
645 if (!WIFEXITED(return_code)) {
646 LOG(WARNING) << "profman failed for package " << pkgname << ": " << return_code;
647 } else {
648 return_code = WEXITSTATUS(return_code);
649 switch (return_code) {
650 case PROFMAN_BIN_RETURN_CODE_COMPILE:
651 need_to_compile = true;
652 should_clear_current_profiles = true;
653 should_clear_reference_profile = false;
654 break;
655 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
656 need_to_compile = false;
657 should_clear_current_profiles = false;
658 should_clear_reference_profile = false;
659 break;
660 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
661 LOG(WARNING) << "Bad profiles for package " << pkgname;
662 need_to_compile = false;
663 should_clear_current_profiles = true;
664 should_clear_reference_profile = true;
665 break;
666 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
667 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
668 // Temporary IO problem (e.g. locking). Ignore but log a warning.
669 LOG(WARNING) << "IO error while reading profiles for package " << pkgname;
670 need_to_compile = false;
671 should_clear_current_profiles = false;
672 should_clear_reference_profile = false;
673 break;
674 default:
675 // Unknown return code or error. Unlink profiles.
676 LOG(WARNING) << "Unknown error code while processing profiles for package " << pkgname
677 << ": " << return_code;
678 need_to_compile = false;
679 should_clear_current_profiles = true;
680 should_clear_reference_profile = true;
681 break;
682 }
683 }
684 close_all_fds(profiles_fd, "profiles_fd");
685 if (close(reference_profile_fd) != 0) {
686 PLOG(WARNING) << "Failed to close fd for reference profile";
687 }
688 if (should_clear_current_profiles) {
689 clear_current_profiles(pkgname);
690 }
691 if (should_clear_reference_profile) {
692 clear_reference_profile(pkgname);
693 }
694 return need_to_compile;
695}
696
697static void run_profman_dump(const std::vector<fd_t>& profile_fds,
698 fd_t reference_profile_fd,
699 const std::vector<std::string>& dex_locations,
700 const std::vector<fd_t>& apk_fds,
701 fd_t output_fd) {
702 std::vector<std::string> profman_args;
703 static const char* PROFMAN_BIN = "/system/bin/profman";
704 profman_args.push_back(PROFMAN_BIN);
705 profman_args.push_back("--dump-only");
706 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd));
707 if (reference_profile_fd != -1) {
708 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
709 reference_profile_fd));
710 }
711 for (fd_t profile_fd : profile_fds) {
712 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fd));
713 }
714 for (const std::string& dex_location : dex_locations) {
715 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
716 }
717 for (fd_t apk_fd : apk_fds) {
718 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fd));
719 }
720 const char **argv = new const char*[profman_args.size() + 1];
721 size_t i = 0;
722 for (const std::string& profman_arg : profman_args) {
723 argv[i++] = profman_arg.c_str();
724 }
725 argv[i] = NULL;
726
727 execv(PROFMAN_BIN, (char * const *)argv);
728 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
729 exit(68); /* only get here on exec failure */
730}
731
732static const char* get_location_from_path(const char* path) {
733 static constexpr char kLocationSeparator = '/';
734 const char *location = strrchr(path, kLocationSeparator);
735 if (location == NULL) {
736 return path;
737 } else {
738 // Skip the separator character.
739 return location + 1;
740 }
741}
742
743bool dump_profiles(int32_t uid, const char* pkgname, const char* code_paths) {
744 std::vector<fd_t> profile_fds;
745 fd_t reference_profile_fd = -1;
746 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname);
747
748 ALOGV("PROFMAN (DUMP): --- BEGIN '%s' ---\n", pkgname);
749
750 open_profile_files(uid, pkgname, &profile_fds, &reference_profile_fd);
751
752 const bool has_reference_profile = (reference_profile_fd != -1);
753 const bool has_profiles = !profile_fds.empty();
754
755 if (!has_reference_profile && !has_profiles) {
756 ALOGE("profman dump: no profiles to dump for '%s'", pkgname);
757 return false;
758 }
759
George Burgess IV3ef54f22017-01-25 11:36:12 -0800760 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 -0700761 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
762 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
763 return false;
764 }
765 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
766 std::vector<std::string> dex_locations;
767 std::vector<fd_t> apk_fds;
768 for (const std::string& code_full_path : code_full_paths) {
769 const char* full_path = code_full_path.c_str();
770 fd_t apk_fd = open(full_path, O_RDONLY | O_NOFOLLOW);
771 if (apk_fd == -1) {
772 ALOGE("installd cannot open '%s'\n", full_path);
773 return false;
774 }
775 dex_locations.push_back(get_location_from_path(full_path));
776 apk_fds.push_back(apk_fd);
777 }
778
779 pid_t pid = fork();
780 if (pid == 0) {
781 /* child -- drop privileges before continuing */
782 drop_capabilities(uid);
783 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
784 apk_fds, output_fd);
785 exit(68); /* only get here on exec failure */
786 }
787 /* parent */
788 close_all_fds(apk_fds, "apk_fds");
789 close_all_fds(profile_fds, "profile_fds");
790 if (close(reference_profile_fd) != 0) {
791 PLOG(WARNING) << "Failed to close fd for reference profile";
792 }
793 int return_code = wait_child(pid);
794 if (!WIFEXITED(return_code)) {
795 LOG(WARNING) << "profman failed for package " << pkgname << ": "
796 << return_code;
797 return false;
798 }
799 return true;
800}
801
802static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
803 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
804 if (EndsWith(oat_path, ".dex")) {
805 std::string new_path = oat_path;
806 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
807 CHECK(EndsWith(new_path, new_ext.c_str()));
808 return new_path;
809 }
810
811 // An odex entry. Not that this may not be an extension, e.g., in the OTA
812 // case (where the base name will have an extension for the B artifact).
813 size_t odex_pos = oat_path.rfind(".odex");
814 if (odex_pos != std::string::npos) {
815 std::string new_path = oat_path;
816 new_path.replace(odex_pos, strlen(".odex"), new_ext);
817 CHECK_NE(new_path.find(new_ext), std::string::npos);
818 return new_path;
819 }
820
821 // Don't know how to handle this.
822 return "";
823}
824
825// Translate the given oat path to an art (app image) path. An empty string
826// denotes an error.
827static std::string create_image_filename(const std::string& oat_path) {
828 return replace_file_extension(oat_path, ".art");
829}
830
831// Translate the given oat path to a vdex path. An empty string denotes an error.
832static std::string create_vdex_filename(const std::string& oat_path) {
833 return replace_file_extension(oat_path, ".vdex");
834}
835
836static bool add_extension_to_file_name(char* file_name, const char* extension) {
837 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
838 return false;
839 }
840 strcat(file_name, extension);
841 return true;
842}
843
844static int open_output_file(const char* file_name, bool recreate, int permissions) {
845 int flags = O_RDWR | O_CREAT;
846 if (recreate) {
847 if (unlink(file_name) < 0) {
848 if (errno != ENOENT) {
849 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
850 }
851 }
852 flags |= O_EXCL;
853 }
854 return open(file_name, flags, permissions);
855}
856
857static bool set_permissions_and_ownership(int fd, bool is_public, int uid, const char* path) {
858 if (fchmod(fd,
859 S_IRUSR|S_IWUSR|S_IRGRP |
860 (is_public ? S_IROTH : 0)) < 0) {
861 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
862 return false;
863 } else if (fchown(fd, AID_SYSTEM, uid) < 0) {
864 ALOGE("installd cannot chown '%s' during dexopt\n", path);
865 return false;
866 }
867 return true;
868}
869
870static bool IsOutputDalvikCache(const char* oat_dir) {
871 // InstallerConnection.java (which invokes installd) transforms Java null arguments
872 // into '!'. Play it safe by handling it both.
873 // TODO: ensure we never get null.
874 // TODO: pass a flag instead of inferring if the output is dalvik cache.
875 return oat_dir == nullptr || oat_dir[0] == '!';
876}
877
878static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800879 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700880 // Early best-effort check whether we can fit the the path into our buffers.
881 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
882 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
883 // extension to the cache path (5 bytes).
884 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
885 ALOGE("apk_path too long '%s'\n", apk_path);
886 return false;
887 }
888
889 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800890 // Oat dirs for secondary dex files are already validated.
891 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700892 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
893 return false;
894 }
895 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
896 return false;
897 }
898 } else {
899 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
900 return false;
901 }
902 }
903 return true;
904}
905
906// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
907// on destruction. It will also run the given cleanup (unless told not to) after closing.
908//
909// Usage example:
910//
Calin Juravle7a570e82017-01-14 16:23:30 -0800911// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700912// [name]() {
913// unlink(name.c_str());
914// });
915// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
916// wrapper if captured as a reference.
917//
918// if (file.get() == -1) {
919// // Error opening...
920// }
921//
922// ...
923// if (error) {
924// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
925// // and delete the file (after the fd is closed).
926// return -1;
927// }
928//
929// (Success case)
930// file.SetCleanup(false);
931// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
932// // (leaving the file around; after the fd is closed).
933//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934class Dex2oatFileWrapper {
935 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800936 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937 }
938
Calin Juravle7a570e82017-01-14 16:23:30 -0800939 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
940 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
941
942 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
943 value_ = other.value_;
944 cleanup_ = other.cleanup_;
945 do_cleanup_ = other.do_cleanup_;
946 auto_close_ = other.auto_close_;
947 other.release();
948 }
949
950 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
951 value_ = other.value_;
952 cleanup_ = other.cleanup_;
953 do_cleanup_ = other.do_cleanup_;
954 auto_close_ = other.auto_close_;
955 other.release();
956 return *this;
957 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700958
959 ~Dex2oatFileWrapper() {
960 reset(-1);
961 }
962
963 int get() {
964 return value_;
965 }
966
967 void SetCleanup(bool cleanup) {
968 do_cleanup_ = cleanup;
969 }
970
971 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800972 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 close(value_);
974 }
975 if (do_cleanup_ && cleanup_ != nullptr) {
976 cleanup_();
977 }
978
979 value_ = new_value;
980 }
981
Calin Juravle7a570e82017-01-14 16:23:30 -0800982 void reset(int new_value, std::function<void ()> new_cleanup) {
983 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700984 close(value_);
985 }
986 if (do_cleanup_ && cleanup_ != nullptr) {
987 cleanup_();
988 }
989
990 value_ = new_value;
991 cleanup_ = new_cleanup;
992 }
993
Calin Juravle7a570e82017-01-14 16:23:30 -0800994 void DisableAutoClose() {
995 auto_close_ = false;
996 }
997
Jeff Sharkey90aff262016-12-12 14:28:24 -0700998 private:
Calin Juravle7a570e82017-01-14 16:23:30 -0800999 void release() {
1000 value_ = -1;
1001 do_cleanup_ = false;
1002 cleanup_ = nullptr;
1003 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001004 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001005 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001006 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001007 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001008};
1009
Calin Juravle7a570e82017-01-14 16:23:30 -08001010// (re)Creates the app image if needed.
1011Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
1012 bool is_public, int uid) {
1013 // Use app images only if it is enabled (by a set image format) and we are compiling
1014 // profile-guided (so the app image doesn't conservatively contain all classes).
1015 if (!profile_guided) {
1016 return Dex2oatFileWrapper();
1017 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018
Calin Juravle7a570e82017-01-14 16:23:30 -08001019 const std::string image_path = create_image_filename(out_oat_path);
1020 if (image_path.empty()) {
1021 // Happens when the out_oat_path has an unknown extension.
1022 return Dex2oatFileWrapper();
1023 }
1024 char app_image_format[kPropertyValueMax];
1025 bool have_app_image_format =
1026 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1027 if (!have_app_image_format) {
1028 return Dex2oatFileWrapper();
1029 }
1030 // Recreate is true since we do not want to modify a mapped image. If the app is
1031 // already running and we modify the image file, it can cause crashes (b/27493510).
1032 Dex2oatFileWrapper wrapper_fd(
1033 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1034 [image_path]() { unlink(image_path.c_str()); });
1035 if (wrapper_fd.get() < 0) {
1036 // Could not create application image file. Go on since we can compile without it.
1037 LOG(ERROR) << "installd could not create '" << image_path
1038 << "' for image file during dexopt";
1039 // If we have a valid image file path but no image fd, explicitly erase the image file.
1040 if (unlink(image_path.c_str()) < 0) {
1041 if (errno != ENOENT) {
1042 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1043 }
1044 }
1045 } else if (!set_permissions_and_ownership(
1046 wrapper_fd.get(), is_public, uid, image_path.c_str())) {
1047 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1048 wrapper_fd.reset(-1);
1049 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001050
Calin Juravle7a570e82017-01-14 16:23:30 -08001051 return wrapper_fd;
1052}
1053
1054// Creates the dexopt swap file if necessary and return its fd.
1055// Returns -1 if there's no need for a swap or in case of errors.
1056base::unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
1057 if (!ShouldUseSwapFileForDexopt()) {
1058 return base::unique_fd();
1059 }
1060 // Make sure there really is enough space.
1061 char swap_file_name[PKG_PATH_MAX];
1062 strcpy(swap_file_name, out_oat_path);
1063 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
1064 return base::unique_fd();
1065 }
1066 base::unique_fd swap_fd(open_output_file(
1067 swap_file_name, /*recreate*/true, /*permissions*/0600));
1068 if (swap_fd.get() < 0) {
1069 // Could not create swap file. Optimistically go on and hope that we can compile
1070 // without it.
1071 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1072 } else {
1073 // Immediately unlink. We don't really want to hit flash.
1074 if (unlink(swap_file_name) < 0) {
1075 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1076 }
1077 }
1078 return swap_fd;
1079}
1080
1081// Opens the reference profiles if needed.
1082// Note that the reference profile might not exist so it's OK if the fd will be -1.
1083Dex2oatFileWrapper maybe_open_reference_profile(const char* pkgname, bool profile_guided,
Calin Juravle80a21252017-01-17 14:43:25 -08001084 bool is_public, int uid, bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085 // Public apps should not be compiled with profile information ever. Same goes for the special
1086 // package '*' used for the system server.
Calin Juravle80a21252017-01-17 14:43:25 -08001087 // TODO(calin): add support for writing profiles for secondary dex files
1088 if (profile_guided && !is_secondary_dex && !is_public && (pkgname[0] != '*')) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 // Open reference profile in read only mode as dex2oat does not get write permissions.
1090 const std::string pkgname_str(pkgname);
Calin Juravle7a570e82017-01-14 16:23:30 -08001091 return Dex2oatFileWrapper(
1092 open_reference_profile(uid, pkgname, /*read_write*/ false),
1093 [pkgname_str]() {
1094 clear_reference_profile(pkgname_str.c_str());
1095 });
1096 } else {
1097 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001098 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001099}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001100
Calin Juravle7a570e82017-01-14 16:23:30 -08001101// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1102// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1103bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
1104 const char* instruction_set, bool is_public, int uid,
1105 Dex2oatFileWrapper* in_vdex_wrapper_fd,
1106 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1107 CHECK(in_vdex_wrapper_fd != nullptr);
1108 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001109 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1110 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001111 char in_odex_path[PKG_PATH_MAX];
1112 int dexopt_action = abs(dexopt_needed);
1113 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001114 std::string in_vdex_path_str;
Richard Uhler76cc0272016-12-08 10:46:35 +00001115 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001116 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1117 const char* path = nullptr;
1118 if (is_odex_location) {
1119 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1120 path = in_odex_path;
1121 } else {
1122 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001123 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001124 }
1125 } else {
1126 path = out_oat_path;
1127 }
1128 in_vdex_path_str = create_vdex_filename(path);
1129 if (in_vdex_path_str.empty()) {
1130 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001131 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001132 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001133 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
1134 // When we dex2oat because iof boot image change, we are going to update
1135 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001136 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001137 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001138 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001139 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001140 }
1141
1142 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001143 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001144 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001145 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001147
1148 // If we are compiling because the boot image is out of date, we do not
1149 // need to recreate a vdex, and can use the same existing one.
1150 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001151 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001152 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001153 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1154 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1155 // wrapper).
1156 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001157 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001158 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001159 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1160 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001161 if (out_vdex_wrapper_fd->get() < 0) {
1162 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1163 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001164 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001166 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
1167 out_vdex_path_str.c_str())) {
1168 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1169 return false;
1170 }
1171
1172 // If we got here we successfully opened the vdex files.
1173 return true;
1174}
1175
1176// Opens the output oat file for the given apk.
1177// If successful it stores the output path into out_oat_path and returns true.
1178Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001179 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1180 char* out_oat_path) {
1181 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001182 return Dex2oatFileWrapper();
1183 }
1184 const std::string out_oat_path_str(out_oat_path);
1185 Dex2oatFileWrapper wrapper_fd(
1186 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1187 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1188 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001189 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle7a570e82017-01-14 16:23:30 -08001190 } else if (!set_permissions_and_ownership(wrapper_fd.get(), is_public, uid, out_oat_path)) {
1191 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1192 wrapper_fd.reset(-1);
1193 }
1194 return wrapper_fd;
1195}
1196
1197// Updates the access times of out_oat_path based on those from apk_path.
1198void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1199 struct stat input_stat;
1200 memset(&input_stat, 0, sizeof(input_stat));
1201 if (stat(apk_path, &input_stat) != 0) {
1202 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1203 return;
1204 }
1205
1206 struct utimbuf ut;
1207 ut.actime = input_stat.st_atime;
1208 ut.modtime = input_stat.st_mtime;
1209 if (utime(out_oat_path, &ut) != 0) {
1210 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1211 }
1212}
1213
Calin Juravle80a21252017-01-17 14:43:25 -08001214// Runs (execv) dexoptanalyzer on the given arguments.
1215static void exec_dexoptanalyzer(const char* dex_file, const char* instruction_set,
1216 const char* compiler_filter) {
1217 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1218 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1219
1220 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1221 ALOGE("Instruction set %s longer than max length of %d",
1222 instruction_set, MAX_INSTRUCTION_SET_LEN);
1223 return;
1224 }
1225
1226 char dex_file_arg[strlen("--dex-file=") + PKG_PATH_MAX];
1227 char isa_arg[strlen("--isa=") + MAX_INSTRUCTION_SET_LEN];
1228 char compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
1229
1230 sprintf(dex_file_arg, "--dex-file=%s", dex_file);
1231 sprintf(isa_arg, "--isa=%s", instruction_set);
1232 sprintf(compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1233
1234 // program name, dex file, isa, filter, the final NULL
1235 const char* argv[5];
1236 int i = 0;
1237 argv[i++] = DEXOPTANALYZER_BIN;
1238 argv[i++] = dex_file_arg;
1239 argv[i++] = isa_arg;
1240 argv[i++] = compiler_filter_arg;
1241 argv[i] = NULL;
1242
1243 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1244 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1245}
1246
1247// Prepares the oat dir for the secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001248static bool prepare_secondary_dex_oat_dir(const char* dex_path, int uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001249 const char* instruction_set, std::string* oat_dir_out) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001250 std::string apk_path_str(dex_path);
Calin Juravle80a21252017-01-17 14:43:25 -08001251 unsigned long dirIndex = apk_path_str.rfind('/');
1252 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001253 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001254 return false;
1255 }
1256 std::string apk_dir = apk_path_str.substr(0, dirIndex);
1257
1258 // Assign the gid to the cache gid so that the oat file storage
1259 // is counted towards the app cache.
1260 int32_t cache_gid = multiuser_get_cache_gid(
1261 multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1262 // If UID doesn't have a specific cache GID, use UID value
1263 if (cache_gid == -1) {
1264 cache_gid = uid;
1265 }
1266
1267 // Create oat file output directory.
1268 if (prepare_app_cache_dir(apk_dir, "oat", 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001269 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001270 return false;
1271 }
1272
1273 char oat_dir[PKG_PATH_MAX];
1274 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1275 oat_dir_out->assign(oat_dir);
1276
1277 // Create oat/isa output directory.
1278 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001279 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001280 return false;
1281 }
1282
1283 return true;
1284}
1285
1286static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1287
1288// Verifies the result of dexoptanalyzer executed for the apk_path.
1289// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1290// Returns false for errors or unexpected result values.
Calin Juravlec9eab382017-01-25 01:17:17 -08001291static bool process_dexoptanalyzer_result(const char* dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001292 int* dexopt_needed_out) {
1293 // The result values are defined in dexoptanalyzer.
1294 switch (result) {
1295 case 0: // no_dexopt_needed
1296 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1297 case 1: // dex2oat_from_scratch
1298 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1299 case 5: // dex2oat_for_bootimage_odex
1300 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1301 case 6: // dex2oat_for_filter_odex
1302 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1303 case 7: // dex2oat_for_relocation_odex
1304 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1305 case 2: // dex2oat_for_bootimage_oat
1306 case 3: // dex2oat_for_filter_oat
1307 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001308 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1309 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001310 << " : dexoptanalyzer result=" << result;
1311 return false;
1312 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001313 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001314 << " exec_dexoptanalyzer result=" << result;
1315 return false;
1316 }
1317}
1318
Calin Juravlec9eab382017-01-25 01:17:17 -08001319// Processes the dex_path as a secondary dex files and return true if the path dex file should
Calin Juravle80a21252017-01-17 14:43:25 -08001320// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1321// successfully.
1322// When returning true, dexopt_needed_out is assigned a valid OatFileAsssitant::DexOptNeeded
1323// code and aot_dir_out is assigned the oat dir path where the oat file should be stored.
Calin Juravlec9eab382017-01-25 01:17:17 -08001324static bool process_secondary_dex_dexopt(const char* dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001325 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
1326 const char* compiler_filter, int* dexopt_needed_out, std::string* aot_dir_out) {
1327 int storage_flag;
1328
1329 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1330 storage_flag = FLAG_STORAGE_CE;
1331 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1332 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1333 return false;
1334 }
1335 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1336 storage_flag = FLAG_STORAGE_DE;
1337 } else {
1338 LOG(ERROR) << "Secondary dex storage flag must be set";
1339 return false;
1340 }
1341
Calin Juravlec9eab382017-01-25 01:17:17 -08001342 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1343 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001344 return false;
1345 }
1346
1347 // Check if the path exist. If not, there's nothing to do.
Calin Juravlec9eab382017-01-25 01:17:17 -08001348 if (access(dex_path, F_OK) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001349 if (errno == ENOENT) {
1350 // Secondary dex files might be deleted any time by the app.
1351 // Nothing to do if that's the case
Calin Juravlec9eab382017-01-25 01:17:17 -08001352 ALOGV("Secondary dex does not exist %s", dex_path);
Calin Juravle80a21252017-01-17 14:43:25 -08001353 return NO_DEXOPT_NEEDED;
1354 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001355 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001356 }
1357 }
1358
1359 // Prepare the oat directories.
Calin Juravlec9eab382017-01-25 01:17:17 -08001360 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, aot_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001361 return false;
1362 }
1363
1364 pid_t pid = fork();
1365 if (pid == 0) {
1366 // child -- drop privileges before continuing.
1367 drop_capabilities(uid);
1368 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravlec9eab382017-01-25 01:17:17 -08001369 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter);
Calin Juravle80a21252017-01-17 14:43:25 -08001370 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1371 }
1372
1373 /* parent */
1374
1375 int result = wait_child(pid);
1376 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001377 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001378 return false;
1379 }
1380 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001381 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001382 // Run dexopt only if needed or forced.
1383 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1384 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1385 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1386 // for oat files from dalvik-cache.
1387 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1388 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1389 }
1390
1391 return success;
1392}
1393
Calin Juravlec9eab382017-01-25 01:17:17 -08001394int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001395 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1396 const char* volume_uuid, const char* shared_libraries) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001397 CHECK(pkgname != nullptr);
1398 CHECK(pkgname[0] != 0);
1399 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1400 LOG_FATAL("dexopt flags contains unknown fields\n");
1401 }
1402
1403 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1404 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1405 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1406 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1407 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001408 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1409
1410 // Check if we're dealing with a secondary dex file and if we need to compile it.
1411 std::string oat_dir_str;
1412 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001413 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001414 instruction_set, compiler_filter, &dexopt_needed, &oat_dir_str)) {
1415 oat_dir = oat_dir_str.c_str();
1416 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1417 return 0; // Nothing to do, report success.
1418 }
1419 } else {
1420 return -1; // We had an error, logged in the process method.
1421 }
1422 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001423 // Currently these flags are only use for secondary dex files.
1424 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001425 CHECK((dexopt_flags & DEXOPT_FORCE) == 0);
1426 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1427 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1428 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001429
1430 // Open the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001431 base::unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001432 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001433 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001434 return -1;
1435 }
1436
1437 // Create the output OAT file.
1438 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001439 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001440 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001441 if (out_oat_fd.get() < 0) {
1442 return -1;
1443 }
1444
1445 // Open vdex files.
1446 Dex2oatFileWrapper in_vdex_fd;
1447 Dex2oatFileWrapper out_vdex_fd;
Calin Juravlec9eab382017-01-25 01:17:17 -08001448 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
Calin Juravle7a570e82017-01-14 16:23:30 -08001449 &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001450 return -1;
1451 }
1452
1453 // Create a swap file if necessary.
Calin Juravle7a570e82017-01-14 16:23:30 -08001454 base::unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001455
Calin Juravle7a570e82017-01-14 16:23:30 -08001456 // Create the app image file if needed.
1457 Dex2oatFileWrapper image_fd =
1458 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001459
Calin Juravle7a570e82017-01-14 16:23:30 -08001460 // Open the reference profile if needed.
1461 Dex2oatFileWrapper reference_profile_fd =
Calin Juravle80a21252017-01-17 14:43:25 -08001462 maybe_open_reference_profile(pkgname, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001463
Calin Juravlec9eab382017-01-25 01:17:17 -08001464 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001465
1466 pid_t pid = fork();
1467 if (pid == 0) {
1468 /* child -- drop privileges before continuing */
1469 drop_capabilities(uid);
1470
Richard Uhler76cc0272016-12-08 10:46:35 +00001471 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001472 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1473 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1474 _exit(67);
1475 }
1476
Richard Uhler76cc0272016-12-08 10:46:35 +00001477 // Pass dex2oat the relative path to the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001478 const char *input_file_name = get_location_from_path(dex_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001479 run_dex2oat(input_fd.get(),
1480 out_oat_fd.get(),
1481 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001482 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001483 image_fd.get(),
1484 input_file_name,
1485 out_oat_path,
1486 swap_fd.get(),
1487 instruction_set,
1488 compiler_filter,
1489 vm_safe_mode,
1490 debuggable,
1491 boot_complete,
1492 reference_profile_fd.get(),
1493 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001494 _exit(68); /* only get here on exec failure */
1495 } else {
1496 int res = wait_child(pid);
1497 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001498 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001499 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001500 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001501 return -1;
1502 }
1503 }
1504
Calin Juravlec9eab382017-01-25 01:17:17 -08001505 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001506
1507 // We've been successful, don't delete output.
1508 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001509 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001510 image_fd.SetCleanup(false);
1511 reference_profile_fd.SetCleanup(false);
1512
1513 return 0;
1514}
1515
Calin Juravlec9eab382017-01-25 01:17:17 -08001516// Try to remove the given directory. Log an error if the directory exists
1517// and is empty but could not be removed.
1518static bool rmdir_if_empty(const char* dir) {
1519 if (rmdir(dir) == 0) {
1520 return true;
1521 }
1522 if (errno == ENOENT || errno == ENOTEMPTY) {
1523 return true;
1524 }
1525 PLOG(ERROR) << "Failed to remove dir: " << dir;
1526 return false;
1527}
1528
1529// Try to unlink the given file. Log an error if the file exists and could not
1530// be unlinked.
1531static bool unlink_if_exists(const std::string& file) {
1532 if (unlink(file.c_str()) == 0) {
1533 return true;
1534 }
1535 if (errno == ENOENT) {
1536 return true;
1537
1538 }
1539 PLOG(ERROR) << "Could not unlink: " << file;
1540 return false;
1541}
1542
1543// Create the oat file structure for the secondary dex 'dex_path' and assign
1544// the individual path component to the 'out_' parameters.
1545static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1546 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1547 size_t dirIndex = dex_path.rfind('/');
1548 if (dirIndex == std::string::npos) {
1549 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1550 return false;
1551 }
1552 // TODO(calin): we have similar computations in at lest 3 other places
1553 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1554 // use string append.
1555 std::string apk_dir = dex_path.substr(0, dirIndex);
1556 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1557 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1558
1559 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1560 /*is_secondary_dex*/ true, out_oat_path)) {
1561 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1562 return false;
1563 }
1564 return true;
1565}
1566
1567// Reconcile the secondary dex 'dex_path' and its generated oat files.
1568// Return true if all the parameters are valid and the secondary dex file was
1569// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1570// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1571// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1572// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1573// Return false if there were errors during processing. In this case
1574// out_secondary_dex_exists will be set to false.
1575bool reconcile_secondary_dex_file(const std::string& dex_path,
1576 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1577 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1578 /*out*/bool* out_secondary_dex_exists) {
1579 // Set out to false to start with, just in case we have validation errors.
1580 *out_secondary_dex_exists = false;
1581 if (isas.size() == 0) {
1582 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1583 return false;
1584 }
1585
1586 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1587 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1588 uid, storage_flag)) {
1589 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1590 return false;
1591 }
1592
1593 if (access(dex_path.c_str(), F_OK) == 0) {
1594 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1595 *out_secondary_dex_exists = true;
1596 return true;
1597 } else if (errno != ENOENT) {
1598 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1599 return false;
1600 }
1601
1602 // The secondary dex does not exist anymore. Clear any generated files.
1603 char oat_path[PKG_PATH_MAX];
1604 char oat_dir[PKG_PATH_MAX];
1605 char oat_isa_dir[PKG_PATH_MAX];
1606 bool result = true;
1607 for (size_t i = 0; i < isas.size(); i++) {
1608 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1609 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1610 result = false;
1611 continue;
1612 }
1613 result = unlink_if_exists(oat_path) && result;
1614 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1615 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1616
1617 // Try removing the directories as well, they might be empty.
1618 result = rmdir_if_empty(oat_isa_dir) && result;
1619 result = rmdir_if_empty(oat_dir) && result;
1620 }
1621
1622 return result;
1623}
1624
Jeff Sharkey90aff262016-12-12 14:28:24 -07001625// Helper for move_ab, so that we can have common failure-case cleanup.
1626static bool unlink_and_rename(const char* from, const char* to) {
1627 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1628 // return a failure.
1629 struct stat s;
1630 if (stat(to, &s) == 0) {
1631 if (!S_ISREG(s.st_mode)) {
1632 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1633 return false;
1634 }
1635 if (unlink(to) != 0) {
1636 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1637 return false;
1638 }
1639 } else {
1640 // This may be a permission problem. We could investigate the error code, but we'll just
1641 // let the rename failure do the work for us.
1642 }
1643
1644 // Try to rename "to" to "from."
1645 if (rename(from, to) != 0) {
1646 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1647 return false;
1648 }
1649 return true;
1650}
1651
1652// Move/rename a B artifact (from) to an A artifact (to).
1653static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1654 // Check whether B exists.
1655 {
1656 struct stat s;
1657 if (stat(b_path.c_str(), &s) != 0) {
1658 // Silently ignore for now. The service calling this isn't smart enough to understand
1659 // lack of artifacts at the moment.
1660 return false;
1661 }
1662 if (!S_ISREG(s.st_mode)) {
1663 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1664 // Try to unlink, but swallow errors.
1665 unlink(b_path.c_str());
1666 return false;
1667 }
1668 }
1669
1670 // Rename B to A.
1671 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1672 // Delete the b_path so we don't try again (or fail earlier).
1673 if (unlink(b_path.c_str()) != 0) {
1674 PLOG(ERROR) << "Could not unlink " << b_path;
1675 }
1676
1677 return false;
1678 }
1679
1680 return true;
1681}
1682
1683bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1684 // Get the current slot suffix. No suffix, no A/B.
1685 std::string slot_suffix;
1686 {
1687 char buf[kPropertyValueMax];
1688 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1689 return false;
1690 }
1691 slot_suffix = buf;
1692
1693 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1694 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1695 return false;
1696 }
1697 }
1698
1699 // Validate other inputs.
1700 if (validate_apk_path(apk_path) != 0) {
1701 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1702 return false;
1703 }
1704 if (validate_apk_path(oat_dir) != 0) {
1705 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1706 return false;
1707 }
1708
1709 char a_path[PKG_PATH_MAX];
1710 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1711 return false;
1712 }
1713 const std::string a_vdex_path = create_vdex_filename(a_path);
1714 const std::string a_image_path = create_image_filename(a_path);
1715
1716 // B path = A path + slot suffix.
1717 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1718 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1719 const std::string b_image_path = StringPrintf("%s.%s",
1720 a_image_path.c_str(),
1721 slot_suffix.c_str());
1722
1723 bool success = true;
1724 if (move_ab_path(b_path, a_path)) {
1725 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1726 // Note: we can live without an app image. As such, ignore failure to move the image file.
1727 // If we decide to require the app image, or the app image being moved correctly,
1728 // then change accordingly.
1729 constexpr bool kIgnoreAppImageFailure = true;
1730
1731 if (!a_image_path.empty()) {
1732 if (!move_ab_path(b_image_path, a_image_path)) {
1733 unlink(a_image_path.c_str());
1734 if (!kIgnoreAppImageFailure) {
1735 success = false;
1736 }
1737 }
1738 }
1739 } else {
1740 // Cleanup: delete B image, ignore errors.
1741 unlink(b_image_path.c_str());
1742 success = false;
1743 }
1744 } else {
1745 // Cleanup: delete B image, ignore errors.
1746 unlink(b_vdex_path.c_str());
1747 unlink(b_image_path.c_str());
1748 success = false;
1749 }
1750 return success;
1751}
1752
1753bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1754 // Delete the oat/odex file.
1755 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001756 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
1757 /*is_secondary_dex*/ false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001758 return false;
1759 }
1760
1761 // In case of a permission failure report the issue. Otherwise just print a warning.
1762 auto unlink_and_check = [](const char* path) -> bool {
1763 int result = unlink(path);
1764 if (result != 0) {
1765 if (errno == EACCES || errno == EPERM) {
1766 PLOG(ERROR) << "Could not unlink " << path;
1767 return false;
1768 }
1769 PLOG(WARNING) << "Could not unlink " << path;
1770 }
1771 return true;
1772 };
1773
1774 // Delete the oat/odex file.
1775 bool return_value_oat = unlink_and_check(out_path);
1776
1777 // Derive and delete the app image.
1778 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1779
1780 // Report success.
1781 return return_value_oat && return_value_art;
1782}
1783
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001784int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1785 return dexopt(params[0], // apk_path
1786 atoi(params[1]), // uid
1787 params[2], // pkgname
1788 params[3], // instruction_set
1789 atoi(params[4]), // dexopt_needed
1790 params[5], // oat_dir
1791 atoi(params[6]), // dexopt_flags
1792 params[7], // compiler_filter
1793 parse_null(params[8]), // volume_uuid
1794 parse_null(params[9])); // shared_libraries
1795 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1796}
1797
1798} // namespace installd
1799} // namespace android