blob: facb189a2d081dfda91c0ca68ea52fbba948b412 [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 Sharkey90aff262016-12-12 14:28:24 -070070static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080071 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070072 if (ufd.get() < 0) {
73 if (errno != ENOENT) {
74 PLOG(WARNING) << "Could not open profile " << profile;
75 return false;
76 } else {
77 // Nothing to clear. That's ok.
78 return true;
79 }
80 }
81
82 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
83 if (errno != EWOULDBLOCK) {
84 PLOG(WARNING) << "Error locking profile " << profile;
85 }
86 // This implies that the app owning this profile is running
87 // (and has acquired the lock).
88 //
89 // If we can't acquire the lock bail out since clearing is useless anyway
90 // (the app will write again to the profile).
91 //
92 // Note:
93 // This does not impact the this is not an issue for the profiling correctness.
94 // In case this is needed because of an app upgrade, profiles will still be
95 // eventually cleared by the app itself due to checksum mismatch.
96 // If this is needed because profman advised, then keeping the data around
97 // until the next run is again not an issue.
98 //
99 // If the app attempts to acquire a lock while we've held one here,
100 // it will simply skip the current write cycle.
101 return false;
102 }
103
104 bool truncated = ftruncate(ufd.get(), 0) == 0;
105 if (!truncated) {
106 PLOG(WARNING) << "Could not truncate " << profile;
107 }
108 if (flock(ufd.get(), LOCK_UN) != 0) {
109 PLOG(WARNING) << "Error unlocking profile " << profile;
110 }
111 return truncated;
112}
113
Calin Juravle114f0812017-03-08 19:05:07 -0800114// Clear the reference profile for the given location.
115// The location is the package name for primary apks or the dex path for secondary dex files.
116static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
117 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700118}
119
Calin Juravle114f0812017-03-08 19:05:07 -0800120// Clear the reference profile for the given location.
121// The location is the package name for primary apks or the dex path for secondary dex files.
122static bool clear_current_profile(const std::string& pkgname, userid_t user,
123 bool is_secondary_dex) {
124 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700125}
126
Calin Juravle114f0812017-03-08 19:05:07 -0800127// Clear the reference profile for the primary apk of the given package.
128bool clear_primary_reference_profile(const std::string& pkgname) {
129 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
130}
131
132// Clear all current profile for the primary apk of the given package.
133bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700134 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800135 // 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 -0700136 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
137 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800138 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700139 }
140 return success;
141}
142
Calin Juravle114f0812017-03-08 19:05:07 -0800143// Clear the current profile for the primary apk of the given package and user.
144bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
145 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
146}
147
Jeff Sharkey90aff262016-12-12 14:28:24 -0700148static int split_count(const char *str)
149{
150 char *ctx;
151 int count = 0;
152 char buf[kPropertyValueMax];
153
154 strncpy(buf, str, sizeof(buf));
155 char *pBuf = buf;
156
157 while(strtok_r(pBuf, " ", &ctx) != NULL) {
158 count++;
159 pBuf = NULL;
160 }
161
162 return count;
163}
164
165static int split(char *buf, const char **argv)
166{
167 char *ctx;
168 int count = 0;
169 char *tok;
170 char *pBuf = buf;
171
172 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
173 argv[count++] = tok;
174 pBuf = NULL;
175 }
176
177 return count;
178}
179
Jeff Sharkey90aff262016-12-12 14:28:24 -0700180static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
181 const char* input_file_name, const char* output_file_name, int swap_fd,
182 const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
183 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
184 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
185
186 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
187 ALOGE("Instruction set %s longer than max length of %d",
188 instruction_set, MAX_INSTRUCTION_SET_LEN);
189 return;
190 }
191
192 char dex2oat_Xms_flag[kPropertyValueMax];
193 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
194
195 char dex2oat_Xmx_flag[kPropertyValueMax];
196 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
197
198 char dex2oat_threads_buf[kPropertyValueMax];
199 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
200 ? "dalvik.vm.dex2oat-threads"
201 : "dalvik.vm.boot-dex2oat-threads",
202 dex2oat_threads_buf,
203 NULL) > 0;
204 char dex2oat_threads_arg[kPropertyValueMax + 2];
205 if (have_dex2oat_threads_flag) {
206 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
207 }
208
209 char dex2oat_isa_features_key[kPropertyKeyMax];
210 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
211 char dex2oat_isa_features[kPropertyValueMax];
212 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
213 dex2oat_isa_features, NULL) > 0;
214
215 char dex2oat_isa_variant_key[kPropertyKeyMax];
216 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
217 char dex2oat_isa_variant[kPropertyValueMax];
218 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
219 dex2oat_isa_variant, NULL) > 0;
220
221 const char *dex2oat_norelocation = "-Xnorelocate";
222 bool have_dex2oat_relocation_skip_flag = false;
223
224 char dex2oat_flags[kPropertyValueMax];
225 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
226 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
227 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
228
229 // If we booting without the real /data, don't spend time compiling.
230 char vold_decrypt[kPropertyValueMax];
231 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
232 bool skip_compilation = (have_vold_decrypt &&
233 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
234 (strcmp(vold_decrypt, "1") == 0)));
235
236 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
237
238 char app_image_format[kPropertyValueMax];
239 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
240 bool have_app_image_format =
241 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
242 if (have_app_image_format) {
243 sprintf(image_format_arg, "--image-format=%s", app_image_format);
244 }
245
246 char dex2oat_large_app_threshold[kPropertyValueMax];
247 bool have_dex2oat_large_app_threshold =
248 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
249 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
250 if (have_dex2oat_large_app_threshold) {
251 sprintf(dex2oat_large_app_threshold_arg,
252 "--very-large-app-threshold=%s",
253 dex2oat_large_app_threshold);
254 }
255
256 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
257
258 static const char* RUNTIME_ARG = "--runtime-arg";
259
260 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
261
George Burgess IV36cebe772017-01-25 11:52:01 -0800262 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
263 // use arraysize instead.
264 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
265 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
266 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
267 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
268 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
269 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
270 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
271 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
272 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
273 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
274 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
275 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700276 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800277 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700278 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800279 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700280
281 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
282 sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
283 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
284 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
285 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
286 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
287 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
288 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
289 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
290 if (swap_fd >= 0) {
291 have_dex2oat_swap_fd = true;
292 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
293 }
294 if (image_fd >= 0) {
295 have_dex2oat_image_fd = true;
296 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
297 }
298
299 if (have_dex2oat_Xms_flag) {
300 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
301 }
302 if (have_dex2oat_Xmx_flag) {
303 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
304 }
305
306 // Compute compiler filter.
307
308 bool have_dex2oat_compiler_filter_flag;
309 if (skip_compilation) {
310 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=verify-none");
311 have_dex2oat_compiler_filter_flag = true;
312 have_dex2oat_relocation_skip_flag = true;
313 } else if (vm_safe_mode) {
314 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=interpret-only");
315 have_dex2oat_compiler_filter_flag = true;
316 } else if (compiler_filter != nullptr &&
317 strlen(compiler_filter) + strlen("--compiler-filter=") <
318 arraysize(dex2oat_compiler_filter_arg)) {
319 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
320 have_dex2oat_compiler_filter_flag = true;
321 } else {
322 char dex2oat_compiler_filter_flag[kPropertyValueMax];
323 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
324 dex2oat_compiler_filter_flag, NULL) > 0;
325 if (have_dex2oat_compiler_filter_flag) {
326 sprintf(dex2oat_compiler_filter_arg,
327 "--compiler-filter=%s",
328 dex2oat_compiler_filter_flag);
329 }
330 }
331
332 // Check whether all apps should be compiled debuggable.
333 if (!debuggable) {
334 char prop_buf[kPropertyValueMax];
335 debuggable =
336 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
337 (prop_buf[0] == '1');
338 }
339 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
340 if (profile_fd != -1) {
341 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
342 }
343
344
345 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
346
347 const char* argv[9 // program name, mandatory arguments and the final NULL
348 + (have_dex2oat_isa_variant ? 1 : 0)
349 + (have_dex2oat_isa_features ? 1 : 0)
350 + (have_dex2oat_Xms_flag ? 2 : 0)
351 + (have_dex2oat_Xmx_flag ? 2 : 0)
352 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
353 + (have_dex2oat_threads_flag ? 1 : 0)
354 + (have_dex2oat_swap_fd ? 1 : 0)
355 + (have_dex2oat_image_fd ? 1 : 0)
356 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
357 + (generate_debug_info ? 1 : 0)
358 + (debuggable ? 1 : 0)
359 + (have_app_image_format ? 1 : 0)
360 + dex2oat_flags_count
361 + (profile_fd == -1 ? 0 : 1)
362 + (shared_libraries != nullptr ? 4 : 0)
363 + (have_dex2oat_large_app_threshold ? 1 : 0)];
364 int i = 0;
365 argv[i++] = DEX2OAT_BIN;
366 argv[i++] = zip_fd_arg;
367 argv[i++] = zip_location_arg;
368 argv[i++] = input_vdex_fd_arg;
369 argv[i++] = output_vdex_fd_arg;
370 argv[i++] = oat_fd_arg;
371 argv[i++] = oat_location_arg;
372 argv[i++] = instruction_set_arg;
373 if (have_dex2oat_isa_variant) {
374 argv[i++] = instruction_set_variant_arg;
375 }
376 if (have_dex2oat_isa_features) {
377 argv[i++] = instruction_set_features_arg;
378 }
379 if (have_dex2oat_Xms_flag) {
380 argv[i++] = RUNTIME_ARG;
381 argv[i++] = dex2oat_Xms_arg;
382 }
383 if (have_dex2oat_Xmx_flag) {
384 argv[i++] = RUNTIME_ARG;
385 argv[i++] = dex2oat_Xmx_arg;
386 }
387 if (have_dex2oat_compiler_filter_flag) {
388 argv[i++] = dex2oat_compiler_filter_arg;
389 }
390 if (have_dex2oat_threads_flag) {
391 argv[i++] = dex2oat_threads_arg;
392 }
393 if (have_dex2oat_swap_fd) {
394 argv[i++] = dex2oat_swap_fd;
395 }
396 if (have_dex2oat_image_fd) {
397 argv[i++] = dex2oat_image_fd;
398 }
399 if (generate_debug_info) {
400 argv[i++] = "--generate-debug-info";
401 }
402 if (debuggable) {
403 argv[i++] = "--debuggable";
404 }
405 if (have_app_image_format) {
406 argv[i++] = image_format_arg;
407 }
408 if (have_dex2oat_large_app_threshold) {
409 argv[i++] = dex2oat_large_app_threshold_arg;
410 }
411 if (dex2oat_flags_count) {
412 i += split(dex2oat_flags, argv + i);
413 }
414 if (have_dex2oat_relocation_skip_flag) {
415 argv[i++] = RUNTIME_ARG;
416 argv[i++] = dex2oat_norelocation;
417 }
418 if (profile_fd != -1) {
419 argv[i++] = profile_arg;
420 }
421 if (shared_libraries != nullptr) {
422 argv[i++] = RUNTIME_ARG;
423 argv[i++] = "-classpath";
424 argv[i++] = RUNTIME_ARG;
425 argv[i++] = shared_libraries;
426 }
427 // Do not add after dex2oat_flags, they should override others for debugging.
428 argv[i] = NULL;
429
430 execv(DEX2OAT_BIN, (char * const *)argv);
431 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
432}
433
434/*
435 * Whether dexopt should use a swap file when compiling an APK.
436 *
437 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
438 * itself, anyways).
439 *
440 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
441 *
442 * Otherwise, return true if this is a low-mem device.
443 *
444 * Otherwise, return default value.
445 */
446static bool kAlwaysProvideSwapFile = false;
447static bool kDefaultProvideSwapFile = true;
448
449static bool ShouldUseSwapFileForDexopt() {
450 if (kAlwaysProvideSwapFile) {
451 return true;
452 }
453
454 // Check the "override" property. If it exists, return value == "true".
455 char dex2oat_prop_buf[kPropertyValueMax];
456 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
457 if (strcmp(dex2oat_prop_buf, "true") == 0) {
458 return true;
459 } else {
460 return false;
461 }
462 }
463
464 // Shortcut for default value. This is an implementation optimization for the process sketched
465 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
466 // as low-mem is never returning false. The compiler will optimize this away if it can.
467 if (kDefaultProvideSwapFile) {
468 return true;
469 }
470
471 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
472 if (is_low_mem) {
473 return true;
474 }
475
476 // Default value must be false here.
477 return kDefaultProvideSwapFile;
478}
479
Richard Uhler76cc0272016-12-08 10:46:35 +0000480static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700481 if (set_to_bg) {
482 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
483 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
484 exit(70);
485 }
486 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
487 ALOGE("setpriority failed: %s\n", strerror(errno));
488 exit(71);
489 }
490 }
491}
492
Calin Juravle114f0812017-03-08 19:05:07 -0800493static bool create_profile(int uid, const std::string& profile) {
494 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), O_CREAT | O_NOFOLLOW, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800495 if (fd.get() < 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800496 if (errno == EEXIST) {
497 return true;
498 } else {
499 PLOG(ERROR) << "Failed to create profile " << profile;
500 return false;
501 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700502 }
Calin Juravle114f0812017-03-08 19:05:07 -0800503 // Profiles should belong to the app; make sure of that by giving ownership to
504 // the app uid. If we cannot do that, there's no point in returning the fd
505 // since dex2oat/profman will fail with SElinux denials.
506 if (fchown(fd.get(), uid, uid) < 0) {
507 PLOG(ERROR) << "Could not chwon profile " << profile;
508 return false;
509 }
510 return true;
511}
512
513static unique_fd open_profile(int uid, const std::string& profile, bool read_write) {
514 // Check if we need to open the profile for a read-write operation. If so, we
515 // might need to create the profile since the file might not be there. Reference
516 // profiles are created on the fly so they might not exist beforehand.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700517 if (read_write) {
Calin Juravle114f0812017-03-08 19:05:07 -0800518 if (!create_profile(uid, profile)) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800519 return invalid_unique_fd();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700520 }
521 }
Calin Juravle114f0812017-03-08 19:05:07 -0800522 int flags = read_write ? O_RDWR : O_RDONLY;
523 // Do not follow symlinks when opening a profile:
524 // - primary profiles should not contain symlinks in their paths
525 // - secondary dex paths should have been already resolved and validated
526 flags |= O_NOFOLLOW;
527
528 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
529 if (fd.get() < 0) {
530 if (errno != ENOENT) {
531 // Profiles might be missing for various reasons. For example, in a
532 // multi-user environment, the profile directory for one user can be created
533 // after we start a merge. In this case the current profile for that user
534 // will not be found.
535 // Also, the secondary dex profiles might be deleted by the app at any time,
536 // so we can't we need to prepare if they are missing.
537 PLOG(ERROR) << "Failed to open profile " << profile;
538 }
539 return invalid_unique_fd();
540 }
541
Jeff Sharkey90aff262016-12-12 14:28:24 -0700542 return fd;
543}
544
Calin Juravle114f0812017-03-08 19:05:07 -0800545static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
546 bool is_secondary_dex) {
547 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
548 return open_profile(uid, profile, /*read_write*/false);
549}
550
551static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
552 bool is_secondary_dex) {
553 std::string profile = create_reference_profile_path(location, is_secondary_dex);
554 return open_profile(uid, profile, read_write);
555}
556
557static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800558 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700559 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800560 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
561 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700562
Calin Juravle114f0812017-03-08 19:05:07 -0800563 // For secondary dex files, we don't really need the user but we use it for sanity checks.
564 // Note: the user owning the dex file should be the current user.
565 std::vector<userid_t> users;
566 if (is_secondary_dex){
567 users.push_back(multiuser_get_user_id(uid));
568 } else {
569 users = get_known_users(/*volume_uuid*/ nullptr);
570 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700571 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800572 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700573 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800574 if (profile_fd.get() >= 0) {
575 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700576 }
577 }
578}
579
580static void drop_capabilities(uid_t uid) {
581 if (setgid(uid) != 0) {
582 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
583 exit(64);
584 }
585 if (setuid(uid) != 0) {
586 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
587 exit(65);
588 }
589 // drop capabilities
590 struct __user_cap_header_struct capheader;
591 struct __user_cap_data_struct capdata[2];
592 memset(&capheader, 0, sizeof(capheader));
593 memset(&capdata, 0, sizeof(capdata));
594 capheader.version = _LINUX_CAPABILITY_VERSION_3;
595 if (capset(&capheader, &capdata[0]) < 0) {
596 ALOGE("capset failed: %s\n", strerror(errno));
597 exit(66);
598 }
599}
600
601static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
602static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
603static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
604static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
605static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
606
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800607static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
608 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700609 static const size_t MAX_INT_LEN = 32;
610 static const char* PROFMAN_BIN = "/system/bin/profman";
611
612 std::vector<std::string> profile_args(profiles_fd.size());
613 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
614 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800615 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700616 profile_args[k].assign(profile_buf);
617 }
618 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800619 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700620
621 // program name, reference profile fd, the final NULL and the profile fds
622 const char* argv[3 + profiles_fd.size()];
623 int i = 0;
624 argv[i++] = PROFMAN_BIN;
625 argv[i++] = reference_profile_arg;
626 for (size_t k = 0; k < profile_args.size(); k++) {
627 argv[i++] = profile_args[k].c_str();
628 }
629 // Do not add after dex2oat_flags, they should override others for debugging.
630 argv[i] = NULL;
631
632 execv(PROFMAN_BIN, (char * const *)argv);
633 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
634 exit(68); /* only get here on exec failure */
635}
636
637// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800638// The location is the package name for primary apks or the dex path for secondary dex files.
639// Returns true if there is enough information in the current profiles that makes it
640// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700641// If the return value is true all the current profiles would have been merged into
642// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800643static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800644 std::vector<unique_fd> profiles_fd;
645 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800646 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800647 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700648 // Skip profile guided compilation because no profiles were found.
649 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700650 return false;
651 }
652
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 pid_t pid = fork();
654 if (pid == 0) {
655 /* child -- drop privileges before continuing */
656 drop_capabilities(uid);
657 run_profman_merge(profiles_fd, reference_profile_fd);
658 exit(68); /* only get here on exec failure */
659 }
660 /* parent */
661 int return_code = wait_child(pid);
662 bool need_to_compile = false;
663 bool should_clear_current_profiles = false;
664 bool should_clear_reference_profile = false;
665 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800666 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700667 } else {
668 return_code = WEXITSTATUS(return_code);
669 switch (return_code) {
670 case PROFMAN_BIN_RETURN_CODE_COMPILE:
671 need_to_compile = true;
672 should_clear_current_profiles = true;
673 should_clear_reference_profile = false;
674 break;
675 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
676 need_to_compile = false;
677 should_clear_current_profiles = false;
678 should_clear_reference_profile = false;
679 break;
680 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800681 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700682 need_to_compile = false;
683 should_clear_current_profiles = true;
684 should_clear_reference_profile = true;
685 break;
686 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
687 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
688 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800689 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 need_to_compile = false;
691 should_clear_current_profiles = false;
692 should_clear_reference_profile = false;
693 break;
694 default:
695 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800696 LOG(WARNING) << "Unknown error code while processing profiles for location "
697 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700698 need_to_compile = false;
699 should_clear_current_profiles = true;
700 should_clear_reference_profile = true;
701 break;
702 }
703 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800704
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800706 if (is_secondary_dex) {
707 // For secondary dex files, the owning user is the current user.
708 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
709 } else {
710 clear_primary_current_profiles(location);
711 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700712 }
713 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800714 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700715 }
716 return need_to_compile;
717}
718
Calin Juravle114f0812017-03-08 19:05:07 -0800719// Decides if profile guided compilation is needed or not based on existing profiles.
720// The analysis is done for the primary apks of the given package.
721// Returns true if there is enough information in the current profiles that makes it
722// worth to recompile the package.
723// If the return value is true all the current profiles would have been merged into
724// the reference profiles accessible with open_reference_profile().
725bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
726 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
727}
728
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800729static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
730 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700731 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800732 const std::vector<unique_fd>& apk_fds,
733 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700734 std::vector<std::string> profman_args;
735 static const char* PROFMAN_BIN = "/system/bin/profman";
736 profman_args.push_back(PROFMAN_BIN);
737 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800738 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700739 if (reference_profile_fd != -1) {
740 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800741 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800743 for (size_t i = 0; i < profile_fds.size(); i++) {
744 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700745 }
746 for (const std::string& dex_location : dex_locations) {
747 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
748 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800749 for (size_t i = 0; i < apk_fds.size(); i++) {
750 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700751 }
752 const char **argv = new const char*[profman_args.size() + 1];
753 size_t i = 0;
754 for (const std::string& profman_arg : profman_args) {
755 argv[i++] = profman_arg.c_str();
756 }
757 argv[i] = NULL;
758
759 execv(PROFMAN_BIN, (char * const *)argv);
760 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
761 exit(68); /* only get here on exec failure */
762}
763
764static const char* get_location_from_path(const char* path) {
765 static constexpr char kLocationSeparator = '/';
766 const char *location = strrchr(path, kLocationSeparator);
767 if (location == NULL) {
768 return path;
769 } else {
770 // Skip the separator character.
771 return location + 1;
772 }
773}
774
Calin Juravle76268c52017-03-09 13:19:42 -0800775bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800776 std::vector<unique_fd> profile_fds;
777 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800778 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779
Calin Juravle114f0812017-03-08 19:05:07 -0800780 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
781 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700782
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800783 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 const bool has_profiles = !profile_fds.empty();
785
786 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800787 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700788 return false;
789 }
790
Calin Juravle114f0812017-03-08 19:05:07 -0800791 unique_fd output_fd(open(out_file_name.c_str(),
792 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700793 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
794 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
795 return false;
796 }
797 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
798 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800799 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800 for (const std::string& code_full_path : code_full_paths) {
801 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800802 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700803 if (apk_fd == -1) {
804 ALOGE("installd cannot open '%s'\n", full_path);
805 return false;
806 }
807 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800808 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700809 }
810
811 pid_t pid = fork();
812 if (pid == 0) {
813 /* child -- drop privileges before continuing */
814 drop_capabilities(uid);
815 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
816 apk_fds, output_fd);
817 exit(68); /* only get here on exec failure */
818 }
819 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700820 int return_code = wait_child(pid);
821 if (!WIFEXITED(return_code)) {
822 LOG(WARNING) << "profman failed for package " << pkgname << ": "
823 << return_code;
824 return false;
825 }
826 return true;
827}
828
829static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
830 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
831 if (EndsWith(oat_path, ".dex")) {
832 std::string new_path = oat_path;
833 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
834 CHECK(EndsWith(new_path, new_ext.c_str()));
835 return new_path;
836 }
837
838 // An odex entry. Not that this may not be an extension, e.g., in the OTA
839 // case (where the base name will have an extension for the B artifact).
840 size_t odex_pos = oat_path.rfind(".odex");
841 if (odex_pos != std::string::npos) {
842 std::string new_path = oat_path;
843 new_path.replace(odex_pos, strlen(".odex"), new_ext);
844 CHECK_NE(new_path.find(new_ext), std::string::npos);
845 return new_path;
846 }
847
848 // Don't know how to handle this.
849 return "";
850}
851
852// Translate the given oat path to an art (app image) path. An empty string
853// denotes an error.
854static std::string create_image_filename(const std::string& oat_path) {
855 return replace_file_extension(oat_path, ".art");
856}
857
858// Translate the given oat path to a vdex path. An empty string denotes an error.
859static std::string create_vdex_filename(const std::string& oat_path) {
860 return replace_file_extension(oat_path, ".vdex");
861}
862
863static bool add_extension_to_file_name(char* file_name, const char* extension) {
864 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
865 return false;
866 }
867 strcat(file_name, extension);
868 return true;
869}
870
871static int open_output_file(const char* file_name, bool recreate, int permissions) {
872 int flags = O_RDWR | O_CREAT;
873 if (recreate) {
874 if (unlink(file_name) < 0) {
875 if (errno != ENOENT) {
876 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
877 }
878 }
879 flags |= O_EXCL;
880 }
881 return open(file_name, flags, permissions);
882}
883
Calin Juravle2289c0a2017-02-15 12:44:14 -0800884static bool set_permissions_and_ownership(
885 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
886 // Primary apks are owned by the system. Secondary dex files are owned by the app.
887 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 if (fchmod(fd,
889 S_IRUSR|S_IWUSR|S_IRGRP |
890 (is_public ? S_IROTH : 0)) < 0) {
891 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
892 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800893 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 ALOGE("installd cannot chown '%s' during dexopt\n", path);
895 return false;
896 }
897 return true;
898}
899
900static bool IsOutputDalvikCache(const char* oat_dir) {
901 // InstallerConnection.java (which invokes installd) transforms Java null arguments
902 // into '!'. Play it safe by handling it both.
903 // TODO: ensure we never get null.
904 // TODO: pass a flag instead of inferring if the output is dalvik cache.
905 return oat_dir == nullptr || oat_dir[0] == '!';
906}
907
908static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800909 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700910 // Early best-effort check whether we can fit the the path into our buffers.
911 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
912 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
913 // extension to the cache path (5 bytes).
914 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
915 ALOGE("apk_path too long '%s'\n", apk_path);
916 return false;
917 }
918
919 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800920 // Oat dirs for secondary dex files are already validated.
921 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700922 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
923 return false;
924 }
925 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
926 return false;
927 }
928 } else {
929 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
930 return false;
931 }
932 }
933 return true;
934}
935
936// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
937// on destruction. It will also run the given cleanup (unless told not to) after closing.
938//
939// Usage example:
940//
Calin Juravle7a570e82017-01-14 16:23:30 -0800941// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700942// [name]() {
943// unlink(name.c_str());
944// });
945// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
946// wrapper if captured as a reference.
947//
948// if (file.get() == -1) {
949// // Error opening...
950// }
951//
952// ...
953// if (error) {
954// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
955// // and delete the file (after the fd is closed).
956// return -1;
957// }
958//
959// (Success case)
960// file.SetCleanup(false);
961// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
962// // (leaving the file around; after the fd is closed).
963//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964class Dex2oatFileWrapper {
965 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800966 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967 }
968
Calin Juravle7a570e82017-01-14 16:23:30 -0800969 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
970 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
971
972 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
973 value_ = other.value_;
974 cleanup_ = other.cleanup_;
975 do_cleanup_ = other.do_cleanup_;
976 auto_close_ = other.auto_close_;
977 other.release();
978 }
979
980 Dex2oatFileWrapper& operator=(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 return *this;
987 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988
989 ~Dex2oatFileWrapper() {
990 reset(-1);
991 }
992
993 int get() {
994 return value_;
995 }
996
997 void SetCleanup(bool cleanup) {
998 do_cleanup_ = cleanup;
999 }
1000
1001 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001002 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001003 close(value_);
1004 }
1005 if (do_cleanup_ && cleanup_ != nullptr) {
1006 cleanup_();
1007 }
1008
1009 value_ = new_value;
1010 }
1011
Calin Juravle7a570e82017-01-14 16:23:30 -08001012 void reset(int new_value, std::function<void ()> new_cleanup) {
1013 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001014 close(value_);
1015 }
1016 if (do_cleanup_ && cleanup_ != nullptr) {
1017 cleanup_();
1018 }
1019
1020 value_ = new_value;
1021 cleanup_ = new_cleanup;
1022 }
1023
Calin Juravle7a570e82017-01-14 16:23:30 -08001024 void DisableAutoClose() {
1025 auto_close_ = false;
1026 }
1027
Jeff Sharkey90aff262016-12-12 14:28:24 -07001028 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001029 void release() {
1030 value_ = -1;
1031 do_cleanup_ = false;
1032 cleanup_ = nullptr;
1033 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001034 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001035 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001036 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001037 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001038};
1039
Calin Juravle7a570e82017-01-14 16:23:30 -08001040// (re)Creates the app image if needed.
1041Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001042 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001043 // Use app images only if it is enabled (by a set image format) and we are compiling
1044 // profile-guided (so the app image doesn't conservatively contain all classes).
Calin Juravle2289c0a2017-02-15 12:44:14 -08001045 // Note that we don't create an image for secondary dex files.
1046 if (is_secondary_dex || !profile_guided) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001047 return Dex2oatFileWrapper();
1048 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001049
Calin Juravle7a570e82017-01-14 16:23:30 -08001050 const std::string image_path = create_image_filename(out_oat_path);
1051 if (image_path.empty()) {
1052 // Happens when the out_oat_path has an unknown extension.
1053 return Dex2oatFileWrapper();
1054 }
1055 char app_image_format[kPropertyValueMax];
1056 bool have_app_image_format =
1057 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1058 if (!have_app_image_format) {
1059 return Dex2oatFileWrapper();
1060 }
1061 // Recreate is true since we do not want to modify a mapped image. If the app is
1062 // already running and we modify the image file, it can cause crashes (b/27493510).
1063 Dex2oatFileWrapper wrapper_fd(
1064 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1065 [image_path]() { unlink(image_path.c_str()); });
1066 if (wrapper_fd.get() < 0) {
1067 // Could not create application image file. Go on since we can compile without it.
1068 LOG(ERROR) << "installd could not create '" << image_path
1069 << "' for image file during dexopt";
1070 // If we have a valid image file path but no image fd, explicitly erase the image file.
1071 if (unlink(image_path.c_str()) < 0) {
1072 if (errno != ENOENT) {
1073 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1074 }
1075 }
1076 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001077 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001078 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1079 wrapper_fd.reset(-1);
1080 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001081
Calin Juravle7a570e82017-01-14 16:23:30 -08001082 return wrapper_fd;
1083}
1084
1085// Creates the dexopt swap file if necessary and return its fd.
1086// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001087unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001088 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001089 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001090 }
1091 // Make sure there really is enough space.
1092 char swap_file_name[PKG_PATH_MAX];
1093 strcpy(swap_file_name, out_oat_path);
1094 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001095 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001096 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001097 unique_fd swap_fd(open_output_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001098 swap_file_name, /*recreate*/true, /*permissions*/0600));
1099 if (swap_fd.get() < 0) {
1100 // Could not create swap file. Optimistically go on and hope that we can compile
1101 // without it.
1102 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1103 } else {
1104 // Immediately unlink. We don't really want to hit flash.
1105 if (unlink(swap_file_name) < 0) {
1106 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1107 }
1108 }
1109 return swap_fd;
1110}
1111
1112// Opens the reference profiles if needed.
1113// 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 -08001114Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1115 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1116 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001117 // Public apps should not be compiled with profile information ever. Same goes for the special
1118 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001119 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001120 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 }
Calin Juravle114f0812017-03-08 19:05:07 -08001122
1123 // Open reference profile in read only mode as dex2oat does not get write permissions.
1124 const std::string location = is_secondary_dex ? dex_path : pkgname;
1125 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1126 const auto& cleanup = [location, is_secondary_dex]() {
1127 clear_reference_profile(location.c_str(), is_secondary_dex);
1128 };
1129 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001130}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131
Calin Juravle7a570e82017-01-14 16:23:30 -08001132// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1133// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1134bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001135 const char* instruction_set, bool is_public, bool profile_guided,
1136 int uid, bool is_secondary_dex, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001137 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1138 CHECK(in_vdex_wrapper_fd != nullptr);
1139 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001140 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1141 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001142 char in_odex_path[PKG_PATH_MAX];
1143 int dexopt_action = abs(dexopt_needed);
1144 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001145 std::string in_vdex_path_str;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001146 // Disable passing an input vdex when the compilation is profile-guided. The dexlayout
1147 // optimization in dex2oat is incompatible with it. b/35872504.
1148 if (dexopt_action != DEX2OAT_FROM_SCRATCH && !profile_guided) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001149 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1150 const char* path = nullptr;
1151 if (is_odex_location) {
1152 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1153 path = in_odex_path;
1154 } else {
1155 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001157 }
1158 } else {
1159 path = out_oat_path;
1160 }
1161 in_vdex_path_str = create_vdex_filename(path);
1162 if (in_vdex_path_str.empty()) {
1163 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001166 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001167 // When we dex2oat because of boot image change, we are going to update
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001168 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001169 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001170 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001171 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001172 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001173 }
1174
1175 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001176 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001177 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001179 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001180
1181 // If we are compiling because the boot image is out of date, we do not
1182 // need to recreate a vdex, and can use the same existing one.
1183 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001185 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1187 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1188 // wrapper).
1189 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001190 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001191 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001192 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1193 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001194 if (out_vdex_wrapper_fd->get() < 0) {
1195 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1196 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001197 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001198 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001199 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001200 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1202 return false;
1203 }
1204
1205 // If we got here we successfully opened the vdex files.
1206 return true;
1207}
1208
1209// Opens the output oat file for the given apk.
1210// If successful it stores the output path into out_oat_path and returns true.
1211Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001212 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1213 char* out_oat_path) {
1214 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001215 return Dex2oatFileWrapper();
1216 }
1217 const std::string out_oat_path_str(out_oat_path);
1218 Dex2oatFileWrapper wrapper_fd(
1219 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1220 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1221 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001222 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001223 } else if (!set_permissions_and_ownership(
1224 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1226 wrapper_fd.reset(-1);
1227 }
1228 return wrapper_fd;
1229}
1230
1231// Updates the access times of out_oat_path based on those from apk_path.
1232void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1233 struct stat input_stat;
1234 memset(&input_stat, 0, sizeof(input_stat));
1235 if (stat(apk_path, &input_stat) != 0) {
1236 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1237 return;
1238 }
1239
1240 struct utimbuf ut;
1241 ut.actime = input_stat.st_atime;
1242 ut.modtime = input_stat.st_mtime;
1243 if (utime(out_oat_path, &ut) != 0) {
1244 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1245 }
1246}
1247
Calin Juravle80a21252017-01-17 14:43:25 -08001248// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001249// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1250// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1251// the profile has changed.
1252static void exec_dexoptanalyzer(const std::string& dex_file, const char* instruction_set,
1253 const char* compiler_filter, bool profile_was_updated) {
Calin Juravle80a21252017-01-17 14:43:25 -08001254 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1255 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1256
1257 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1258 ALOGE("Instruction set %s longer than max length of %d",
1259 instruction_set, MAX_INSTRUCTION_SET_LEN);
1260 return;
1261 }
1262
1263 char dex_file_arg[strlen("--dex-file=") + PKG_PATH_MAX];
1264 char isa_arg[strlen("--isa=") + MAX_INSTRUCTION_SET_LEN];
1265 char compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Calin Juravle114f0812017-03-08 19:05:07 -08001266 const char* assume_profile_changed = "--assume-profile-changed";
Calin Juravle80a21252017-01-17 14:43:25 -08001267
Calin Juravle114f0812017-03-08 19:05:07 -08001268 sprintf(dex_file_arg, "--dex-file=%s", dex_file.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001269 sprintf(isa_arg, "--isa=%s", instruction_set);
1270 sprintf(compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1271
1272 // program name, dex file, isa, filter, the final NULL
Calin Juravle114f0812017-03-08 19:05:07 -08001273 const char* argv[5 + (profile_was_updated ? 1 : 0)];
Calin Juravle80a21252017-01-17 14:43:25 -08001274 int i = 0;
1275 argv[i++] = DEXOPTANALYZER_BIN;
1276 argv[i++] = dex_file_arg;
1277 argv[i++] = isa_arg;
1278 argv[i++] = compiler_filter_arg;
Calin Juravle114f0812017-03-08 19:05:07 -08001279 if (profile_was_updated) {
1280 argv[i++] = assume_profile_changed;
1281 }
Calin Juravle80a21252017-01-17 14:43:25 -08001282 argv[i] = NULL;
1283
1284 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1285 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1286}
1287
1288// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001289static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1290 const char* instruction_set, std::string* oat_dir_out) {
1291 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001292 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001293 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001294 return false;
1295 }
Calin Juravle114f0812017-03-08 19:05:07 -08001296 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001297
Calin Juravle80a21252017-01-17 14:43:25 -08001298 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001299 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1300 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001301 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001302 return false;
1303 }
1304
1305 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001306 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001307 oat_dir_out->assign(oat_dir);
1308
1309 // Create oat/isa output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001310 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001311 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001312 return false;
1313 }
1314
1315 return true;
1316}
1317
1318static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1319
1320// Verifies the result of dexoptanalyzer executed for the apk_path.
1321// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1322// Returns false for errors or unexpected result values.
Calin Juravle114f0812017-03-08 19:05:07 -08001323static bool process_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001324 int* dexopt_needed_out) {
1325 // The result values are defined in dexoptanalyzer.
1326 switch (result) {
1327 case 0: // no_dexopt_needed
1328 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1329 case 1: // dex2oat_from_scratch
1330 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1331 case 5: // dex2oat_for_bootimage_odex
1332 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1333 case 6: // dex2oat_for_filter_odex
1334 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1335 case 7: // dex2oat_for_relocation_odex
1336 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1337 case 2: // dex2oat_for_bootimage_oat
1338 case 3: // dex2oat_for_filter_oat
1339 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001340 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1341 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001342 << " : dexoptanalyzer result=" << result;
1343 return false;
1344 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001345 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001346 << " exec_dexoptanalyzer result=" << result;
1347 return false;
1348 }
1349}
1350
Calin Juravlec9eab382017-01-25 01:17:17 -08001351// 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 -08001352// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1353// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001354// When returning true, the output parameters will be:
1355// - is_public_out: whether or not the oat file should not be made public
1356// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1357// - oat_dir_out: the oat dir path where the oat file should be stored
1358// - dex_path_out: the real path of the dex file
Calin Juravle114f0812017-03-08 19:05:07 -08001359static bool process_secondary_dex_dexopt(const char* original_dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001360 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001361 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
1362 std::string* oat_dir_out, std::string* dex_path_out) {
Calin Juravle80a21252017-01-17 14:43:25 -08001363 int storage_flag;
1364
1365 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1366 storage_flag = FLAG_STORAGE_CE;
1367 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1368 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1369 return false;
1370 }
1371 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1372 storage_flag = FLAG_STORAGE_DE;
1373 } else {
1374 LOG(ERROR) << "Secondary dex storage flag must be set";
1375 return false;
1376 }
1377
Calin Juravle114f0812017-03-08 19:05:07 -08001378 {
1379 // As opposed to the primary apk, secondary dex files might contain symlinks.
1380 // Resolve the path before passing it to the validate method to
1381 // make sure the verification is done on the real location.
1382 UniqueCPtr<char> dex_real_path_cstr(realpath(original_dex_path, nullptr));
1383 if (dex_real_path_cstr == nullptr) {
1384 PLOG(ERROR) << "Could not get the real path of the secondary dex file "
1385 << original_dex_path;
1386 return false;
1387 } else {
1388 dex_path_out->assign(dex_real_path_cstr.get());
1389 }
1390 }
1391 const std::string& dex_path = *dex_path_out;
Calin Juravlec9eab382017-01-25 01:17:17 -08001392 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1393 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001394 return false;
1395 }
1396
1397 // Check if the path exist. If not, there's nothing to do.
Calin Juravleebc8a792017-04-04 20:21:05 -07001398 struct stat dex_path_stat;
1399 if (stat(dex_path.c_str(), &dex_path_stat) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001400 if (errno == ENOENT) {
1401 // Secondary dex files might be deleted any time by the app.
1402 // Nothing to do if that's the case
Calin Juravle114f0812017-03-08 19:05:07 -08001403 ALOGV("Secondary dex does not exist %s", dex_path.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001404 return NO_DEXOPT_NEEDED;
1405 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001406 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001407 }
1408 }
1409
Calin Juravleebc8a792017-04-04 20:21:05 -07001410 // Check if we should make the oat file public.
1411 // Note that if the dex file is not public the compiled code cannot be made public.
1412 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) &&
1413 ((dex_path_stat.st_mode & S_IROTH) != 0);
1414
Calin Juravle80a21252017-01-17 14:43:25 -08001415 // Prepare the oat directories.
Calin Juravle114f0812017-03-08 19:05:07 -08001416 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, oat_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001417 return false;
1418 }
1419
Calin Juravle114f0812017-03-08 19:05:07 -08001420 // Analyze profiles.
1421 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1422
Calin Juravle80a21252017-01-17 14:43:25 -08001423 pid_t pid = fork();
1424 if (pid == 0) {
1425 // child -- drop privileges before continuing.
1426 drop_capabilities(uid);
1427 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravle114f0812017-03-08 19:05:07 -08001428 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter, profile_was_updated);
Calin Juravle80a21252017-01-17 14:43:25 -08001429 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1430 }
1431
1432 /* parent */
1433
1434 int result = wait_child(pid);
1435 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001436 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001437 return false;
1438 }
1439 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001440 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001441 // Run dexopt only if needed or forced.
1442 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1443 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1444 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1445 // for oat files from dalvik-cache.
1446 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1447 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1448 }
1449
1450 return success;
1451}
1452
Calin Juravlec9eab382017-01-25 01:17:17 -08001453int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001454 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravlecb556e32017-04-04 20:22:50 -07001455 const char* volume_uuid, const char* shared_libraries, const char* se_info) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001456 CHECK(pkgname != nullptr);
1457 CHECK(pkgname[0] != 0);
1458 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1459 LOG_FATAL("dexopt flags contains unknown fields\n");
1460 }
1461
Calin Juravleebc8a792017-04-04 20:21:05 -07001462 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001463 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1464 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1465 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1466 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001467 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1468
1469 // Check if we're dealing with a secondary dex file and if we need to compile it.
1470 std::string oat_dir_str;
Calin Juravle114f0812017-03-08 19:05:07 -08001471 std::string dex_real_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001472 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001473 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001474 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
1475 &dex_real_path)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001476 oat_dir = oat_dir_str.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001477 dex_path = dex_real_path.c_str();
Calin Juravle80a21252017-01-17 14:43:25 -08001478 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1479 return 0; // Nothing to do, report success.
1480 }
1481 } else {
1482 return -1; // We had an error, logged in the process method.
1483 }
1484 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001485 // Currently these flags are only use for secondary dex files.
1486 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001487 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1488 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1489 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001490
1491 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001492 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001493 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001494 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001495 return -1;
1496 }
1497
1498 // Create the output OAT file.
1499 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001500 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001501 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001502 if (out_oat_fd.get() < 0) {
1503 return -1;
1504 }
1505
1506 // Open vdex files.
1507 Dex2oatFileWrapper in_vdex_fd;
1508 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001509 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public,
1510 profile_guided, uid, is_secondary_dex, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001511 return -1;
1512 }
1513
Calin Juravlecb556e32017-04-04 20:22:50 -07001514 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1515 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1516 // fully inherit their parent context).
1517 // Note that for primary apk the oat files are created before, in a separate installd
1518 // call which also does the restorecon. TODO(calin): unify the paths.
1519 if (is_secondary_dex) {
1520 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1521 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1522 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1523 return -1;
1524 }
1525 }
1526
Jeff Sharkey90aff262016-12-12 14:28:24 -07001527 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001528 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001529
Calin Juravle7a570e82017-01-14 16:23:30 -08001530 // Create the app image file if needed.
1531 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001532 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001533
Calin Juravle7a570e82017-01-14 16:23:30 -08001534 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001535 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1536 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001537
Calin Juravlec9eab382017-01-25 01:17:17 -08001538 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001539
1540 pid_t pid = fork();
1541 if (pid == 0) {
1542 /* child -- drop privileges before continuing */
1543 drop_capabilities(uid);
1544
Richard Uhler76cc0272016-12-08 10:46:35 +00001545 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001546 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1547 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1548 _exit(67);
1549 }
1550
Richard Uhler76cc0272016-12-08 10:46:35 +00001551 // Pass dex2oat the relative path to the input file.
Calin Juravlec9eab382017-01-25 01:17:17 -08001552 const char *input_file_name = get_location_from_path(dex_path);
Richard Uhler76cc0272016-12-08 10:46:35 +00001553 run_dex2oat(input_fd.get(),
1554 out_oat_fd.get(),
1555 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001556 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001557 image_fd.get(),
1558 input_file_name,
1559 out_oat_path,
1560 swap_fd.get(),
1561 instruction_set,
1562 compiler_filter,
1563 vm_safe_mode,
1564 debuggable,
1565 boot_complete,
1566 reference_profile_fd.get(),
1567 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001568 _exit(68); /* only get here on exec failure */
1569 } else {
1570 int res = wait_child(pid);
1571 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001572 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001573 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001574 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001575 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001576 }
1577 }
1578
Calin Juravlec9eab382017-01-25 01:17:17 -08001579 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001580
1581 // We've been successful, don't delete output.
1582 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001583 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001584 image_fd.SetCleanup(false);
1585 reference_profile_fd.SetCleanup(false);
1586
1587 return 0;
1588}
1589
Calin Juravlec9eab382017-01-25 01:17:17 -08001590// Try to remove the given directory. Log an error if the directory exists
1591// and is empty but could not be removed.
1592static bool rmdir_if_empty(const char* dir) {
1593 if (rmdir(dir) == 0) {
1594 return true;
1595 }
1596 if (errno == ENOENT || errno == ENOTEMPTY) {
1597 return true;
1598 }
1599 PLOG(ERROR) << "Failed to remove dir: " << dir;
1600 return false;
1601}
1602
1603// Try to unlink the given file. Log an error if the file exists and could not
1604// be unlinked.
1605static bool unlink_if_exists(const std::string& file) {
1606 if (unlink(file.c_str()) == 0) {
1607 return true;
1608 }
1609 if (errno == ENOENT) {
1610 return true;
1611
1612 }
1613 PLOG(ERROR) << "Could not unlink: " << file;
1614 return false;
1615}
1616
1617// Create the oat file structure for the secondary dex 'dex_path' and assign
1618// the individual path component to the 'out_' parameters.
1619static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1620 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1621 size_t dirIndex = dex_path.rfind('/');
1622 if (dirIndex == std::string::npos) {
1623 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1624 return false;
1625 }
1626 // TODO(calin): we have similar computations in at lest 3 other places
1627 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1628 // use string append.
1629 std::string apk_dir = dex_path.substr(0, dirIndex);
1630 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1631 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1632
1633 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001634 /*is_secondary_dex*/true, out_oat_path)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001635 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1636 return false;
1637 }
1638 return true;
1639}
1640
1641// Reconcile the secondary dex 'dex_path' and its generated oat files.
1642// Return true if all the parameters are valid and the secondary dex file was
1643// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1644// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1645// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1646// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1647// Return false if there were errors during processing. In this case
1648// out_secondary_dex_exists will be set to false.
1649bool reconcile_secondary_dex_file(const std::string& dex_path,
1650 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1651 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1652 /*out*/bool* out_secondary_dex_exists) {
1653 // Set out to false to start with, just in case we have validation errors.
1654 *out_secondary_dex_exists = false;
1655 if (isas.size() == 0) {
1656 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1657 return false;
1658 }
1659
1660 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1661 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1662 uid, storage_flag)) {
1663 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1664 return false;
1665 }
1666
1667 if (access(dex_path.c_str(), F_OK) == 0) {
1668 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1669 *out_secondary_dex_exists = true;
1670 return true;
1671 } else if (errno != ENOENT) {
1672 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1673 return false;
1674 }
1675
1676 // The secondary dex does not exist anymore. Clear any generated files.
1677 char oat_path[PKG_PATH_MAX];
1678 char oat_dir[PKG_PATH_MAX];
1679 char oat_isa_dir[PKG_PATH_MAX];
1680 bool result = true;
1681 for (size_t i = 0; i < isas.size(); i++) {
1682 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1683 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1684 result = false;
1685 continue;
1686 }
1687 result = unlink_if_exists(oat_path) && result;
1688 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1689 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1690
1691 // Try removing the directories as well, they might be empty.
1692 result = rmdir_if_empty(oat_isa_dir) && result;
1693 result = rmdir_if_empty(oat_dir) && result;
1694 }
1695
1696 return result;
1697}
1698
Jeff Sharkey90aff262016-12-12 14:28:24 -07001699// Helper for move_ab, so that we can have common failure-case cleanup.
1700static bool unlink_and_rename(const char* from, const char* to) {
1701 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1702 // return a failure.
1703 struct stat s;
1704 if (stat(to, &s) == 0) {
1705 if (!S_ISREG(s.st_mode)) {
1706 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1707 return false;
1708 }
1709 if (unlink(to) != 0) {
1710 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1711 return false;
1712 }
1713 } else {
1714 // This may be a permission problem. We could investigate the error code, but we'll just
1715 // let the rename failure do the work for us.
1716 }
1717
1718 // Try to rename "to" to "from."
1719 if (rename(from, to) != 0) {
1720 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1721 return false;
1722 }
1723 return true;
1724}
1725
1726// Move/rename a B artifact (from) to an A artifact (to).
1727static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1728 // Check whether B exists.
1729 {
1730 struct stat s;
1731 if (stat(b_path.c_str(), &s) != 0) {
1732 // Silently ignore for now. The service calling this isn't smart enough to understand
1733 // lack of artifacts at the moment.
1734 return false;
1735 }
1736 if (!S_ISREG(s.st_mode)) {
1737 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1738 // Try to unlink, but swallow errors.
1739 unlink(b_path.c_str());
1740 return false;
1741 }
1742 }
1743
1744 // Rename B to A.
1745 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1746 // Delete the b_path so we don't try again (or fail earlier).
1747 if (unlink(b_path.c_str()) != 0) {
1748 PLOG(ERROR) << "Could not unlink " << b_path;
1749 }
1750
1751 return false;
1752 }
1753
1754 return true;
1755}
1756
1757bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1758 // Get the current slot suffix. No suffix, no A/B.
1759 std::string slot_suffix;
1760 {
1761 char buf[kPropertyValueMax];
1762 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1763 return false;
1764 }
1765 slot_suffix = buf;
1766
1767 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1768 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1769 return false;
1770 }
1771 }
1772
1773 // Validate other inputs.
1774 if (validate_apk_path(apk_path) != 0) {
1775 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1776 return false;
1777 }
1778 if (validate_apk_path(oat_dir) != 0) {
1779 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1780 return false;
1781 }
1782
1783 char a_path[PKG_PATH_MAX];
1784 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1785 return false;
1786 }
1787 const std::string a_vdex_path = create_vdex_filename(a_path);
1788 const std::string a_image_path = create_image_filename(a_path);
1789
1790 // B path = A path + slot suffix.
1791 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1792 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1793 const std::string b_image_path = StringPrintf("%s.%s",
1794 a_image_path.c_str(),
1795 slot_suffix.c_str());
1796
1797 bool success = true;
1798 if (move_ab_path(b_path, a_path)) {
1799 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1800 // Note: we can live without an app image. As such, ignore failure to move the image file.
1801 // If we decide to require the app image, or the app image being moved correctly,
1802 // then change accordingly.
1803 constexpr bool kIgnoreAppImageFailure = true;
1804
1805 if (!a_image_path.empty()) {
1806 if (!move_ab_path(b_image_path, a_image_path)) {
1807 unlink(a_image_path.c_str());
1808 if (!kIgnoreAppImageFailure) {
1809 success = false;
1810 }
1811 }
1812 }
1813 } else {
1814 // Cleanup: delete B image, ignore errors.
1815 unlink(b_image_path.c_str());
1816 success = false;
1817 }
1818 } else {
1819 // Cleanup: delete B image, ignore errors.
1820 unlink(b_vdex_path.c_str());
1821 unlink(b_image_path.c_str());
1822 success = false;
1823 }
1824 return success;
1825}
1826
1827bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1828 // Delete the oat/odex file.
1829 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001830 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001831 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001832 return false;
1833 }
1834
1835 // In case of a permission failure report the issue. Otherwise just print a warning.
1836 auto unlink_and_check = [](const char* path) -> bool {
1837 int result = unlink(path);
1838 if (result != 0) {
1839 if (errno == EACCES || errno == EPERM) {
1840 PLOG(ERROR) << "Could not unlink " << path;
1841 return false;
1842 }
1843 PLOG(WARNING) << "Could not unlink " << path;
1844 }
1845 return true;
1846 };
1847
1848 // Delete the oat/odex file.
1849 bool return_value_oat = unlink_and_check(out_path);
1850
1851 // Derive and delete the app image.
1852 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1853
1854 // Report success.
1855 return return_value_oat && return_value_art;
1856}
1857
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001858} // namespace installd
1859} // namespace android