blob: 63afdcd111385575f9e4a547904f882208cb6915 [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>
Calin Juravlecb556e32017-04-04 20:22:50 -070039#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070041
42#include "dexopt.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070043#include "installd_deps.h"
44#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070045#include "utils.h"
46
47using android::base::StringPrintf;
Jeff Sharkey90aff262016-12-12 14:28:24 -070048using android::base::EndsWith;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080049using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050
51namespace android {
52namespace installd {
53
Calin Juravle114f0812017-03-08 19:05:07 -080054// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
55struct FreeDelete {
56 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
57 void operator()(const void* ptr) const {
58 free(const_cast<void*>(ptr));
59 }
60};
61
62// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
63template <typename T>
64using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
65
Calin Juravle1a0af3b2017-03-09 14:33:33 -080066static unique_fd invalid_unique_fd() {
67 return unique_fd(-1);
68}
69
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070070static const char* parse_null(const char* arg) {
71 if (strcmp(arg, "!") == 0) {
72 return nullptr;
73 } else {
74 return arg;
75 }
76}
77
Jeff Sharkey90aff262016-12-12 14:28:24 -070078static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080079 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070080 if (ufd.get() < 0) {
81 if (errno != ENOENT) {
82 PLOG(WARNING) << "Could not open profile " << profile;
83 return false;
84 } else {
85 // Nothing to clear. That's ok.
86 return true;
87 }
88 }
89
90 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
91 if (errno != EWOULDBLOCK) {
92 PLOG(WARNING) << "Error locking profile " << profile;
93 }
94 // This implies that the app owning this profile is running
95 // (and has acquired the lock).
96 //
97 // If we can't acquire the lock bail out since clearing is useless anyway
98 // (the app will write again to the profile).
99 //
100 // Note:
101 // This does not impact the this is not an issue for the profiling correctness.
102 // In case this is needed because of an app upgrade, profiles will still be
103 // eventually cleared by the app itself due to checksum mismatch.
104 // If this is needed because profman advised, then keeping the data around
105 // until the next run is again not an issue.
106 //
107 // If the app attempts to acquire a lock while we've held one here,
108 // it will simply skip the current write cycle.
109 return false;
110 }
111
112 bool truncated = ftruncate(ufd.get(), 0) == 0;
113 if (!truncated) {
114 PLOG(WARNING) << "Could not truncate " << profile;
115 }
116 if (flock(ufd.get(), LOCK_UN) != 0) {
117 PLOG(WARNING) << "Error unlocking profile " << profile;
118 }
119 return truncated;
120}
121
Calin Juravle114f0812017-03-08 19:05:07 -0800122// Clear the reference profile for the given location.
123// The location is the package name for primary apks or the dex path for secondary dex files.
124static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
125 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700126}
127
Calin Juravle114f0812017-03-08 19:05:07 -0800128// Clear the reference profile for the given location.
129// The location is the package name for primary apks or the dex path for secondary dex files.
130static bool clear_current_profile(const std::string& pkgname, userid_t user,
131 bool is_secondary_dex) {
132 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700133}
134
Calin Juravle114f0812017-03-08 19:05:07 -0800135// Clear the reference profile for the primary apk of the given package.
136bool clear_primary_reference_profile(const std::string& pkgname) {
137 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
138}
139
140// Clear all current profile for the primary apk of the given package.
141bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700142 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800143 // For secondary dex files, we don't really need the user but we use it for sanity checks.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700144 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
145 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800146 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700147 }
148 return success;
149}
150
Calin Juravle114f0812017-03-08 19:05:07 -0800151// Clear the current profile for the primary apk of the given package and user.
152bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
153 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
154}
155
Jeff Sharkey90aff262016-12-12 14:28:24 -0700156static int split_count(const char *str)
157{
158 char *ctx;
159 int count = 0;
160 char buf[kPropertyValueMax];
161
162 strncpy(buf, str, sizeof(buf));
163 char *pBuf = buf;
164
165 while(strtok_r(pBuf, " ", &ctx) != NULL) {
166 count++;
167 pBuf = NULL;
168 }
169
170 return count;
171}
172
173static int split(char *buf, const char **argv)
174{
175 char *ctx;
176 int count = 0;
177 char *tok;
178 char *pBuf = buf;
179
180 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
181 argv[count++] = tok;
182 pBuf = NULL;
183 }
184
185 return count;
186}
187
Jeff Sharkey90aff262016-12-12 14:28:24 -0700188static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
189 const char* input_file_name, const char* output_file_name, int swap_fd,
190 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
191 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
192 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
193
194 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
195 ALOGE("Instruction set %s longer than max length of %d",
196 instruction_set, MAX_INSTRUCTION_SET_LEN);
197 return;
198 }
199
200 char dex2oat_Xms_flag[kPropertyValueMax];
201 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
202
203 char dex2oat_Xmx_flag[kPropertyValueMax];
204 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
205
206 char dex2oat_threads_buf[kPropertyValueMax];
207 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
208 ? "dalvik.vm.dex2oat-threads"
209 : "dalvik.vm.boot-dex2oat-threads",
210 dex2oat_threads_buf,
211 NULL) > 0;
212 char dex2oat_threads_arg[kPropertyValueMax + 2];
213 if (have_dex2oat_threads_flag) {
214 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
215 }
216
217 char dex2oat_isa_features_key[kPropertyKeyMax];
218 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
219 char dex2oat_isa_features[kPropertyValueMax];
220 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
221 dex2oat_isa_features, NULL) > 0;
222
223 char dex2oat_isa_variant_key[kPropertyKeyMax];
224 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
225 char dex2oat_isa_variant[kPropertyValueMax];
226 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
227 dex2oat_isa_variant, NULL) > 0;
228
229 const char *dex2oat_norelocation = "-Xnorelocate";
230 bool have_dex2oat_relocation_skip_flag = false;
231
232 char dex2oat_flags[kPropertyValueMax];
233 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
234 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
235 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
236
237 // If we booting without the real /data, don't spend time compiling.
238 char vold_decrypt[kPropertyValueMax];
239 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
240 bool skip_compilation = (have_vold_decrypt &&
241 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
242 (strcmp(vold_decrypt, "1") == 0)));
243
244 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
245
246 char app_image_format[kPropertyValueMax];
247 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
248 bool have_app_image_format =
249 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
250 if (have_app_image_format) {
251 sprintf(image_format_arg, "--image-format=%s", app_image_format);
252 }
253
254 char dex2oat_large_app_threshold[kPropertyValueMax];
255 bool have_dex2oat_large_app_threshold =
256 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
257 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
258 if (have_dex2oat_large_app_threshold) {
259 sprintf(dex2oat_large_app_threshold_arg,
260 "--very-large-app-threshold=%s",
261 dex2oat_large_app_threshold);
262 }
263
264 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
265
266 static const char* RUNTIME_ARG = "--runtime-arg";
267
268 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
269
George Burgess IV36cebe772017-01-25 11:52:01 -0800270 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
271 // use arraysize instead.
272 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
273 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
274 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
275 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
276 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
277 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
278 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
279 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
280 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
281 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
282 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
283 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700284 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800285 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700286 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800287 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700288
289 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
290 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
291 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
292 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
293 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
294 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
295 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
296 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
297 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
298 if (swap_fd >= 0) {
299 have_dex2oat_swap_fd = true;
300 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
301 }
302 if (image_fd >= 0) {
303 have_dex2oat_image_fd = true;
304 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
305 }
306
307 if (have_dex2oat_Xms_flag) {
308 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
309 }
310 if (have_dex2oat_Xmx_flag) {
311 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
312 }
313
314 // Compute compiler filter.
315
316 bool have_dex2oat_compiler_filter_flag;
317 if (skip_compilation) {
318 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
319 have_dex2oat_compiler_filter_flag = true;
320 have_dex2oat_relocation_skip_flag = true;
321 } else if (vm_safe_mode) {
322 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
323 have_dex2oat_compiler_filter_flag = true;
324 } else if (compiler_filter != nullptr &&
325 strlen(compiler_filter) + strlen("--compiler-filter=") <
326 arraysize(dex2oat_compiler_filter_arg)) {
327 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
328 have_dex2oat_compiler_filter_flag = true;
329 } else {
330 char dex2oat_compiler_filter_flag[kPropertyValueMax];
331 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
332 dex2oat_compiler_filter_flag, NULL) > 0;
333 if (have_dex2oat_compiler_filter_flag) {
334 sprintf(dex2oat_compiler_filter_arg,
335 "--compiler-filter=%s",
336 dex2oat_compiler_filter_flag);
337 }
338 }
339
340 // Check whether all apps should be compiled debuggable.
341 if (!debuggable) {
342 char prop_buf[kPropertyValueMax];
343 debuggable =
344 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
345 (prop_buf[0] == '1');
346 }
347 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
348 if (profile_fd != -1) {
349 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
350 }
351
352
353 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
354
355 const char* argv[9 // program name, mandatory arguments and the final NULL
356 + (have_dex2oat_isa_variant ? 1 : 0)
357 + (have_dex2oat_isa_features ? 1 : 0)
358 + (have_dex2oat_Xms_flag ? 2 : 0)
359 + (have_dex2oat_Xmx_flag ? 2 : 0)
360 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
361 + (have_dex2oat_threads_flag ? 1 : 0)
362 + (have_dex2oat_swap_fd ? 1 : 0)
363 + (have_dex2oat_image_fd ? 1 : 0)
364 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
365 + (generate_debug_info ? 1 : 0)
366 + (debuggable ? 1 : 0)
367 + (have_app_image_format ? 1 : 0)
368 + dex2oat_flags_count
369 + (profile_fd == -1 ? 0 : 1)
370 + (shared_libraries != nullptr ? 4 : 0)
371 + (have_dex2oat_large_app_threshold ? 1 : 0)];
372 int i = 0;
373 argv[i++] = DEX2OAT_BIN;
374 argv[i++] = zip_fd_arg;
375 argv[i++] = zip_location_arg;
376 argv[i++] = input_vdex_fd_arg;
377 argv[i++] = output_vdex_fd_arg;
378 argv[i++] = oat_fd_arg;
379 argv[i++] = oat_location_arg;
380 argv[i++] = instruction_set_arg;
381 if (have_dex2oat_isa_variant) {
382 argv[i++] = instruction_set_variant_arg;
383 }
384 if (have_dex2oat_isa_features) {
385 argv[i++] = instruction_set_features_arg;
386 }
387 if (have_dex2oat_Xms_flag) {
388 argv[i++] = RUNTIME_ARG;
389 argv[i++] = dex2oat_Xms_arg;
390 }
391 if (have_dex2oat_Xmx_flag) {
392 argv[i++] = RUNTIME_ARG;
393 argv[i++] = dex2oat_Xmx_arg;
394 }
395 if (have_dex2oat_compiler_filter_flag) {
396 argv[i++] = dex2oat_compiler_filter_arg;
397 }
398 if (have_dex2oat_threads_flag) {
399 argv[i++] = dex2oat_threads_arg;
400 }
401 if (have_dex2oat_swap_fd) {
402 argv[i++] = dex2oat_swap_fd;
403 }
404 if (have_dex2oat_image_fd) {
405 argv[i++] = dex2oat_image_fd;
406 }
407 if (generate_debug_info) {
408 argv[i++] = "--generate-debug-info";
409 }
410 if (debuggable) {
411 argv[i++] = "--debuggable";
412 }
413 if (have_app_image_format) {
414 argv[i++] = image_format_arg;
415 }
416 if (have_dex2oat_large_app_threshold) {
417 argv[i++] = dex2oat_large_app_threshold_arg;
418 }
419 if (dex2oat_flags_count) {
420 i += split(dex2oat_flags, argv + i);
421 }
422 if (have_dex2oat_relocation_skip_flag) {
423 argv[i++] = RUNTIME_ARG;
424 argv[i++] = dex2oat_norelocation;
425 }
426 if (profile_fd != -1) {
427 argv[i++] = profile_arg;
428 }
429 if (shared_libraries != nullptr) {
430 argv[i++] = RUNTIME_ARG;
431 argv[i++] = "-classpath";
432 argv[i++] = RUNTIME_ARG;
433 argv[i++] = shared_libraries;
434 }
435 // Do not add after dex2oat_flags, they should override others for debugging.
436 argv[i] = NULL;
437
438 execv(DEX2OAT_BIN, (char * const *)argv);
439 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
440}
441
442/*
443 * Whether dexopt should use a swap file when compiling an APK.
444 *
445 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
446 * itself, anyways).
447 *
448 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
449 *
450 * Otherwise, return true if this is a low-mem device.
451 *
452 * Otherwise, return default value.
453 */
454static bool kAlwaysProvideSwapFile = false;
455static bool kDefaultProvideSwapFile = true;
456
457static bool ShouldUseSwapFileForDexopt() {
458 if (kAlwaysProvideSwapFile) {
459 return true;
460 }
461
462 // Check the "override" property. If it exists, return value == "true".
463 char dex2oat_prop_buf[kPropertyValueMax];
464 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
465 if (strcmp(dex2oat_prop_buf, "true") == 0) {
466 return true;
467 } else {
468 return false;
469 }
470 }
471
472 // Shortcut for default value. This is an implementation optimization for the process sketched
473 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
474 // as low-mem is never returning false. The compiler will optimize this away if it can.
475 if (kDefaultProvideSwapFile) {
476 return true;
477 }
478
479 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
480 if (is_low_mem) {
481 return true;
482 }
483
484 // Default value must be false here.
485 return kDefaultProvideSwapFile;
486}
487
Richard Uhler76cc0272016-12-08 10:46:35 +0000488static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700489 if (set_to_bg) {
490 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
491 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
492 exit(70);
493 }
494 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
495 ALOGE("setpriority failed: %s\n", strerror(errno));
496 exit(71);
497 }
498 }
499}
500
Calin Juravle114f0812017-03-08 19:05:07 -0800501static bool create_profile(int uid, const std::string& profile) {
502 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), O_CREAT | O_NOFOLLOW, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800503 if (fd.get() < 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800504 if (errno == EEXIST) {
505 return true;
506 } else {
507 PLOG(ERROR) << "Failed to create profile " << profile;
508 return false;
509 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700510 }
Calin Juravle114f0812017-03-08 19:05:07 -0800511 // Profiles should belong to the app; make sure of that by giving ownership to
512 // the app uid. If we cannot do that, there's no point in returning the fd
513 // since dex2oat/profman will fail with SElinux denials.
514 if (fchown(fd.get(), uid, uid) < 0) {
515 PLOG(ERROR) << "Could not chwon profile " << profile;
516 return false;
517 }
518 return true;
519}
520
521static unique_fd open_profile(int uid, const std::string& profile, bool read_write) {
522 // Check if we need to open the profile for a read-write operation. If so, we
523 // might need to create the profile since the file might not be there. Reference
524 // profiles are created on the fly so they might not exist beforehand.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525 if (read_write) {
Calin Juravle114f0812017-03-08 19:05:07 -0800526 if (!create_profile(uid, profile)) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800527 return invalid_unique_fd();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700528 }
529 }
Calin Juravle114f0812017-03-08 19:05:07 -0800530 int flags = read_write ? O_RDWR : O_RDONLY;
531 // Do not follow symlinks when opening a profile:
532 // - primary profiles should not contain symlinks in their paths
533 // - secondary dex paths should have been already resolved and validated
534 flags |= O_NOFOLLOW;
535
536 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
537 if (fd.get() < 0) {
538 if (errno != ENOENT) {
539 // Profiles might be missing for various reasons. For example, in a
540 // multi-user environment, the profile directory for one user can be created
541 // after we start a merge. In this case the current profile for that user
542 // will not be found.
543 // Also, the secondary dex profiles might be deleted by the app at any time,
544 // so we can't we need to prepare if they are missing.
545 PLOG(ERROR) << "Failed to open profile " << profile;
546 }
547 return invalid_unique_fd();
548 }
549
Jeff Sharkey90aff262016-12-12 14:28:24 -0700550 return fd;
551}
552
Calin Juravle114f0812017-03-08 19:05:07 -0800553static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
554 bool is_secondary_dex) {
555 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
556 return open_profile(uid, profile, /*read_write*/false);
557}
558
559static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
560 bool is_secondary_dex) {
561 std::string profile = create_reference_profile_path(location, is_secondary_dex);
562 return open_profile(uid, profile, read_write);
563}
564
565static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800566 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700567 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800568 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
569 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700570
Calin Juravle114f0812017-03-08 19:05:07 -0800571 // For secondary dex files, we don't really need the user but we use it for sanity checks.
572 // Note: the user owning the dex file should be the current user.
573 std::vector<userid_t> users;
574 if (is_secondary_dex){
575 users.push_back(multiuser_get_user_id(uid));
576 } else {
577 users = get_known_users(/*volume_uuid*/ nullptr);
578 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700579 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800580 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700581 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800582 if (profile_fd.get() >= 0) {
583 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700584 }
585 }
586}
587
588static void drop_capabilities(uid_t uid) {
589 if (setgid(uid) != 0) {
590 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
591 exit(64);
592 }
593 if (setuid(uid) != 0) {
594 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
595 exit(65);
596 }
597 // drop capabilities
598 struct __user_cap_header_struct capheader;
599 struct __user_cap_data_struct capdata[2];
600 memset(&capheader, 0, sizeof(capheader));
601 memset(&capdata, 0, sizeof(capdata));
602 capheader.version = _LINUX_CAPABILITY_VERSION_3;
603 if (capset(&capheader, &capdata[0]) < 0) {
604 ALOGE("capset failed: %s\n", strerror(errno));
605 exit(66);
606 }
607}
608
609static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
610static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
611static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
612static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
613static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
614
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800615static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
616 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 static const size_t MAX_INT_LEN = 32;
618 static const char* PROFMAN_BIN = "/system/bin/profman";
619
620 std::vector<std::string> profile_args(profiles_fd.size());
621 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
622 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800623 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700624 profile_args[k].assign(profile_buf);
625 }
626 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800627 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700628
629 // program name, reference profile fd, the final NULL and the profile fds
630 const char* argv[3 + profiles_fd.size()];
631 int i = 0;
632 argv[i++] = PROFMAN_BIN;
633 argv[i++] = reference_profile_arg;
634 for (size_t k = 0; k < profile_args.size(); k++) {
635 argv[i++] = profile_args[k].c_str();
636 }
637 // Do not add after dex2oat_flags, they should override others for debugging.
638 argv[i] = NULL;
639
640 execv(PROFMAN_BIN, (char * const *)argv);
641 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
642 exit(68); /* only get here on exec failure */
643}
644
645// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800646// The location is the package name for primary apks or the dex path for secondary dex files.
647// Returns true if there is enough information in the current profiles that makes it
648// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700649// If the return value is true all the current profiles would have been merged into
650// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800651static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800652 std::vector<unique_fd> profiles_fd;
653 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800654 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800655 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 // Skip profile guided compilation because no profiles were found.
657 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700658 return false;
659 }
660
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 pid_t pid = fork();
662 if (pid == 0) {
663 /* child -- drop privileges before continuing */
664 drop_capabilities(uid);
665 run_profman_merge(profiles_fd, reference_profile_fd);
666 exit(68); /* only get here on exec failure */
667 }
668 /* parent */
669 int return_code = wait_child(pid);
670 bool need_to_compile = false;
671 bool should_clear_current_profiles = false;
672 bool should_clear_reference_profile = false;
673 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800674 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700675 } else {
676 return_code = WEXITSTATUS(return_code);
677 switch (return_code) {
678 case PROFMAN_BIN_RETURN_CODE_COMPILE:
679 need_to_compile = true;
680 should_clear_current_profiles = true;
681 should_clear_reference_profile = false;
682 break;
683 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
684 need_to_compile = false;
685 should_clear_current_profiles = false;
686 should_clear_reference_profile = false;
687 break;
688 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800689 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 need_to_compile = false;
691 should_clear_current_profiles = true;
692 should_clear_reference_profile = true;
693 break;
694 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
695 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
696 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800697 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700698 need_to_compile = false;
699 should_clear_current_profiles = false;
700 should_clear_reference_profile = false;
701 break;
702 default:
703 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800704 LOG(WARNING) << "Unknown error code while processing profiles for location "
705 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700706 need_to_compile = false;
707 should_clear_current_profiles = true;
708 should_clear_reference_profile = true;
709 break;
710 }
711 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800712
Jeff Sharkey90aff262016-12-12 14:28:24 -0700713 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800714 if (is_secondary_dex) {
715 // For secondary dex files, the owning user is the current user.
716 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
717 } else {
718 clear_primary_current_profiles(location);
719 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700720 }
721 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800722 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700723 }
724 return need_to_compile;
725}
726
Calin Juravle114f0812017-03-08 19:05:07 -0800727// Decides if profile guided compilation is needed or not based on existing profiles.
728// The analysis is done for the primary apks of the given package.
729// Returns true if there is enough information in the current profiles that makes it
730// worth to recompile the package.
731// If the return value is true all the current profiles would have been merged into
732// the reference profiles accessible with open_reference_profile().
733bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
734 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
735}
736
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800737static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
738 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700739 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800740 const std::vector<unique_fd>& apk_fds,
741 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742 std::vector<std::string> profman_args;
743 static const char* PROFMAN_BIN = "/system/bin/profman";
744 profman_args.push_back(PROFMAN_BIN);
745 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800746 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747 if (reference_profile_fd != -1) {
748 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800749 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800751 for (size_t i = 0; i < profile_fds.size(); i++) {
752 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700753 }
754 for (const std::string& dex_location : dex_locations) {
755 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
756 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800757 for (size_t i = 0; i < apk_fds.size(); i++) {
758 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700759 }
760 const char **argv = new const char*[profman_args.size() + 1];
761 size_t i = 0;
762 for (const std::string& profman_arg : profman_args) {
763 argv[i++] = profman_arg.c_str();
764 }
765 argv[i] = NULL;
766
767 execv(PROFMAN_BIN, (char * const *)argv);
768 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
769 exit(68); /* only get here on exec failure */
770}
771
772static const char* get_location_from_path(const char* path) {
773 static constexpr char kLocationSeparator = '/';
774 const char *location = strrchr(path, kLocationSeparator);
775 if (location == NULL) {
776 return path;
777 } else {
778 // Skip the separator character.
779 return location + 1;
780 }
781}
782
Calin Juravle76268c52017-03-09 13:19:42 -0800783bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800784 std::vector<unique_fd> profile_fds;
785 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800786 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700787
Calin Juravle114f0812017-03-08 19:05:07 -0800788 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
789 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700790
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800791 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792 const bool has_profiles = !profile_fds.empty();
793
794 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800795 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700796 return false;
797 }
798
Calin Juravle114f0812017-03-08 19:05:07 -0800799 unique_fd output_fd(open(out_file_name.c_str(),
800 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700801 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
802 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
803 return false;
804 }
805 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
806 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800807 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808 for (const std::string& code_full_path : code_full_paths) {
809 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800810 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700811 if (apk_fd == -1) {
812 ALOGE("installd cannot open '%s'\n", full_path);
813 return false;
814 }
815 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800816 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 }
818
819 pid_t pid = fork();
820 if (pid == 0) {
821 /* child -- drop privileges before continuing */
822 drop_capabilities(uid);
823 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
824 apk_fds, output_fd);
825 exit(68); /* only get here on exec failure */
826 }
827 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700828 int return_code = wait_child(pid);
829 if (!WIFEXITED(return_code)) {
830 LOG(WARNING) << "profman failed for package " << pkgname << ": "
831 << return_code;
832 return false;
833 }
834 return true;
835}
836
837static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
838 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
839 if (EndsWith(oat_path, ".dex")) {
840 std::string new_path = oat_path;
841 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
842 CHECK(EndsWith(new_path, new_ext.c_str()));
843 return new_path;
844 }
845
846 // An odex entry. Not that this may not be an extension, e.g., in the OTA
847 // case (where the base name will have an extension for the B artifact).
848 size_t odex_pos = oat_path.rfind(".odex");
849 if (odex_pos != std::string::npos) {
850 std::string new_path = oat_path;
851 new_path.replace(odex_pos, strlen(".odex"), new_ext);
852 CHECK_NE(new_path.find(new_ext), std::string::npos);
853 return new_path;
854 }
855
856 // Don't know how to handle this.
857 return "";
858}
859
860// Translate the given oat path to an art (app image) path. An empty string
861// denotes an error.
862static std::string create_image_filename(const std::string& oat_path) {
863 return replace_file_extension(oat_path, ".art");
864}
865
866// Translate the given oat path to a vdex path. An empty string denotes an error.
867static std::string create_vdex_filename(const std::string& oat_path) {
868 return replace_file_extension(oat_path, ".vdex");
869}
870
871static bool add_extension_to_file_name(char* file_name, const char* extension) {
872 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
873 return false;
874 }
875 strcat(file_name, extension);
876 return true;
877}
878
879static int open_output_file(const char* file_name, bool recreate, int permissions) {
880 int flags = O_RDWR | O_CREAT;
881 if (recreate) {
882 if (unlink(file_name) < 0) {
883 if (errno != ENOENT) {
884 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
885 }
886 }
887 flags |= O_EXCL;
888 }
889 return open(file_name, flags, permissions);
890}
891
Calin Juravle2289c0a2017-02-15 12:44:14 -0800892static bool set_permissions_and_ownership(
893 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
894 // Primary apks are owned by the system. Secondary dex files are owned by the app.
895 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 if (fchmod(fd,
897 S_IRUSR|S_IWUSR|S_IRGRP |
898 (is_public ? S_IROTH : 0)) < 0) {
899 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
900 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800901 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 ALOGE("installd cannot chown '%s' during dexopt\n", path);
903 return false;
904 }
905 return true;
906}
907
908static bool IsOutputDalvikCache(const char* oat_dir) {
909 // InstallerConnection.java (which invokes installd) transforms Java null arguments
910 // into '!'. Play it safe by handling it both.
911 // TODO: ensure we never get null.
912 // TODO: pass a flag instead of inferring if the output is dalvik cache.
913 return oat_dir == nullptr || oat_dir[0] == '!';
914}
915
916static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800917 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700918 // Early best-effort check whether we can fit the the path into our buffers.
919 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
920 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
921 // extension to the cache path (5 bytes).
922 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
923 ALOGE("apk_path too long '%s'\n", apk_path);
924 return false;
925 }
926
927 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800928 // Oat dirs for secondary dex files are already validated.
929 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700930 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
931 return false;
932 }
933 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
934 return false;
935 }
936 } else {
937 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
938 return false;
939 }
940 }
941 return true;
942}
943
944// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
945// on destruction. It will also run the given cleanup (unless told not to) after closing.
946//
947// Usage example:
948//
Calin Juravle7a570e82017-01-14 16:23:30 -0800949// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700950// [name]() {
951// unlink(name.c_str());
952// });
953// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
954// wrapper if captured as a reference.
955//
956// if (file.get() == -1) {
957// // Error opening...
958// }
959//
960// ...
961// if (error) {
962// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
963// // and delete the file (after the fd is closed).
964// return -1;
965// }
966//
967// (Success case)
968// file.SetCleanup(false);
969// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
970// // (leaving the file around; after the fd is closed).
971//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700972class Dex2oatFileWrapper {
973 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800974 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700975 }
976
Calin Juravle7a570e82017-01-14 16:23:30 -0800977 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
978 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
979
980 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
981 value_ = other.value_;
982 cleanup_ = other.cleanup_;
983 do_cleanup_ = other.do_cleanup_;
984 auto_close_ = other.auto_close_;
985 other.release();
986 }
987
988 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
989 value_ = other.value_;
990 cleanup_ = other.cleanup_;
991 do_cleanup_ = other.do_cleanup_;
992 auto_close_ = other.auto_close_;
993 other.release();
994 return *this;
995 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700996
997 ~Dex2oatFileWrapper() {
998 reset(-1);
999 }
1000
1001 int get() {
1002 return value_;
1003 }
1004
1005 void SetCleanup(bool cleanup) {
1006 do_cleanup_ = cleanup;
1007 }
1008
1009 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001010 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001011 close(value_);
1012 }
1013 if (do_cleanup_ && cleanup_ != nullptr) {
1014 cleanup_();
1015 }
1016
1017 value_ = new_value;
1018 }
1019
Calin Juravle7a570e82017-01-14 16:23:30 -08001020 void reset(int new_value, std::function<void ()> new_cleanup) {
1021 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001022 close(value_);
1023 }
1024 if (do_cleanup_ && cleanup_ != nullptr) {
1025 cleanup_();
1026 }
1027
1028 value_ = new_value;
1029 cleanup_ = new_cleanup;
1030 }
1031
Calin Juravle7a570e82017-01-14 16:23:30 -08001032 void DisableAutoClose() {
1033 auto_close_ = false;
1034 }
1035
Jeff Sharkey90aff262016-12-12 14:28:24 -07001036 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001037 void release() {
1038 value_ = -1;
1039 do_cleanup_ = false;
1040 cleanup_ = nullptr;
1041 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001042 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001043 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001044 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001045 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001046};
1047
Calin Juravle7a570e82017-01-14 16:23:30 -08001048// (re)Creates the app image if needed.
1049Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001050 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001051 // Use app images only if it is enabled (by a set image format) and we are compiling
1052 // profile-guided (so the app image doesn't conservatively contain all classes).
Calin Juravle2289c0a2017-02-15 12:44:14 -08001053 // Note that we don't create an image for secondary dex files.
1054 if (is_secondary_dex || !profile_guided) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001055 return Dex2oatFileWrapper();
1056 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001057
Calin Juravle7a570e82017-01-14 16:23:30 -08001058 const std::string image_path = create_image_filename(out_oat_path);
1059 if (image_path.empty()) {
1060 // Happens when the out_oat_path has an unknown extension.
1061 return Dex2oatFileWrapper();
1062 }
1063 char app_image_format[kPropertyValueMax];
1064 bool have_app_image_format =
1065 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1066 if (!have_app_image_format) {
1067 return Dex2oatFileWrapper();
1068 }
1069 // Recreate is true since we do not want to modify a mapped image. If the app is
1070 // already running and we modify the image file, it can cause crashes (b/27493510).
1071 Dex2oatFileWrapper wrapper_fd(
1072 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1073 [image_path]() { unlink(image_path.c_str()); });
1074 if (wrapper_fd.get() < 0) {
1075 // Could not create application image file. Go on since we can compile without it.
1076 LOG(ERROR) << "installd could not create '" << image_path
1077 << "' for image file during dexopt";
1078 // If we have a valid image file path but no image fd, explicitly erase the image file.
1079 if (unlink(image_path.c_str()) < 0) {
1080 if (errno != ENOENT) {
1081 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1082 }
1083 }
1084 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001085 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001086 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1087 wrapper_fd.reset(-1);
1088 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001089
Calin Juravle7a570e82017-01-14 16:23:30 -08001090 return wrapper_fd;
1091}
1092
1093// Creates the dexopt swap file if necessary and return its fd.
1094// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001095unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001096 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001097 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001098 }
1099 // Make sure there really is enough space.
1100 char swap_file_name[PKG_PATH_MAX];
1101 strcpy(swap_file_name, out_oat_path);
1102 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001103 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001104 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001105 unique_fd swap_fd(open_output_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001106 swap_file_name, /*recreate*/true, /*permissions*/0600));
1107 if (swap_fd.get() < 0) {
1108 // Could not create swap file. Optimistically go on and hope that we can compile
1109 // without it.
1110 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1111 } else {
1112 // Immediately unlink. We don't really want to hit flash.
1113 if (unlink(swap_file_name) < 0) {
1114 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1115 }
1116 }
1117 return swap_fd;
1118}
1119
1120// Opens the reference profiles if needed.
1121// Note that the reference profile might not exist so it's OK if the fd will be -1.
Calin Juravle114f0812017-03-08 19:05:07 -08001122Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1123 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1124 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 // Public apps should not be compiled with profile information ever. Same goes for the special
1126 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001127 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001128 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001129 }
Calin Juravle114f0812017-03-08 19:05:07 -08001130
1131 // Open reference profile in read only mode as dex2oat does not get write permissions.
1132 const std::string location = is_secondary_dex ? dex_path : pkgname;
1133 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1134 const auto& cleanup = [location, is_secondary_dex]() {
1135 clear_reference_profile(location.c_str(), is_secondary_dex);
1136 };
1137 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001138}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001139
Calin Juravle7a570e82017-01-14 16:23:30 -08001140// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1141// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1142bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001143 const char* instruction_set, bool is_public, bool profile_guided,
1144 int uid, bool is_secondary_dex, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001145 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1146 CHECK(in_vdex_wrapper_fd != nullptr);
1147 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001148 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1149 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001150 char in_odex_path[PKG_PATH_MAX];
1151 int dexopt_action = abs(dexopt_needed);
1152 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001153 std::string in_vdex_path_str;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001154 // Disable passing an input vdex when the compilation is profile-guided. The dexlayout
1155 // optimization in dex2oat is incompatible with it. b/35872504.
1156 if (dexopt_action != DEX2OAT_FROM_SCRATCH && !profile_guided) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1158 const char* path = nullptr;
1159 if (is_odex_location) {
1160 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1161 path = in_odex_path;
1162 } else {
1163 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 }
1166 } else {
1167 path = out_oat_path;
1168 }
1169 in_vdex_path_str = create_vdex_filename(path);
1170 if (in_vdex_path_str.empty()) {
1171 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001172 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001173 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001174 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001175 // When we dex2oat because of boot image change, we are going to update
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001176 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001177 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001178 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001179 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001180 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001181 }
1182
1183 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001185 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001187 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001188
1189 // If we are compiling because the boot image is out of date, we do not
1190 // need to recreate a vdex, and can use the same existing one.
1191 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001193 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001194 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1195 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1196 // wrapper).
1197 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001198 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001199 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001200 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1201 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001202 if (out_vdex_wrapper_fd->get() < 0) {
1203 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1204 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001205 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001206 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001207 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001208 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001209 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1210 return false;
1211 }
1212
1213 // If we got here we successfully opened the vdex files.
1214 return true;
1215}
1216
1217// Opens the output oat file for the given apk.
1218// If successful it stores the output path into out_oat_path and returns true.
1219Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001220 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1221 char* out_oat_path) {
1222 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001223 return Dex2oatFileWrapper();
1224 }
1225 const std::string out_oat_path_str(out_oat_path);
1226 Dex2oatFileWrapper wrapper_fd(
1227 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1228 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1229 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001230 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001231 } else if (!set_permissions_and_ownership(
1232 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1234 wrapper_fd.reset(-1);
1235 }
1236 return wrapper_fd;
1237}
1238
1239// Updates the access times of out_oat_path based on those from apk_path.
1240void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1241 struct stat input_stat;
1242 memset(&input_stat, 0, sizeof(input_stat));
1243 if (stat(apk_path, &input_stat) != 0) {
1244 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1245 return;
1246 }
1247
1248 struct utimbuf ut;
1249 ut.actime = input_stat.st_atime;
1250 ut.modtime = input_stat.st_mtime;
1251 if (utime(out_oat_path, &ut) != 0) {
1252 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1253 }
1254}
1255
Calin Juravle80a21252017-01-17 14:43:25 -08001256// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001257// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1258// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1259// the profile has changed.
1260static void exec_dexoptanalyzer(const std::string& dex_file, const char* instruction_set,
1261 const char* compiler_filter, bool profile_was_updated) {
Calin Juravle80a21252017-01-17 14:43:25 -08001262 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1263 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1264
1265 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1266 ALOGE("Instruction set %s longer than max length of %d",
1267 instruction_set, MAX_INSTRUCTION_SET_LEN);
1268 return;
1269 }
1270
1271 char dex_file_arg[strlen("--dex-file=") + PKG_PATH_MAX];
1272 char isa_arg[strlen("--isa=") + MAX_INSTRUCTION_SET_LEN];
1273 char compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Calin Juravle114f0812017-03-08 19:05:07 -08001274 const char* assume_profile_changed = "--assume-profile-changed";
Calin Juravle80a21252017-01-17 14:43:25 -08001275
Calin Juravle114f0812017-03-08 19:05:07 -08001276 sprintf(dex_file_arg, "--dex-file=%s", dex_file.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001277 sprintf(isa_arg, "--isa=%s", instruction_set);
1278 sprintf(compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1279
1280 // program name, dex file, isa, filter, the final NULL
Calin Juravle114f0812017-03-08 19:05:07 -08001281 const char* argv[5 + (profile_was_updated ? 1 : 0)];
Calin Juravle80a21252017-01-17 14:43:25 -08001282 int i = 0;
1283 argv[i++] = DEXOPTANALYZER_BIN;
1284 argv[i++] = dex_file_arg;
1285 argv[i++] = isa_arg;
1286 argv[i++] = compiler_filter_arg;
Calin Juravle114f0812017-03-08 19:05:07 -08001287 if (profile_was_updated) {
1288 argv[i++] = assume_profile_changed;
1289 }
Calin Juravle80a21252017-01-17 14:43:25 -08001290 argv[i] = NULL;
1291
1292 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1293 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1294}
1295
1296// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001297static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1298 const char* instruction_set, std::string* oat_dir_out) {
1299 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001300 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001301 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001302 return false;
1303 }
Calin Juravle114f0812017-03-08 19:05:07 -08001304 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001305
Calin Juravle80a21252017-01-17 14:43:25 -08001306 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001307 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1308 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001309 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001310 return false;
1311 }
1312
1313 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001314 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001315 oat_dir_out->assign(oat_dir);
1316
1317 // Create oat/isa output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001318 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001319 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001320 return false;
1321 }
1322
1323 return true;
1324}
1325
1326static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1327
1328// Verifies the result of dexoptanalyzer executed for the apk_path.
1329// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1330// Returns false for errors or unexpected result values.
Calin Juravle114f0812017-03-08 19:05:07 -08001331static bool process_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001332 int* dexopt_needed_out) {
1333 // The result values are defined in dexoptanalyzer.
1334 switch (result) {
1335 case 0: // no_dexopt_needed
1336 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1337 case 1: // dex2oat_from_scratch
1338 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1339 case 5: // dex2oat_for_bootimage_odex
1340 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1341 case 6: // dex2oat_for_filter_odex
1342 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1343 case 7: // dex2oat_for_relocation_odex
1344 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1345 case 2: // dex2oat_for_bootimage_oat
1346 case 3: // dex2oat_for_filter_oat
1347 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001348 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1349 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001350 << " : dexoptanalyzer result=" << result;
1351 return false;
1352 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001353 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001354 << " exec_dexoptanalyzer result=" << result;
1355 return false;
1356 }
1357}
1358
Calin Juravlec9eab382017-01-25 01:17:17 -08001359// 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 -08001360// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1361// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001362// When returning true, the output parameters will be:
1363// - is_public_out: whether or not the oat file should not be made public
1364// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1365// - oat_dir_out: the oat dir path where the oat file should be stored
1366// - dex_path_out: the real path of the dex file
Calin Juravle114f0812017-03-08 19:05:07 -08001367static bool process_secondary_dex_dexopt(const char* original_dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001368 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001369 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
1370 std::string* oat_dir_out, std::string* dex_path_out) {
Calin Juravle80a21252017-01-17 14:43:25 -08001371 int storage_flag;
1372
1373 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1374 storage_flag = FLAG_STORAGE_CE;
1375 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1376 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1377 return false;
1378 }
1379 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1380 storage_flag = FLAG_STORAGE_DE;
1381 } else {
1382 LOG(ERROR) << "Secondary dex storage flag must be set";
1383 return false;
1384 }
1385
Calin Juravle114f0812017-03-08 19:05:07 -08001386 {
1387 // As opposed to the primary apk, secondary dex files might contain symlinks.
1388 // Resolve the path before passing it to the validate method to
1389 // make sure the verification is done on the real location.
1390 UniqueCPtr<char> dex_real_path_cstr(realpath(original_dex_path, nullptr));
1391 if (dex_real_path_cstr == nullptr) {
1392 PLOG(ERROR) << "Could not get the real path of the secondary dex file "
1393 << original_dex_path;
1394 return false;
1395 } else {
1396 dex_path_out->assign(dex_real_path_cstr.get());
1397 }
1398 }
1399 const std::string& dex_path = *dex_path_out;
Calin Juravlec9eab382017-01-25 01:17:17 -08001400 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1401 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001402 return false;
1403 }
1404
1405 // Check if the path exist. If not, there's nothing to do.
Calin Juravleebc8a792017-04-04 20:21:05 -07001406 struct stat dex_path_stat;
1407 if (stat(dex_path.c_str(), &dex_path_stat) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001408 if (errno == ENOENT) {
1409 // Secondary dex files might be deleted any time by the app.
1410 // Nothing to do if that's the case
Calin Juravle114f0812017-03-08 19:05:07 -08001411 ALOGV("Secondary dex does not exist %s", dex_path.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001412 return NO_DEXOPT_NEEDED;
1413 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001414 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001415 }
1416 }
1417
Calin Juravleebc8a792017-04-04 20:21:05 -07001418 // Check if we should make the oat file public.
1419 // Note that if the dex file is not public the compiled code cannot be made public.
1420 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) &&
1421 ((dex_path_stat.st_mode & S_IROTH) != 0);
1422
Calin Juravle80a21252017-01-17 14:43:25 -08001423 // Prepare the oat directories.
Calin Juravle114f0812017-03-08 19:05:07 -08001424 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, oat_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001425 return false;
1426 }
1427
Calin Juravle114f0812017-03-08 19:05:07 -08001428 // Analyze profiles.
1429 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1430
Calin Juravle80a21252017-01-17 14:43:25 -08001431 pid_t pid = fork();
1432 if (pid == 0) {
1433 // child -- drop privileges before continuing.
1434 drop_capabilities(uid);
1435 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravle114f0812017-03-08 19:05:07 -08001436 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter, profile_was_updated);
Calin Juravle80a21252017-01-17 14:43:25 -08001437 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1438 }
1439
1440 /* parent */
1441
1442 int result = wait_child(pid);
1443 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001444 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001445 return false;
1446 }
1447 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001448 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001449 // Run dexopt only if needed or forced.
1450 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1451 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1452 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1453 // for oat files from dalvik-cache.
1454 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1455 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1456 }
1457
1458 return success;
1459}
1460
Calin Juravlec9eab382017-01-25 01:17:17 -08001461int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001462 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravlecb556e32017-04-04 20:22:50 -07001463 const char* volume_uuid, const char* shared_libraries, const char* se_info) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001464 CHECK(pkgname != nullptr);
1465 CHECK(pkgname[0] != 0);
1466 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1467 LOG_FATAL("dexopt flags contains unknown fields\n");
1468 }
1469
Calin Juravleebc8a792017-04-04 20:21:05 -07001470 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001471 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1472 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1473 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1474 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001475 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1476
1477 // Check if we're dealing with a secondary dex file and if we need to compile it.
1478 std::string oat_dir_str;
Calin Juravle114f0812017-03-08 19:05:07 -08001479 std::string dex_real_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001480 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001481 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001482 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
1483 &dex_real_path)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001484 oat_dir = oat_dir_str.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001485 dex_path = dex_real_path.c_str();
Calin Juravle80a21252017-01-17 14:43:25 -08001486 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1487 return 0; // Nothing to do, report success.
1488 }
1489 } else {
1490 return -1; // We had an error, logged in the process method.
1491 }
1492 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001493 // Currently these flags are only use for secondary dex files.
1494 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001495 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1496 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1497 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001498
1499 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001500 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001501 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001502 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001503 return -1;
1504 }
1505
1506 // Create the output OAT file.
1507 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001508 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001509 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001510 if (out_oat_fd.get() < 0) {
1511 return -1;
1512 }
1513
1514 // Open vdex files.
1515 Dex2oatFileWrapper in_vdex_fd;
1516 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001517 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public,
1518 profile_guided, uid, is_secondary_dex, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001519 return -1;
1520 }
1521
Calin Juravlecb556e32017-04-04 20:22:50 -07001522 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1523 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1524 // fully inherit their parent context).
1525 // Note that for primary apk the oat files are created before, in a separate installd
1526 // call which also does the restorecon. TODO(calin): unify the paths.
1527 if (is_secondary_dex) {
1528 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1529 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1530 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1531 return -1;
1532 }
1533 }
1534
Jeff Sharkey90aff262016-12-12 14:28:24 -07001535 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001536 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001537
Calin Juravle7a570e82017-01-14 16:23:30 -08001538 // Create the app image file if needed.
1539 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001540 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001541
Calin Juravle7a570e82017-01-14 16:23:30 -08001542 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001543 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1544 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001545
Calin Juravlec9eab382017-01-25 01:17:17 -08001546 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001547
1548 pid_t pid = fork();
1549 if (pid == 0) {
1550 /* child -- drop privileges before continuing */
1551 drop_capabilities(uid);
1552
Richard Uhler76cc0272016-12-08 10:46:35 +00001553 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001554 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1555 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1556 _exit(67);
1557 }
1558
Richard Uhler76cc0272016-12-08 10:46:35 +00001559 // Pass dex2oat the relative path to the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001560 const char *input_file_name = get_location_from_path(dex_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001561 run_dex2oat(input_fd.get(),
1562 out_oat_fd.get(),
1563 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001564 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001565 image_fd.get(),
1566 input_file_name,
1567 out_oat_path,
1568 swap_fd.get(),
1569 instruction_set,
1570 compiler_filter,
1571 vm_safe_mode,
1572 debuggable,
1573 boot_complete,
1574 reference_profile_fd.get(),
1575 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001576 _exit(68); /* only get here on exec failure */
1577 } else {
1578 int res = wait_child(pid);
1579 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001580 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001581 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001582 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001583 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001584 }
1585 }
1586
Calin Juravlec9eab382017-01-25 01:17:17 -08001587 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001588
1589 // We've been successful, don't delete output.
1590 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001591 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001592 image_fd.SetCleanup(false);
1593 reference_profile_fd.SetCleanup(false);
1594
1595 return 0;
1596}
1597
Calin Juravlec9eab382017-01-25 01:17:17 -08001598// Try to remove the given directory. Log an error if the directory exists
1599// and is empty but could not be removed.
1600static bool rmdir_if_empty(const char* dir) {
1601 if (rmdir(dir) == 0) {
1602 return true;
1603 }
1604 if (errno == ENOENT || errno == ENOTEMPTY) {
1605 return true;
1606 }
1607 PLOG(ERROR) << "Failed to remove dir: " << dir;
1608 return false;
1609}
1610
1611// Try to unlink the given file. Log an error if the file exists and could not
1612// be unlinked.
1613static bool unlink_if_exists(const std::string& file) {
1614 if (unlink(file.c_str()) == 0) {
1615 return true;
1616 }
1617 if (errno == ENOENT) {
1618 return true;
1619
1620 }
1621 PLOG(ERROR) << "Could not unlink: " << file;
1622 return false;
1623}
1624
1625// Create the oat file structure for the secondary dex 'dex_path' and assign
1626// the individual path component to the 'out_' parameters.
1627static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1628 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1629 size_t dirIndex = dex_path.rfind('/');
1630 if (dirIndex == std::string::npos) {
1631 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1632 return false;
1633 }
1634 // TODO(calin): we have similar computations in at lest 3 other places
1635 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1636 // use string append.
1637 std::string apk_dir = dex_path.substr(0, dirIndex);
1638 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1639 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1640
1641 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001642 /*is_secondary_dex*/true, out_oat_path)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001643 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1644 return false;
1645 }
1646 return true;
1647}
1648
1649// Reconcile the secondary dex 'dex_path' and its generated oat files.
1650// Return true if all the parameters are valid and the secondary dex file was
1651// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1652// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1653// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1654// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1655// Return false if there were errors during processing. In this case
1656// out_secondary_dex_exists will be set to false.
1657bool reconcile_secondary_dex_file(const std::string& dex_path,
1658 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1659 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1660 /*out*/bool* out_secondary_dex_exists) {
1661 // Set out to false to start with, just in case we have validation errors.
1662 *out_secondary_dex_exists = false;
1663 if (isas.size() == 0) {
1664 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1665 return false;
1666 }
1667
1668 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1669 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1670 uid, storage_flag)) {
1671 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1672 return false;
1673 }
1674
1675 if (access(dex_path.c_str(), F_OK) == 0) {
1676 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1677 *out_secondary_dex_exists = true;
1678 return true;
1679 } else if (errno != ENOENT) {
1680 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1681 return false;
1682 }
1683
1684 // The secondary dex does not exist anymore. Clear any generated files.
1685 char oat_path[PKG_PATH_MAX];
1686 char oat_dir[PKG_PATH_MAX];
1687 char oat_isa_dir[PKG_PATH_MAX];
1688 bool result = true;
1689 for (size_t i = 0; i < isas.size(); i++) {
1690 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1691 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1692 result = false;
1693 continue;
1694 }
1695 result = unlink_if_exists(oat_path) && result;
1696 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1697 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1698
1699 // Try removing the directories as well, they might be empty.
1700 result = rmdir_if_empty(oat_isa_dir) && result;
1701 result = rmdir_if_empty(oat_dir) && result;
1702 }
1703
1704 return result;
1705}
1706
Jeff Sharkey90aff262016-12-12 14:28:24 -07001707// Helper for move_ab, so that we can have common failure-case cleanup.
1708static bool unlink_and_rename(const char* from, const char* to) {
1709 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1710 // return a failure.
1711 struct stat s;
1712 if (stat(to, &s) == 0) {
1713 if (!S_ISREG(s.st_mode)) {
1714 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1715 return false;
1716 }
1717 if (unlink(to) != 0) {
1718 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1719 return false;
1720 }
1721 } else {
1722 // This may be a permission problem. We could investigate the error code, but we'll just
1723 // let the rename failure do the work for us.
1724 }
1725
1726 // Try to rename "to" to "from."
1727 if (rename(from, to) != 0) {
1728 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1729 return false;
1730 }
1731 return true;
1732}
1733
1734// Move/rename a B artifact (from) to an A artifact (to).
1735static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1736 // Check whether B exists.
1737 {
1738 struct stat s;
1739 if (stat(b_path.c_str(), &s) != 0) {
1740 // Silently ignore for now. The service calling this isn't smart enough to understand
1741 // lack of artifacts at the moment.
1742 return false;
1743 }
1744 if (!S_ISREG(s.st_mode)) {
1745 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1746 // Try to unlink, but swallow errors.
1747 unlink(b_path.c_str());
1748 return false;
1749 }
1750 }
1751
1752 // Rename B to A.
1753 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1754 // Delete the b_path so we don't try again (or fail earlier).
1755 if (unlink(b_path.c_str()) != 0) {
1756 PLOG(ERROR) << "Could not unlink " << b_path;
1757 }
1758
1759 return false;
1760 }
1761
1762 return true;
1763}
1764
1765bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1766 // Get the current slot suffix. No suffix, no A/B.
1767 std::string slot_suffix;
1768 {
1769 char buf[kPropertyValueMax];
1770 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1771 return false;
1772 }
1773 slot_suffix = buf;
1774
1775 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1776 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1777 return false;
1778 }
1779 }
1780
1781 // Validate other inputs.
1782 if (validate_apk_path(apk_path) != 0) {
1783 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1784 return false;
1785 }
1786 if (validate_apk_path(oat_dir) != 0) {
1787 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1788 return false;
1789 }
1790
1791 char a_path[PKG_PATH_MAX];
1792 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1793 return false;
1794 }
1795 const std::string a_vdex_path = create_vdex_filename(a_path);
1796 const std::string a_image_path = create_image_filename(a_path);
1797
1798 // B path = A path + slot suffix.
1799 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1800 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1801 const std::string b_image_path = StringPrintf("%s.%s",
1802 a_image_path.c_str(),
1803 slot_suffix.c_str());
1804
1805 bool success = true;
1806 if (move_ab_path(b_path, a_path)) {
1807 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1808 // Note: we can live without an app image. As such, ignore failure to move the image file.
1809 // If we decide to require the app image, or the app image being moved correctly,
1810 // then change accordingly.
1811 constexpr bool kIgnoreAppImageFailure = true;
1812
1813 if (!a_image_path.empty()) {
1814 if (!move_ab_path(b_image_path, a_image_path)) {
1815 unlink(a_image_path.c_str());
1816 if (!kIgnoreAppImageFailure) {
1817 success = false;
1818 }
1819 }
1820 }
1821 } else {
1822 // Cleanup: delete B image, ignore errors.
1823 unlink(b_image_path.c_str());
1824 success = false;
1825 }
1826 } else {
1827 // Cleanup: delete B image, ignore errors.
1828 unlink(b_vdex_path.c_str());
1829 unlink(b_image_path.c_str());
1830 success = false;
1831 }
1832 return success;
1833}
1834
1835bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1836 // Delete the oat/odex file.
1837 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001838 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001839 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001840 return false;
1841 }
1842
1843 // In case of a permission failure report the issue. Otherwise just print a warning.
1844 auto unlink_and_check = [](const char* path) -> bool {
1845 int result = unlink(path);
1846 if (result != 0) {
1847 if (errno == EACCES || errno == EPERM) {
1848 PLOG(ERROR) << "Could not unlink " << path;
1849 return false;
1850 }
1851 PLOG(WARNING) << "Could not unlink " << path;
1852 }
1853 return true;
1854 };
1855
1856 // Delete the oat/odex file.
1857 bool return_value_oat = unlink_and_check(out_path);
1858
1859 // Derive and delete the app image.
1860 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1861
1862 // Report success.
1863 return return_value_oat && return_value_art;
1864}
1865
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001866int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1867 return dexopt(params[0], // apk_path
1868 atoi(params[1]), // uid
1869 params[2], // pkgname
1870 params[3], // instruction_set
1871 atoi(params[4]), // dexopt_needed
1872 params[5], // oat_dir
1873 atoi(params[6]), // dexopt_flags
1874 params[7], // compiler_filter
1875 parse_null(params[8]), // volume_uuid
Calin Juravlecb556e32017-04-04 20:22:50 -07001876 parse_null(params[9]), // shared_libraries
1877 parse_null(params[10])); // se_info
1878 static_assert(DEXOPT_PARAM_COUNT == 11U, "Unexpected dexopt param count");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001879}
1880
1881} // namespace installd
1882} // namespace android