blob: b4c4e5c42939b59f7cf553fff7fc033472dc3313 [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
Calin Juravle2289c0a2017-02-15 12:44:14 -0800857static bool set_permissions_and_ownership(
858 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
859 // Primary apks are owned by the system. Secondary dex files are owned by the app.
860 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700861 if (fchmod(fd,
862 S_IRUSR|S_IWUSR|S_IRGRP |
863 (is_public ? S_IROTH : 0)) < 0) {
864 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
865 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800866 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867 ALOGE("installd cannot chown '%s' during dexopt\n", path);
868 return false;
869 }
870 return true;
871}
872
873static bool IsOutputDalvikCache(const char* oat_dir) {
874 // InstallerConnection.java (which invokes installd) transforms Java null arguments
875 // into '!'. Play it safe by handling it both.
876 // TODO: ensure we never get null.
877 // TODO: pass a flag instead of inferring if the output is dalvik cache.
878 return oat_dir == nullptr || oat_dir[0] == '!';
879}
880
881static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800882 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883 // Early best-effort check whether we can fit the the path into our buffers.
884 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
885 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
886 // extension to the cache path (5 bytes).
887 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
888 ALOGE("apk_path too long '%s'\n", apk_path);
889 return false;
890 }
891
892 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800893 // Oat dirs for secondary dex files are already validated.
894 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700895 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
896 return false;
897 }
898 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
899 return false;
900 }
901 } else {
902 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
903 return false;
904 }
905 }
906 return true;
907}
908
909// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
910// on destruction. It will also run the given cleanup (unless told not to) after closing.
911//
912// Usage example:
913//
Calin Juravle7a570e82017-01-14 16:23:30 -0800914// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700915// [name]() {
916// unlink(name.c_str());
917// });
918// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
919// wrapper if captured as a reference.
920//
921// if (file.get() == -1) {
922// // Error opening...
923// }
924//
925// ...
926// if (error) {
927// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
928// // and delete the file (after the fd is closed).
929// return -1;
930// }
931//
932// (Success case)
933// file.SetCleanup(false);
934// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
935// // (leaving the file around; after the fd is closed).
936//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937class Dex2oatFileWrapper {
938 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800939 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700940 }
941
Calin Juravle7a570e82017-01-14 16:23:30 -0800942 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
943 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
944
945 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
946 value_ = other.value_;
947 cleanup_ = other.cleanup_;
948 do_cleanup_ = other.do_cleanup_;
949 auto_close_ = other.auto_close_;
950 other.release();
951 }
952
953 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
954 value_ = other.value_;
955 cleanup_ = other.cleanup_;
956 do_cleanup_ = other.do_cleanup_;
957 auto_close_ = other.auto_close_;
958 other.release();
959 return *this;
960 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700961
962 ~Dex2oatFileWrapper() {
963 reset(-1);
964 }
965
966 int get() {
967 return value_;
968 }
969
970 void SetCleanup(bool cleanup) {
971 do_cleanup_ = cleanup;
972 }
973
974 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -0800975 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700976 close(value_);
977 }
978 if (do_cleanup_ && cleanup_ != nullptr) {
979 cleanup_();
980 }
981
982 value_ = new_value;
983 }
984
Calin Juravle7a570e82017-01-14 16:23:30 -0800985 void reset(int new_value, std::function<void ()> new_cleanup) {
986 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700987 close(value_);
988 }
989 if (do_cleanup_ && cleanup_ != nullptr) {
990 cleanup_();
991 }
992
993 value_ = new_value;
994 cleanup_ = new_cleanup;
995 }
996
Calin Juravle7a570e82017-01-14 16:23:30 -0800997 void DisableAutoClose() {
998 auto_close_ = false;
999 }
1000
Jeff Sharkey90aff262016-12-12 14:28:24 -07001001 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001002 void release() {
1003 value_ = -1;
1004 do_cleanup_ = false;
1005 cleanup_ = nullptr;
1006 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001008 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001010 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001011};
1012
Calin Juravle7a570e82017-01-14 16:23:30 -08001013// (re)Creates the app image if needed.
1014Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001015 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001016 // Use app images only if it is enabled (by a set image format) and we are compiling
1017 // profile-guided (so the app image doesn't conservatively contain all classes).
Calin Juravle2289c0a2017-02-15 12:44:14 -08001018 // Note that we don't create an image for secondary dex files.
1019 if (is_secondary_dex || !profile_guided) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001020 return Dex2oatFileWrapper();
1021 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001022
Calin Juravle7a570e82017-01-14 16:23:30 -08001023 const std::string image_path = create_image_filename(out_oat_path);
1024 if (image_path.empty()) {
1025 // Happens when the out_oat_path has an unknown extension.
1026 return Dex2oatFileWrapper();
1027 }
1028 char app_image_format[kPropertyValueMax];
1029 bool have_app_image_format =
1030 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1031 if (!have_app_image_format) {
1032 return Dex2oatFileWrapper();
1033 }
1034 // Recreate is true since we do not want to modify a mapped image. If the app is
1035 // already running and we modify the image file, it can cause crashes (b/27493510).
1036 Dex2oatFileWrapper wrapper_fd(
1037 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1038 [image_path]() { unlink(image_path.c_str()); });
1039 if (wrapper_fd.get() < 0) {
1040 // Could not create application image file. Go on since we can compile without it.
1041 LOG(ERROR) << "installd could not create '" << image_path
1042 << "' for image file during dexopt";
1043 // If we have a valid image file path but no image fd, explicitly erase the image file.
1044 if (unlink(image_path.c_str()) < 0) {
1045 if (errno != ENOENT) {
1046 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1047 }
1048 }
1049 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001050 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001051 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1052 wrapper_fd.reset(-1);
1053 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001054
Calin Juravle7a570e82017-01-14 16:23:30 -08001055 return wrapper_fd;
1056}
1057
1058// Creates the dexopt swap file if necessary and return its fd.
1059// Returns -1 if there's no need for a swap or in case of errors.
1060base::unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
1061 if (!ShouldUseSwapFileForDexopt()) {
1062 return base::unique_fd();
1063 }
1064 // Make sure there really is enough space.
1065 char swap_file_name[PKG_PATH_MAX];
1066 strcpy(swap_file_name, out_oat_path);
1067 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
1068 return base::unique_fd();
1069 }
1070 base::unique_fd swap_fd(open_output_file(
1071 swap_file_name, /*recreate*/true, /*permissions*/0600));
1072 if (swap_fd.get() < 0) {
1073 // Could not create swap file. Optimistically go on and hope that we can compile
1074 // without it.
1075 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1076 } else {
1077 // Immediately unlink. We don't really want to hit flash.
1078 if (unlink(swap_file_name) < 0) {
1079 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1080 }
1081 }
1082 return swap_fd;
1083}
1084
1085// Opens the reference profiles if needed.
1086// Note that the reference profile might not exist so it's OK if the fd will be -1.
1087Dex2oatFileWrapper maybe_open_reference_profile(const char* pkgname, bool profile_guided,
Calin Juravle80a21252017-01-17 14:43:25 -08001088 bool is_public, int uid, bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089 // Public apps should not be compiled with profile information ever. Same goes for the special
1090 // package '*' used for the system server.
Calin Juravle80a21252017-01-17 14:43:25 -08001091 // TODO(calin): add support for writing profiles for secondary dex files
1092 if (profile_guided && !is_secondary_dex && !is_public && (pkgname[0] != '*')) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001093 // Open reference profile in read only mode as dex2oat does not get write permissions.
1094 const std::string pkgname_str(pkgname);
Calin Juravle7a570e82017-01-14 16:23:30 -08001095 return Dex2oatFileWrapper(
1096 open_reference_profile(uid, pkgname, /*read_write*/ false),
1097 [pkgname_str]() {
1098 clear_reference_profile(pkgname_str.c_str());
1099 });
1100 } else {
1101 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001102 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001103}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001104
Calin Juravle7a570e82017-01-14 16:23:30 -08001105// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1106// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1107bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001108 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
1109 Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001110 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1111 CHECK(in_vdex_wrapper_fd != nullptr);
1112 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001113 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1114 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001115 char in_odex_path[PKG_PATH_MAX];
1116 int dexopt_action = abs(dexopt_needed);
1117 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001118 std::string in_vdex_path_str;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001119 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001120 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1121 const char* path = nullptr;
1122 if (is_odex_location) {
1123 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1124 path = in_odex_path;
1125 } else {
1126 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001127 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001128 }
1129 } else {
1130 path = out_oat_path;
1131 }
1132 in_vdex_path_str = create_vdex_filename(path);
1133 if (in_vdex_path_str.empty()) {
1134 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001135 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001136 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001137 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001138 // When we dex2oat because of boot image change, we are going to update
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001139 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001141 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001142 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001143 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001144 }
1145
1146 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001147 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001148 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001149 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001150 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001151
1152 // If we are compiling because the boot image is out of date, we do not
1153 // need to recreate a vdex, and can use the same existing one.
1154 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001155 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001156 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001157 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1158 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1159 // wrapper).
1160 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001161 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001162 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001163 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1164 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001165 if (out_vdex_wrapper_fd->get() < 0) {
1166 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1167 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001168 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001170 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001171 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001172 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1173 return false;
1174 }
1175
1176 // If we got here we successfully opened the vdex files.
1177 return true;
1178}
1179
1180// Opens the output oat file for the given apk.
1181// If successful it stores the output path into out_oat_path and returns true.
1182Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001183 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1184 char* out_oat_path) {
1185 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 return Dex2oatFileWrapper();
1187 }
1188 const std::string out_oat_path_str(out_oat_path);
1189 Dex2oatFileWrapper wrapper_fd(
1190 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1191 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1192 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001193 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001194 } else if (!set_permissions_and_ownership(
1195 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001196 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1197 wrapper_fd.reset(-1);
1198 }
1199 return wrapper_fd;
1200}
1201
1202// Updates the access times of out_oat_path based on those from apk_path.
1203void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1204 struct stat input_stat;
1205 memset(&input_stat, 0, sizeof(input_stat));
1206 if (stat(apk_path, &input_stat) != 0) {
1207 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1208 return;
1209 }
1210
1211 struct utimbuf ut;
1212 ut.actime = input_stat.st_atime;
1213 ut.modtime = input_stat.st_mtime;
1214 if (utime(out_oat_path, &ut) != 0) {
1215 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1216 }
1217}
1218
Calin Juravle80a21252017-01-17 14:43:25 -08001219// Runs (execv) dexoptanalyzer on the given arguments.
1220static void exec_dexoptanalyzer(const char* dex_file, const char* instruction_set,
1221 const char* compiler_filter) {
1222 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1223 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1224
1225 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1226 ALOGE("Instruction set %s longer than max length of %d",
1227 instruction_set, MAX_INSTRUCTION_SET_LEN);
1228 return;
1229 }
1230
1231 char dex_file_arg[strlen("--dex-file=") + PKG_PATH_MAX];
1232 char isa_arg[strlen("--isa=") + MAX_INSTRUCTION_SET_LEN];
1233 char compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
1234
1235 sprintf(dex_file_arg, "--dex-file=%s", dex_file);
1236 sprintf(isa_arg, "--isa=%s", instruction_set);
1237 sprintf(compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1238
1239 // program name, dex file, isa, filter, the final NULL
1240 const char* argv[5];
1241 int i = 0;
1242 argv[i++] = DEXOPTANALYZER_BIN;
1243 argv[i++] = dex_file_arg;
1244 argv[i++] = isa_arg;
1245 argv[i++] = compiler_filter_arg;
1246 argv[i] = NULL;
1247
1248 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1249 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1250}
1251
1252// Prepares the oat dir for the secondary dex files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001253static bool prepare_secondary_dex_oat_dir(const char* dex_path, int uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001254 const char* instruction_set, std::string* oat_dir_out) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001255 std::string apk_path_str(dex_path);
Calin Juravle80a21252017-01-17 14:43:25 -08001256 unsigned long dirIndex = apk_path_str.rfind('/');
1257 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001258 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001259 return false;
1260 }
1261 std::string apk_dir = apk_path_str.substr(0, dirIndex);
1262
1263 // Assign the gid to the cache gid so that the oat file storage
1264 // is counted towards the app cache.
1265 int32_t cache_gid = multiuser_get_cache_gid(
1266 multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1267 // If UID doesn't have a specific cache GID, use UID value
1268 if (cache_gid == -1) {
1269 cache_gid = uid;
1270 }
1271
1272 // Create oat file output directory.
1273 if (prepare_app_cache_dir(apk_dir, "oat", 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001274 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001275 return false;
1276 }
1277
1278 char oat_dir[PKG_PATH_MAX];
1279 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1280 oat_dir_out->assign(oat_dir);
1281
1282 // Create oat/isa output directory.
1283 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001284 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001285 return false;
1286 }
1287
1288 return true;
1289}
1290
1291static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1292
1293// Verifies the result of dexoptanalyzer executed for the apk_path.
1294// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1295// Returns false for errors or unexpected result values.
Calin Juravlec9eab382017-01-25 01:17:17 -08001296static bool process_dexoptanalyzer_result(const char* dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001297 int* dexopt_needed_out) {
1298 // The result values are defined in dexoptanalyzer.
1299 switch (result) {
1300 case 0: // no_dexopt_needed
1301 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1302 case 1: // dex2oat_from_scratch
1303 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1304 case 5: // dex2oat_for_bootimage_odex
1305 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1306 case 6: // dex2oat_for_filter_odex
1307 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1308 case 7: // dex2oat_for_relocation_odex
1309 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1310 case 2: // dex2oat_for_bootimage_oat
1311 case 3: // dex2oat_for_filter_oat
1312 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001313 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1314 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001315 << " : dexoptanalyzer result=" << result;
1316 return false;
1317 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001318 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001319 << " exec_dexoptanalyzer result=" << result;
1320 return false;
1321 }
1322}
1323
Calin Juravlec9eab382017-01-25 01:17:17 -08001324// 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 -08001325// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1326// successfully.
1327// When returning true, dexopt_needed_out is assigned a valid OatFileAsssitant::DexOptNeeded
1328// 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 -08001329static bool process_secondary_dex_dexopt(const char* dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001330 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
1331 const char* compiler_filter, int* dexopt_needed_out, std::string* aot_dir_out) {
1332 int storage_flag;
1333
1334 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1335 storage_flag = FLAG_STORAGE_CE;
1336 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1337 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1338 return false;
1339 }
1340 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1341 storage_flag = FLAG_STORAGE_DE;
1342 } else {
1343 LOG(ERROR) << "Secondary dex storage flag must be set";
1344 return false;
1345 }
1346
Calin Juravlec9eab382017-01-25 01:17:17 -08001347 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1348 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001349 return false;
1350 }
1351
1352 // Check if the path exist. If not, there's nothing to do.
Calin Juravlec9eab382017-01-25 01:17:17 -08001353 if (access(dex_path, F_OK) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001354 if (errno == ENOENT) {
1355 // Secondary dex files might be deleted any time by the app.
1356 // Nothing to do if that's the case
Calin Juravlec9eab382017-01-25 01:17:17 -08001357 ALOGV("Secondary dex does not exist %s", dex_path);
Calin Juravle80a21252017-01-17 14:43:25 -08001358 return NO_DEXOPT_NEEDED;
1359 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001360 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001361 }
1362 }
1363
1364 // Prepare the oat directories.
Calin Juravlec9eab382017-01-25 01:17:17 -08001365 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, aot_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001366 return false;
1367 }
1368
1369 pid_t pid = fork();
1370 if (pid == 0) {
1371 // child -- drop privileges before continuing.
1372 drop_capabilities(uid);
1373 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravlec9eab382017-01-25 01:17:17 -08001374 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter);
Calin Juravle80a21252017-01-17 14:43:25 -08001375 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1376 }
1377
1378 /* parent */
1379
1380 int result = wait_child(pid);
1381 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001382 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001383 return false;
1384 }
1385 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001386 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001387 // Run dexopt only if needed or forced.
1388 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1389 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1390 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1391 // for oat files from dalvik-cache.
1392 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1393 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1394 }
1395
1396 return success;
1397}
1398
Calin Juravlec9eab382017-01-25 01:17:17 -08001399int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001400 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1401 const char* volume_uuid, const char* shared_libraries) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001402 CHECK(pkgname != nullptr);
1403 CHECK(pkgname[0] != 0);
1404 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1405 LOG_FATAL("dexopt flags contains unknown fields\n");
1406 }
1407
1408 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1409 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1410 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1411 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1412 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001413 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1414
1415 // Check if we're dealing with a secondary dex file and if we need to compile it.
1416 std::string oat_dir_str;
1417 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001418 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001419 instruction_set, compiler_filter, &dexopt_needed, &oat_dir_str)) {
1420 oat_dir = oat_dir_str.c_str();
1421 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1422 return 0; // Nothing to do, report success.
1423 }
1424 } else {
1425 return -1; // We had an error, logged in the process method.
1426 }
1427 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001428 // Currently these flags are only use for secondary dex files.
1429 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001430 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1431 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1432 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001433
1434 // Open the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001435 base::unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001436 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001437 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001438 return -1;
1439 }
1440
1441 // Create the output OAT file.
1442 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001443 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001444 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001445 if (out_oat_fd.get() < 0) {
1446 return -1;
1447 }
1448
1449 // Open vdex files.
1450 Dex2oatFileWrapper in_vdex_fd;
1451 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001452 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
1453 is_secondary_dex, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001454 return -1;
1455 }
1456
1457 // Create a swap file if necessary.
Calin Juravle7a570e82017-01-14 16:23:30 -08001458 base::unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001459
Calin Juravle7a570e82017-01-14 16:23:30 -08001460 // Create the app image file if needed.
1461 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001462 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001463
Calin Juravle7a570e82017-01-14 16:23:30 -08001464 // Open the reference profile if needed.
1465 Dex2oatFileWrapper reference_profile_fd =
Calin Juravle80a21252017-01-17 14:43:25 -08001466 maybe_open_reference_profile(pkgname, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001467
Calin Juravlec9eab382017-01-25 01:17:17 -08001468 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001469
1470 pid_t pid = fork();
1471 if (pid == 0) {
1472 /* child -- drop privileges before continuing */
1473 drop_capabilities(uid);
1474
Richard Uhler76cc0272016-12-08 10:46:35 +00001475 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001476 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1477 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1478 _exit(67);
1479 }
1480
Richard Uhler76cc0272016-12-08 10:46:35 +00001481 // Pass dex2oat the relative path to the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001482 const char *input_file_name = get_location_from_path(dex_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001483 run_dex2oat(input_fd.get(),
1484 out_oat_fd.get(),
1485 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001486 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001487 image_fd.get(),
1488 input_file_name,
1489 out_oat_path,
1490 swap_fd.get(),
1491 instruction_set,
1492 compiler_filter,
1493 vm_safe_mode,
1494 debuggable,
1495 boot_complete,
1496 reference_profile_fd.get(),
1497 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001498 _exit(68); /* only get here on exec failure */
1499 } else {
1500 int res = wait_child(pid);
1501 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001502 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001503 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001504 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001505 return -1;
1506 }
1507 }
1508
Calin Juravlec9eab382017-01-25 01:17:17 -08001509 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001510
1511 // We've been successful, don't delete output.
1512 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001513 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001514 image_fd.SetCleanup(false);
1515 reference_profile_fd.SetCleanup(false);
1516
1517 return 0;
1518}
1519
Calin Juravlec9eab382017-01-25 01:17:17 -08001520// Try to remove the given directory. Log an error if the directory exists
1521// and is empty but could not be removed.
1522static bool rmdir_if_empty(const char* dir) {
1523 if (rmdir(dir) == 0) {
1524 return true;
1525 }
1526 if (errno == ENOENT || errno == ENOTEMPTY) {
1527 return true;
1528 }
1529 PLOG(ERROR) << "Failed to remove dir: " << dir;
1530 return false;
1531}
1532
1533// Try to unlink the given file. Log an error if the file exists and could not
1534// be unlinked.
1535static bool unlink_if_exists(const std::string& file) {
1536 if (unlink(file.c_str()) == 0) {
1537 return true;
1538 }
1539 if (errno == ENOENT) {
1540 return true;
1541
1542 }
1543 PLOG(ERROR) << "Could not unlink: " << file;
1544 return false;
1545}
1546
1547// Create the oat file structure for the secondary dex 'dex_path' and assign
1548// the individual path component to the 'out_' parameters.
1549static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1550 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1551 size_t dirIndex = dex_path.rfind('/');
1552 if (dirIndex == std::string::npos) {
1553 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1554 return false;
1555 }
1556 // TODO(calin): we have similar computations in at lest 3 other places
1557 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1558 // use string append.
1559 std::string apk_dir = dex_path.substr(0, dirIndex);
1560 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1561 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1562
1563 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1564 /*is_secondary_dex*/ true, out_oat_path)) {
1565 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1566 return false;
1567 }
1568 return true;
1569}
1570
1571// Reconcile the secondary dex 'dex_path' and its generated oat files.
1572// Return true if all the parameters are valid and the secondary dex file was
1573// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1574// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1575// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1576// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1577// Return false if there were errors during processing. In this case
1578// out_secondary_dex_exists will be set to false.
1579bool reconcile_secondary_dex_file(const std::string& dex_path,
1580 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1581 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1582 /*out*/bool* out_secondary_dex_exists) {
1583 // Set out to false to start with, just in case we have validation errors.
1584 *out_secondary_dex_exists = false;
1585 if (isas.size() == 0) {
1586 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1587 return false;
1588 }
1589
1590 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1591 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1592 uid, storage_flag)) {
1593 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1594 return false;
1595 }
1596
1597 if (access(dex_path.c_str(), F_OK) == 0) {
1598 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1599 *out_secondary_dex_exists = true;
1600 return true;
1601 } else if (errno != ENOENT) {
1602 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1603 return false;
1604 }
1605
1606 // The secondary dex does not exist anymore. Clear any generated files.
1607 char oat_path[PKG_PATH_MAX];
1608 char oat_dir[PKG_PATH_MAX];
1609 char oat_isa_dir[PKG_PATH_MAX];
1610 bool result = true;
1611 for (size_t i = 0; i < isas.size(); i++) {
1612 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1613 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1614 result = false;
1615 continue;
1616 }
1617 result = unlink_if_exists(oat_path) && result;
1618 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1619 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1620
1621 // Try removing the directories as well, they might be empty.
1622 result = rmdir_if_empty(oat_isa_dir) && result;
1623 result = rmdir_if_empty(oat_dir) && result;
1624 }
1625
1626 return result;
1627}
1628
Jeff Sharkey90aff262016-12-12 14:28:24 -07001629// Helper for move_ab, so that we can have common failure-case cleanup.
1630static bool unlink_and_rename(const char* from, const char* to) {
1631 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1632 // return a failure.
1633 struct stat s;
1634 if (stat(to, &s) == 0) {
1635 if (!S_ISREG(s.st_mode)) {
1636 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1637 return false;
1638 }
1639 if (unlink(to) != 0) {
1640 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1641 return false;
1642 }
1643 } else {
1644 // This may be a permission problem. We could investigate the error code, but we'll just
1645 // let the rename failure do the work for us.
1646 }
1647
1648 // Try to rename "to" to "from."
1649 if (rename(from, to) != 0) {
1650 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1651 return false;
1652 }
1653 return true;
1654}
1655
1656// Move/rename a B artifact (from) to an A artifact (to).
1657static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1658 // Check whether B exists.
1659 {
1660 struct stat s;
1661 if (stat(b_path.c_str(), &s) != 0) {
1662 // Silently ignore for now. The service calling this isn't smart enough to understand
1663 // lack of artifacts at the moment.
1664 return false;
1665 }
1666 if (!S_ISREG(s.st_mode)) {
1667 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1668 // Try to unlink, but swallow errors.
1669 unlink(b_path.c_str());
1670 return false;
1671 }
1672 }
1673
1674 // Rename B to A.
1675 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1676 // Delete the b_path so we don't try again (or fail earlier).
1677 if (unlink(b_path.c_str()) != 0) {
1678 PLOG(ERROR) << "Could not unlink " << b_path;
1679 }
1680
1681 return false;
1682 }
1683
1684 return true;
1685}
1686
1687bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1688 // Get the current slot suffix. No suffix, no A/B.
1689 std::string slot_suffix;
1690 {
1691 char buf[kPropertyValueMax];
1692 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1693 return false;
1694 }
1695 slot_suffix = buf;
1696
1697 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1698 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1699 return false;
1700 }
1701 }
1702
1703 // Validate other inputs.
1704 if (validate_apk_path(apk_path) != 0) {
1705 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1706 return false;
1707 }
1708 if (validate_apk_path(oat_dir) != 0) {
1709 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1710 return false;
1711 }
1712
1713 char a_path[PKG_PATH_MAX];
1714 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1715 return false;
1716 }
1717 const std::string a_vdex_path = create_vdex_filename(a_path);
1718 const std::string a_image_path = create_image_filename(a_path);
1719
1720 // B path = A path + slot suffix.
1721 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1722 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1723 const std::string b_image_path = StringPrintf("%s.%s",
1724 a_image_path.c_str(),
1725 slot_suffix.c_str());
1726
1727 bool success = true;
1728 if (move_ab_path(b_path, a_path)) {
1729 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1730 // Note: we can live without an app image. As such, ignore failure to move the image file.
1731 // If we decide to require the app image, or the app image being moved correctly,
1732 // then change accordingly.
1733 constexpr bool kIgnoreAppImageFailure = true;
1734
1735 if (!a_image_path.empty()) {
1736 if (!move_ab_path(b_image_path, a_image_path)) {
1737 unlink(a_image_path.c_str());
1738 if (!kIgnoreAppImageFailure) {
1739 success = false;
1740 }
1741 }
1742 }
1743 } else {
1744 // Cleanup: delete B image, ignore errors.
1745 unlink(b_image_path.c_str());
1746 success = false;
1747 }
1748 } else {
1749 // Cleanup: delete B image, ignore errors.
1750 unlink(b_vdex_path.c_str());
1751 unlink(b_image_path.c_str());
1752 success = false;
1753 }
1754 return success;
1755}
1756
1757bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1758 // Delete the oat/odex file.
1759 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001760 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
1761 /*is_secondary_dex*/ false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001762 return false;
1763 }
1764
1765 // In case of a permission failure report the issue. Otherwise just print a warning.
1766 auto unlink_and_check = [](const char* path) -> bool {
1767 int result = unlink(path);
1768 if (result != 0) {
1769 if (errno == EACCES || errno == EPERM) {
1770 PLOG(ERROR) << "Could not unlink " << path;
1771 return false;
1772 }
1773 PLOG(WARNING) << "Could not unlink " << path;
1774 }
1775 return true;
1776 };
1777
1778 // Delete the oat/odex file.
1779 bool return_value_oat = unlink_and_check(out_path);
1780
1781 // Derive and delete the app image.
1782 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1783
1784 // Report success.
1785 return return_value_oat && return_value_art;
1786}
1787
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001788int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1789 return dexopt(params[0], // apk_path
1790 atoi(params[1]), // uid
1791 params[2], // pkgname
1792 params[3], // instruction_set
1793 atoi(params[4]), // dexopt_needed
1794 params[5], // oat_dir
1795 atoi(params[6]), // dexopt_flags
1796 params[7], // compiler_filter
1797 parse_null(params[8]), // volume_uuid
1798 parse_null(params[9])); // shared_libraries
1799 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1800}
1801
1802} // namespace installd
1803} // namespace android