blob: 84ef675d809979e170b0966505a38d280f65acdc [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mark Salyzyna5e161b2016-09-29 08:08:05 -070016#define LOG_TAG "installed"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Jeff Sharkey90aff262016-12-12 14:28:24 -070018#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070019#include <stdlib.h>
20#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070021#include <sys/capability.h>
22#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070023#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070024#include <sys/time.h>
25#include <sys/types.h>
26#include <sys/resource.h>
27#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070028#include <unistd.h>
29
30#include <android-base/logging.h>
31#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070032#include <android-base/strings.h>
33#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080034#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070035#include <cutils/properties.h>
36#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070037#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkey90aff262016-12-12 14:28:24 -070038#include <private/android_filesystem_config.h>
39#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070040
41#include "dexopt.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070042#include "installd_deps.h"
43#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070044#include "utils.h"
45
46using android::base::StringPrintf;
Jeff Sharkey90aff262016-12-12 14:28:24 -070047using android::base::EndsWith;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080048using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070049
50namespace android {
51namespace installd {
52
Calin Juravle114f0812017-03-08 19:05:07 -080053// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
54struct FreeDelete {
55 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
56 void operator()(const void* ptr) const {
57 free(const_cast<void*>(ptr));
58 }
59};
60
61// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
62template <typename T>
63using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
64
Calin Juravle1a0af3b2017-03-09 14:33:33 -080065static unique_fd invalid_unique_fd() {
66 return unique_fd(-1);
67}
68
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070069static const char* parse_null(const char* arg) {
70 if (strcmp(arg, "!") == 0) {
71 return nullptr;
72 } else {
73 return arg;
74 }
75}
76
Jeff Sharkey90aff262016-12-12 14:28:24 -070077static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080078 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070079 if (ufd.get() < 0) {
80 if (errno != ENOENT) {
81 PLOG(WARNING) << "Could not open profile " << profile;
82 return false;
83 } else {
84 // Nothing to clear. That's ok.
85 return true;
86 }
87 }
88
89 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
90 if (errno != EWOULDBLOCK) {
91 PLOG(WARNING) << "Error locking profile " << profile;
92 }
93 // This implies that the app owning this profile is running
94 // (and has acquired the lock).
95 //
96 // If we can't acquire the lock bail out since clearing is useless anyway
97 // (the app will write again to the profile).
98 //
99 // Note:
100 // This does not impact the this is not an issue for the profiling correctness.
101 // In case this is needed because of an app upgrade, profiles will still be
102 // eventually cleared by the app itself due to checksum mismatch.
103 // If this is needed because profman advised, then keeping the data around
104 // until the next run is again not an issue.
105 //
106 // If the app attempts to acquire a lock while we've held one here,
107 // it will simply skip the current write cycle.
108 return false;
109 }
110
111 bool truncated = ftruncate(ufd.get(), 0) == 0;
112 if (!truncated) {
113 PLOG(WARNING) << "Could not truncate " << profile;
114 }
115 if (flock(ufd.get(), LOCK_UN) != 0) {
116 PLOG(WARNING) << "Error unlocking profile " << profile;
117 }
118 return truncated;
119}
120
Calin Juravle114f0812017-03-08 19:05:07 -0800121// Clear the reference profile for the given location.
122// The location is the package name for primary apks or the dex path for secondary dex files.
123static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
124 return clear_profile(create_reference_profile_path(location, 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 given location.
128// The location is the package name for primary apks or the dex path for secondary dex files.
129static bool clear_current_profile(const std::string& pkgname, userid_t user,
130 bool is_secondary_dex) {
131 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700132}
133
Calin Juravle114f0812017-03-08 19:05:07 -0800134// Clear the reference profile for the primary apk of the given package.
135bool clear_primary_reference_profile(const std::string& pkgname) {
136 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
137}
138
139// Clear all current profile for the primary apk of the given package.
140bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700141 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800142 // 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 -0700143 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
144 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800145 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700146 }
147 return success;
148}
149
Calin Juravle114f0812017-03-08 19:05:07 -0800150// Clear the current profile for the primary apk of the given package and user.
151bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
152 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
153}
154
Jeff Sharkey90aff262016-12-12 14:28:24 -0700155static int split_count(const char *str)
156{
157 char *ctx;
158 int count = 0;
159 char buf[kPropertyValueMax];
160
161 strncpy(buf, str, sizeof(buf));
162 char *pBuf = buf;
163
164 while(strtok_r(pBuf, " ", &ctx) != NULL) {
165 count++;
166 pBuf = NULL;
167 }
168
169 return count;
170}
171
172static int split(char *buf, const char **argv)
173{
174 char *ctx;
175 int count = 0;
176 char *tok;
177 char *pBuf = buf;
178
179 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
180 argv[count++] = tok;
181 pBuf = NULL;
182 }
183
184 return count;
185}
186
Jeff Hao48874692017-04-05 17:11:39 -0700187static const char* get_location_from_path(const char* path) {
188 static constexpr char kLocationSeparator = '/';
189 const char *location = strrchr(path, kLocationSeparator);
190 if (location == NULL) {
191 return path;
192 } else {
193 // Skip the separator character.
194 return location + 1;
195 }
196}
197
Jeff Sharkey90aff262016-12-12 14:28:24 -0700198static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
199 const char* input_file_name, const char* output_file_name, int swap_fd,
Jeff Hao48874692017-04-05 17:11:39 -0700200 const char* instruction_set, const char* compiler_filter, bool vm_safe_mode,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700201 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
202 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
203
204 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
205 ALOGE("Instruction set %s longer than max length of %d",
206 instruction_set, MAX_INSTRUCTION_SET_LEN);
207 return;
208 }
209
Jeff Hao48874692017-04-05 17:11:39 -0700210 // Get the relative path to the input file.
211 const char* relative_input_file_name = get_location_from_path(input_file_name);
212
Jeff Sharkey90aff262016-12-12 14:28:24 -0700213 char dex2oat_Xms_flag[kPropertyValueMax];
214 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
215
216 char dex2oat_Xmx_flag[kPropertyValueMax];
217 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
218
219 char dex2oat_threads_buf[kPropertyValueMax];
220 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
221 ? "dalvik.vm.dex2oat-threads"
222 : "dalvik.vm.boot-dex2oat-threads",
223 dex2oat_threads_buf,
224 NULL) > 0;
225 char dex2oat_threads_arg[kPropertyValueMax + 2];
226 if (have_dex2oat_threads_flag) {
227 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
228 }
229
230 char dex2oat_isa_features_key[kPropertyKeyMax];
231 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
232 char dex2oat_isa_features[kPropertyValueMax];
233 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
234 dex2oat_isa_features, NULL) > 0;
235
236 char dex2oat_isa_variant_key[kPropertyKeyMax];
237 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
238 char dex2oat_isa_variant[kPropertyValueMax];
239 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
240 dex2oat_isa_variant, NULL) > 0;
241
242 const char *dex2oat_norelocation = "-Xnorelocate";
243 bool have_dex2oat_relocation_skip_flag = false;
244
245 char dex2oat_flags[kPropertyValueMax];
246 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
247 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
248 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
249
250 // If we booting without the real /data, don't spend time compiling.
251 char vold_decrypt[kPropertyValueMax];
252 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
253 bool skip_compilation = (have_vold_decrypt &&
254 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
255 (strcmp(vold_decrypt, "1") == 0)));
256
257 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
258
259 char app_image_format[kPropertyValueMax];
260 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
261 bool have_app_image_format =
262 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
263 if (have_app_image_format) {
264 sprintf(image_format_arg, "--image-format=%s", app_image_format);
265 }
266
267 char dex2oat_large_app_threshold[kPropertyValueMax];
268 bool have_dex2oat_large_app_threshold =
269 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
270 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
271 if (have_dex2oat_large_app_threshold) {
272 sprintf(dex2oat_large_app_threshold_arg,
273 "--very-large-app-threshold=%s",
274 dex2oat_large_app_threshold);
275 }
276
277 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
278
279 static const char* RUNTIME_ARG = "--runtime-arg";
280
281 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
282
George Burgess IV36cebe772017-01-25 11:52:01 -0800283 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
284 // use arraysize instead.
285 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
286 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
287 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
288 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
289 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
290 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
291 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
292 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
293 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
294 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
295 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
296 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700297 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800298 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700299 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800300 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700301
302 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao48874692017-04-05 17:11:39 -0700303 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700304 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
305 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
306 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
307 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
308 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
309 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
310 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
311 if (swap_fd >= 0) {
312 have_dex2oat_swap_fd = true;
313 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
314 }
315 if (image_fd >= 0) {
316 have_dex2oat_image_fd = true;
317 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
318 }
319
320 if (have_dex2oat_Xms_flag) {
321 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
322 }
323 if (have_dex2oat_Xmx_flag) {
324 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
325 }
326
327 // Compute compiler filter.
328
329 bool have_dex2oat_compiler_filter_flag;
330 if (skip_compilation) {
Nicolas Geoffray4b64ed92017-04-25 12:28:28 +0100331 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700332 have_dex2oat_compiler_filter_flag = true;
333 have_dex2oat_relocation_skip_flag = true;
334 } else if (vm_safe_mode) {
Nicolas Geoffray4b64ed92017-04-25 12:28:28 +0100335 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=quicken");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700336 have_dex2oat_compiler_filter_flag = true;
337 } else if (compiler_filter != nullptr &&
338 strlen(compiler_filter) + strlen("--compiler-filter=") <
339 arraysize(dex2oat_compiler_filter_arg)) {
340 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
341 have_dex2oat_compiler_filter_flag = true;
342 } else {
343 char dex2oat_compiler_filter_flag[kPropertyValueMax];
344 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
345 dex2oat_compiler_filter_flag, NULL) > 0;
346 if (have_dex2oat_compiler_filter_flag) {
347 sprintf(dex2oat_compiler_filter_arg,
348 "--compiler-filter=%s",
349 dex2oat_compiler_filter_flag);
350 }
351 }
352
353 // Check whether all apps should be compiled debuggable.
354 if (!debuggable) {
355 char prop_buf[kPropertyValueMax];
356 debuggable =
357 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
358 (prop_buf[0] == '1');
359 }
360 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
361 if (profile_fd != -1) {
362 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
363 }
364
Jeff Hao89aeee42017-04-19 13:50:15 -0700365 // Get the directory of the apk to pass as a base classpath directory.
366 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
Jeff Hao48874692017-04-05 17:11:39 -0700367 std::string apk_dir(input_file_name);
368 unsigned long dir_index = apk_dir.rfind('/');
369 bool has_base_dir = dir_index != std::string::npos;
370 if (has_base_dir) {
371 apk_dir = apk_dir.substr(0, dir_index);
Jeff Hao89aeee42017-04-19 13:50:15 -0700372 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
Jeff Hao48874692017-04-05 17:11:39 -0700373 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700374
Jeff Hao48874692017-04-05 17:11:39 -0700375
376 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700377
378 const char* argv[9 // program name, mandatory arguments and the final NULL
379 + (have_dex2oat_isa_variant ? 1 : 0)
380 + (have_dex2oat_isa_features ? 1 : 0)
381 + (have_dex2oat_Xms_flag ? 2 : 0)
382 + (have_dex2oat_Xmx_flag ? 2 : 0)
383 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
384 + (have_dex2oat_threads_flag ? 1 : 0)
385 + (have_dex2oat_swap_fd ? 1 : 0)
386 + (have_dex2oat_image_fd ? 1 : 0)
387 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
388 + (generate_debug_info ? 1 : 0)
389 + (debuggable ? 1 : 0)
390 + (have_app_image_format ? 1 : 0)
391 + dex2oat_flags_count
392 + (profile_fd == -1 ? 0 : 1)
393 + (shared_libraries != nullptr ? 4 : 0)
Jeff Hao48874692017-04-05 17:11:39 -0700394 + (has_base_dir ? 1 : 0)
Jeff Sharkey90aff262016-12-12 14:28:24 -0700395 + (have_dex2oat_large_app_threshold ? 1 : 0)];
396 int i = 0;
397 argv[i++] = DEX2OAT_BIN;
398 argv[i++] = zip_fd_arg;
399 argv[i++] = zip_location_arg;
400 argv[i++] = input_vdex_fd_arg;
401 argv[i++] = output_vdex_fd_arg;
402 argv[i++] = oat_fd_arg;
403 argv[i++] = oat_location_arg;
404 argv[i++] = instruction_set_arg;
405 if (have_dex2oat_isa_variant) {
406 argv[i++] = instruction_set_variant_arg;
407 }
408 if (have_dex2oat_isa_features) {
409 argv[i++] = instruction_set_features_arg;
410 }
411 if (have_dex2oat_Xms_flag) {
412 argv[i++] = RUNTIME_ARG;
413 argv[i++] = dex2oat_Xms_arg;
414 }
415 if (have_dex2oat_Xmx_flag) {
416 argv[i++] = RUNTIME_ARG;
417 argv[i++] = dex2oat_Xmx_arg;
418 }
419 if (have_dex2oat_compiler_filter_flag) {
420 argv[i++] = dex2oat_compiler_filter_arg;
421 }
422 if (have_dex2oat_threads_flag) {
423 argv[i++] = dex2oat_threads_arg;
424 }
425 if (have_dex2oat_swap_fd) {
426 argv[i++] = dex2oat_swap_fd;
427 }
428 if (have_dex2oat_image_fd) {
429 argv[i++] = dex2oat_image_fd;
430 }
431 if (generate_debug_info) {
432 argv[i++] = "--generate-debug-info";
433 }
434 if (debuggable) {
435 argv[i++] = "--debuggable";
436 }
437 if (have_app_image_format) {
438 argv[i++] = image_format_arg;
439 }
440 if (have_dex2oat_large_app_threshold) {
441 argv[i++] = dex2oat_large_app_threshold_arg;
442 }
443 if (dex2oat_flags_count) {
444 i += split(dex2oat_flags, argv + i);
445 }
446 if (have_dex2oat_relocation_skip_flag) {
447 argv[i++] = RUNTIME_ARG;
448 argv[i++] = dex2oat_norelocation;
449 }
450 if (profile_fd != -1) {
451 argv[i++] = profile_arg;
452 }
453 if (shared_libraries != nullptr) {
454 argv[i++] = RUNTIME_ARG;
455 argv[i++] = "-classpath";
456 argv[i++] = RUNTIME_ARG;
457 argv[i++] = shared_libraries;
458 }
Jeff Hao48874692017-04-05 17:11:39 -0700459 if (has_base_dir) {
460 argv[i++] = base_dir;
461 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700462 // Do not add after dex2oat_flags, they should override others for debugging.
463 argv[i] = NULL;
464
465 execv(DEX2OAT_BIN, (char * const *)argv);
466 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
467}
468
469/*
470 * Whether dexopt should use a swap file when compiling an APK.
471 *
472 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
473 * itself, anyways).
474 *
475 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
476 *
477 * Otherwise, return true if this is a low-mem device.
478 *
479 * Otherwise, return default value.
480 */
481static bool kAlwaysProvideSwapFile = false;
482static bool kDefaultProvideSwapFile = true;
483
484static bool ShouldUseSwapFileForDexopt() {
485 if (kAlwaysProvideSwapFile) {
486 return true;
487 }
488
489 // Check the "override" property. If it exists, return value == "true".
490 char dex2oat_prop_buf[kPropertyValueMax];
491 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
492 if (strcmp(dex2oat_prop_buf, "true") == 0) {
493 return true;
494 } else {
495 return false;
496 }
497 }
498
499 // Shortcut for default value. This is an implementation optimization for the process sketched
500 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
501 // as low-mem is never returning false. The compiler will optimize this away if it can.
502 if (kDefaultProvideSwapFile) {
503 return true;
504 }
505
506 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
507 if (is_low_mem) {
508 return true;
509 }
510
511 // Default value must be false here.
512 return kDefaultProvideSwapFile;
513}
514
Richard Uhler76cc0272016-12-08 10:46:35 +0000515static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700516 if (set_to_bg) {
517 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
518 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
519 exit(70);
520 }
521 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
522 ALOGE("setpriority failed: %s\n", strerror(errno));
523 exit(71);
524 }
525 }
526}
527
Calin Juravle114f0812017-03-08 19:05:07 -0800528static bool create_profile(int uid, const std::string& profile) {
529 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), O_CREAT | O_NOFOLLOW, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800530 if (fd.get() < 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800531 if (errno == EEXIST) {
532 return true;
533 } else {
534 PLOG(ERROR) << "Failed to create profile " << profile;
535 return false;
536 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700537 }
Calin Juravle114f0812017-03-08 19:05:07 -0800538 // Profiles should belong to the app; make sure of that by giving ownership to
539 // the app uid. If we cannot do that, there's no point in returning the fd
540 // since dex2oat/profman will fail with SElinux denials.
541 if (fchown(fd.get(), uid, uid) < 0) {
542 PLOG(ERROR) << "Could not chwon profile " << profile;
543 return false;
544 }
545 return true;
546}
547
548static unique_fd open_profile(int uid, const std::string& profile, bool read_write) {
549 // Check if we need to open the profile for a read-write operation. If so, we
550 // might need to create the profile since the file might not be there. Reference
551 // profiles are created on the fly so they might not exist beforehand.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552 if (read_write) {
Calin Juravle114f0812017-03-08 19:05:07 -0800553 if (!create_profile(uid, profile)) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800554 return invalid_unique_fd();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700555 }
556 }
Calin Juravle114f0812017-03-08 19:05:07 -0800557 int flags = read_write ? O_RDWR : O_RDONLY;
558 // Do not follow symlinks when opening a profile:
559 // - primary profiles should not contain symlinks in their paths
560 // - secondary dex paths should have been already resolved and validated
561 flags |= O_NOFOLLOW;
562
563 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
564 if (fd.get() < 0) {
565 if (errno != ENOENT) {
566 // Profiles might be missing for various reasons. For example, in a
567 // multi-user environment, the profile directory for one user can be created
568 // after we start a merge. In this case the current profile for that user
569 // will not be found.
570 // Also, the secondary dex profiles might be deleted by the app at any time,
571 // so we can't we need to prepare if they are missing.
572 PLOG(ERROR) << "Failed to open profile " << profile;
573 }
574 return invalid_unique_fd();
575 }
576
Jeff Sharkey90aff262016-12-12 14:28:24 -0700577 return fd;
578}
579
Calin Juravle114f0812017-03-08 19:05:07 -0800580static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
581 bool is_secondary_dex) {
582 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
583 return open_profile(uid, profile, /*read_write*/false);
584}
585
586static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
587 bool is_secondary_dex) {
588 std::string profile = create_reference_profile_path(location, is_secondary_dex);
589 return open_profile(uid, profile, read_write);
590}
591
592static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800593 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700594 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800595 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
596 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700597
Calin Juravle114f0812017-03-08 19:05:07 -0800598 // For secondary dex files, we don't really need the user but we use it for sanity checks.
599 // Note: the user owning the dex file should be the current user.
600 std::vector<userid_t> users;
601 if (is_secondary_dex){
602 users.push_back(multiuser_get_user_id(uid));
603 } else {
604 users = get_known_users(/*volume_uuid*/ nullptr);
605 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700606 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800607 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700608 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800609 if (profile_fd.get() >= 0) {
610 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611 }
612 }
613}
614
615static void drop_capabilities(uid_t uid) {
616 if (setgid(uid) != 0) {
617 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
618 exit(64);
619 }
620 if (setuid(uid) != 0) {
621 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
622 exit(65);
623 }
624 // drop capabilities
625 struct __user_cap_header_struct capheader;
626 struct __user_cap_data_struct capdata[2];
627 memset(&capheader, 0, sizeof(capheader));
628 memset(&capdata, 0, sizeof(capdata));
629 capheader.version = _LINUX_CAPABILITY_VERSION_3;
630 if (capset(&capheader, &capdata[0]) < 0) {
631 ALOGE("capset failed: %s\n", strerror(errno));
632 exit(66);
633 }
634}
635
636static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
637static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
638static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
639static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
640static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
641
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800642static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
643 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644 static const size_t MAX_INT_LEN = 32;
645 static const char* PROFMAN_BIN = "/system/bin/profman";
646
647 std::vector<std::string> profile_args(profiles_fd.size());
648 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
649 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800650 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700651 profile_args[k].assign(profile_buf);
652 }
653 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800654 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700655
656 // program name, reference profile fd, the final NULL and the profile fds
657 const char* argv[3 + profiles_fd.size()];
658 int i = 0;
659 argv[i++] = PROFMAN_BIN;
660 argv[i++] = reference_profile_arg;
661 for (size_t k = 0; k < profile_args.size(); k++) {
662 argv[i++] = profile_args[k].c_str();
663 }
664 // Do not add after dex2oat_flags, they should override others for debugging.
665 argv[i] = NULL;
666
667 execv(PROFMAN_BIN, (char * const *)argv);
668 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
669 exit(68); /* only get here on exec failure */
670}
671
672// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800673// The location is the package name for primary apks or the dex path for secondary dex files.
674// Returns true if there is enough information in the current profiles that makes it
675// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700676// If the return value is true all the current profiles would have been merged into
677// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800678static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800679 std::vector<unique_fd> profiles_fd;
680 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800681 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800682 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700683 // Skip profile guided compilation because no profiles were found.
684 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700685 return false;
686 }
687
Jeff Sharkey90aff262016-12-12 14:28:24 -0700688 pid_t pid = fork();
689 if (pid == 0) {
690 /* child -- drop privileges before continuing */
691 drop_capabilities(uid);
692 run_profman_merge(profiles_fd, reference_profile_fd);
693 exit(68); /* only get here on exec failure */
694 }
695 /* parent */
696 int return_code = wait_child(pid);
697 bool need_to_compile = false;
698 bool should_clear_current_profiles = false;
699 bool should_clear_reference_profile = false;
700 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800701 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700702 } else {
703 return_code = WEXITSTATUS(return_code);
704 switch (return_code) {
705 case PROFMAN_BIN_RETURN_CODE_COMPILE:
706 need_to_compile = true;
707 should_clear_current_profiles = true;
708 should_clear_reference_profile = false;
709 break;
710 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
711 need_to_compile = false;
712 should_clear_current_profiles = false;
713 should_clear_reference_profile = false;
714 break;
715 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800716 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700717 need_to_compile = false;
718 should_clear_current_profiles = true;
719 should_clear_reference_profile = true;
720 break;
721 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
722 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
723 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800724 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700725 need_to_compile = false;
726 should_clear_current_profiles = false;
727 should_clear_reference_profile = false;
728 break;
729 default:
730 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800731 LOG(WARNING) << "Unknown error code while processing profiles for location "
732 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700733 need_to_compile = false;
734 should_clear_current_profiles = true;
735 should_clear_reference_profile = true;
736 break;
737 }
738 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800739
Jeff Sharkey90aff262016-12-12 14:28:24 -0700740 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800741 if (is_secondary_dex) {
742 // For secondary dex files, the owning user is the current user.
743 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
744 } else {
745 clear_primary_current_profiles(location);
746 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747 }
748 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800749 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750 }
751 return need_to_compile;
752}
753
Calin Juravle114f0812017-03-08 19:05:07 -0800754// Decides if profile guided compilation is needed or not based on existing profiles.
755// The analysis is done for the primary apks of the given package.
756// Returns true if there is enough information in the current profiles that makes it
757// worth to recompile the package.
758// If the return value is true all the current profiles would have been merged into
759// the reference profiles accessible with open_reference_profile().
760bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
761 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
762}
763
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800764static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
765 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700766 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800767 const std::vector<unique_fd>& apk_fds,
768 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 std::vector<std::string> profman_args;
770 static const char* PROFMAN_BIN = "/system/bin/profman";
771 profman_args.push_back(PROFMAN_BIN);
772 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800773 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774 if (reference_profile_fd != -1) {
775 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800776 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700777 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800778 for (size_t i = 0; i < profile_fds.size(); i++) {
779 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700780 }
781 for (const std::string& dex_location : dex_locations) {
782 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
783 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800784 for (size_t i = 0; i < apk_fds.size(); i++) {
785 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700786 }
787 const char **argv = new const char*[profman_args.size() + 1];
788 size_t i = 0;
789 for (const std::string& profman_arg : profman_args) {
790 argv[i++] = profman_arg.c_str();
791 }
792 argv[i] = NULL;
793
794 execv(PROFMAN_BIN, (char * const *)argv);
795 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
796 exit(68); /* only get here on exec failure */
797}
798
Calin Juravle76268c52017-03-09 13:19:42 -0800799bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800800 std::vector<unique_fd> profile_fds;
801 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800802 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700803
Calin Juravle114f0812017-03-08 19:05:07 -0800804 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
805 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700806
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800807 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808 const bool has_profiles = !profile_fds.empty();
809
810 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800811 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700812 return false;
813 }
814
Calin Juravle114f0812017-03-08 19:05:07 -0800815 unique_fd output_fd(open(out_file_name.c_str(),
816 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
818 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
819 return false;
820 }
821 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
822 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800823 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700824 for (const std::string& code_full_path : code_full_paths) {
825 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800826 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827 if (apk_fd == -1) {
828 ALOGE("installd cannot open '%s'\n", full_path);
829 return false;
830 }
831 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800832 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 }
834
835 pid_t pid = fork();
836 if (pid == 0) {
837 /* child -- drop privileges before continuing */
838 drop_capabilities(uid);
839 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
840 apk_fds, output_fd);
841 exit(68); /* only get here on exec failure */
842 }
843 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700844 int return_code = wait_child(pid);
845 if (!WIFEXITED(return_code)) {
846 LOG(WARNING) << "profman failed for package " << pkgname << ": "
847 << return_code;
848 return false;
849 }
850 return true;
851}
852
853static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
854 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
855 if (EndsWith(oat_path, ".dex")) {
856 std::string new_path = oat_path;
857 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
858 CHECK(EndsWith(new_path, new_ext.c_str()));
859 return new_path;
860 }
861
862 // An odex entry. Not that this may not be an extension, e.g., in the OTA
863 // case (where the base name will have an extension for the B artifact).
864 size_t odex_pos = oat_path.rfind(".odex");
865 if (odex_pos != std::string::npos) {
866 std::string new_path = oat_path;
867 new_path.replace(odex_pos, strlen(".odex"), new_ext);
868 CHECK_NE(new_path.find(new_ext), std::string::npos);
869 return new_path;
870 }
871
872 // Don't know how to handle this.
873 return "";
874}
875
876// Translate the given oat path to an art (app image) path. An empty string
877// denotes an error.
878static std::string create_image_filename(const std::string& oat_path) {
879 return replace_file_extension(oat_path, ".art");
880}
881
882// Translate the given oat path to a vdex path. An empty string denotes an error.
883static std::string create_vdex_filename(const std::string& oat_path) {
884 return replace_file_extension(oat_path, ".vdex");
885}
886
887static bool add_extension_to_file_name(char* file_name, const char* extension) {
888 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
889 return false;
890 }
891 strcat(file_name, extension);
892 return true;
893}
894
895static int open_output_file(const char* file_name, bool recreate, int permissions) {
896 int flags = O_RDWR | O_CREAT;
897 if (recreate) {
898 if (unlink(file_name) < 0) {
899 if (errno != ENOENT) {
900 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
901 }
902 }
903 flags |= O_EXCL;
904 }
905 return open(file_name, flags, permissions);
906}
907
Calin Juravle2289c0a2017-02-15 12:44:14 -0800908static bool set_permissions_and_ownership(
909 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
910 // Primary apks are owned by the system. Secondary dex files are owned by the app.
911 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700912 if (fchmod(fd,
913 S_IRUSR|S_IWUSR|S_IRGRP |
914 (is_public ? S_IROTH : 0)) < 0) {
915 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
916 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800917 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700918 ALOGE("installd cannot chown '%s' during dexopt\n", path);
919 return false;
920 }
921 return true;
922}
923
924static bool IsOutputDalvikCache(const char* oat_dir) {
925 // InstallerConnection.java (which invokes installd) transforms Java null arguments
926 // into '!'. Play it safe by handling it both.
927 // TODO: ensure we never get null.
928 // TODO: pass a flag instead of inferring if the output is dalvik cache.
929 return oat_dir == nullptr || oat_dir[0] == '!';
930}
931
932static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -0800933 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934 // Early best-effort check whether we can fit the the path into our buffers.
935 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
936 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
937 // extension to the cache path (5 bytes).
938 if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
939 ALOGE("apk_path too long '%s'\n", apk_path);
940 return false;
941 }
942
943 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -0800944 // Oat dirs for secondary dex files are already validated.
945 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700946 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
947 return false;
948 }
949 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
950 return false;
951 }
952 } else {
953 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
954 return false;
955 }
956 }
957 return true;
958}
959
960// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
961// on destruction. It will also run the given cleanup (unless told not to) after closing.
962//
963// Usage example:
964//
Calin Juravle7a570e82017-01-14 16:23:30 -0800965// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -0700966// [name]() {
967// unlink(name.c_str());
968// });
969// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
970// wrapper if captured as a reference.
971//
972// if (file.get() == -1) {
973// // Error opening...
974// }
975//
976// ...
977// if (error) {
978// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
979// // and delete the file (after the fd is closed).
980// return -1;
981// }
982//
983// (Success case)
984// file.SetCleanup(false);
985// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
986// // (leaving the file around; after the fd is closed).
987//
Jeff Sharkey90aff262016-12-12 14:28:24 -0700988class Dex2oatFileWrapper {
989 public:
Calin Juravle7a570e82017-01-14 16:23:30 -0800990 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700991 }
992
Calin Juravle7a570e82017-01-14 16:23:30 -0800993 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
994 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
995
996 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
997 value_ = other.value_;
998 cleanup_ = other.cleanup_;
999 do_cleanup_ = other.do_cleanup_;
1000 auto_close_ = other.auto_close_;
1001 other.release();
1002 }
1003
1004 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1005 value_ = other.value_;
1006 cleanup_ = other.cleanup_;
1007 do_cleanup_ = other.do_cleanup_;
1008 auto_close_ = other.auto_close_;
1009 other.release();
1010 return *this;
1011 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001012
1013 ~Dex2oatFileWrapper() {
1014 reset(-1);
1015 }
1016
1017 int get() {
1018 return value_;
1019 }
1020
1021 void SetCleanup(bool cleanup) {
1022 do_cleanup_ = cleanup;
1023 }
1024
1025 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001026 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001027 close(value_);
1028 }
1029 if (do_cleanup_ && cleanup_ != nullptr) {
1030 cleanup_();
1031 }
1032
1033 value_ = new_value;
1034 }
1035
Calin Juravle7a570e82017-01-14 16:23:30 -08001036 void reset(int new_value, std::function<void ()> new_cleanup) {
1037 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001038 close(value_);
1039 }
1040 if (do_cleanup_ && cleanup_ != nullptr) {
1041 cleanup_();
1042 }
1043
1044 value_ = new_value;
1045 cleanup_ = new_cleanup;
1046 }
1047
Calin Juravle7a570e82017-01-14 16:23:30 -08001048 void DisableAutoClose() {
1049 auto_close_ = false;
1050 }
1051
Jeff Sharkey90aff262016-12-12 14:28:24 -07001052 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001053 void release() {
1054 value_ = -1;
1055 do_cleanup_ = false;
1056 cleanup_ = nullptr;
1057 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001058 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001059 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001060 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001061 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001062};
1063
Calin Juravle7a570e82017-01-14 16:23:30 -08001064// (re)Creates the app image if needed.
1065Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001066 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001067 // Use app images only if it is enabled (by a set image format) and we are compiling
1068 // profile-guided (so the app image doesn't conservatively contain all classes).
Calin Juravle2289c0a2017-02-15 12:44:14 -08001069 // Note that we don't create an image for secondary dex files.
1070 if (is_secondary_dex || !profile_guided) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001071 return Dex2oatFileWrapper();
1072 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001073
Calin Juravle7a570e82017-01-14 16:23:30 -08001074 const std::string image_path = create_image_filename(out_oat_path);
1075 if (image_path.empty()) {
1076 // Happens when the out_oat_path has an unknown extension.
1077 return Dex2oatFileWrapper();
1078 }
1079 char app_image_format[kPropertyValueMax];
1080 bool have_app_image_format =
1081 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1082 if (!have_app_image_format) {
1083 return Dex2oatFileWrapper();
1084 }
1085 // Recreate is true since we do not want to modify a mapped image. If the app is
1086 // already running and we modify the image file, it can cause crashes (b/27493510).
1087 Dex2oatFileWrapper wrapper_fd(
1088 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1089 [image_path]() { unlink(image_path.c_str()); });
1090 if (wrapper_fd.get() < 0) {
1091 // Could not create application image file. Go on since we can compile without it.
1092 LOG(ERROR) << "installd could not create '" << image_path
1093 << "' for image file during dexopt";
1094 // If we have a valid image file path but no image fd, explicitly erase the image file.
1095 if (unlink(image_path.c_str()) < 0) {
1096 if (errno != ENOENT) {
1097 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1098 }
1099 }
1100 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001101 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001102 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1103 wrapper_fd.reset(-1);
1104 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001105
Calin Juravle7a570e82017-01-14 16:23:30 -08001106 return wrapper_fd;
1107}
1108
1109// Creates the dexopt swap file if necessary and return its fd.
1110// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001111unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001112 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001113 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001114 }
1115 // Make sure there really is enough space.
1116 char swap_file_name[PKG_PATH_MAX];
1117 strcpy(swap_file_name, out_oat_path);
1118 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001119 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001120 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001121 unique_fd swap_fd(open_output_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001122 swap_file_name, /*recreate*/true, /*permissions*/0600));
1123 if (swap_fd.get() < 0) {
1124 // Could not create swap file. Optimistically go on and hope that we can compile
1125 // without it.
1126 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1127 } else {
1128 // Immediately unlink. We don't really want to hit flash.
1129 if (unlink(swap_file_name) < 0) {
1130 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1131 }
1132 }
1133 return swap_fd;
1134}
1135
1136// Opens the reference profiles if needed.
1137// 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 -08001138Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1139 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1140 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001141 // Public apps should not be compiled with profile information ever. Same goes for the special
1142 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001143 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001144 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001145 }
Calin Juravle114f0812017-03-08 19:05:07 -08001146
1147 // Open reference profile in read only mode as dex2oat does not get write permissions.
1148 const std::string location = is_secondary_dex ? dex_path : pkgname;
1149 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1150 const auto& cleanup = [location, is_secondary_dex]() {
1151 clear_reference_profile(location.c_str(), is_secondary_dex);
1152 };
1153 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001154}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001155
Calin Juravle7a570e82017-01-14 16:23:30 -08001156// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1157// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1158bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001159 const char* instruction_set, bool is_public, bool profile_guided,
1160 int uid, bool is_secondary_dex, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001161 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1162 CHECK(in_vdex_wrapper_fd != nullptr);
1163 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001164 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1165 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001166 char in_odex_path[PKG_PATH_MAX];
1167 int dexopt_action = abs(dexopt_needed);
1168 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169 std::string in_vdex_path_str;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001170 // Disable passing an input vdex when the compilation is profile-guided. The dexlayout
1171 // optimization in dex2oat is incompatible with it. b/35872504.
1172 if (dexopt_action != DEX2OAT_FROM_SCRATCH && !profile_guided) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001173 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1174 const char* path = nullptr;
1175 if (is_odex_location) {
1176 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1177 path = in_odex_path;
1178 } else {
1179 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001180 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001181 }
1182 } else {
1183 path = out_oat_path;
1184 }
1185 in_vdex_path_str = create_vdex_filename(path);
1186 if (in_vdex_path_str.empty()) {
1187 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001188 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001189 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001190 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) {
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001191 // When we dex2oat because of boot image change, we are going to update
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001192 // in-place the vdex file.
Calin Juravle7a570e82017-01-14 16:23:30 -08001193 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001194 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001195 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001196 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001197 }
1198
1199 // Infer the name of the output VDEX and create it.
Calin Juravle7a570e82017-01-14 16:23:30 -08001200 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001201 if (out_vdex_path_str.empty()) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001202 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001203 }
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001204
1205 // If we are compiling because the boot image is out of date, we do not
1206 // need to recreate a vdex, and can use the same existing one.
1207 if (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE &&
Calin Juravle7a570e82017-01-14 16:23:30 -08001208 in_vdex_wrapper_fd->get() != -1 &&
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001209 in_vdex_path_str == out_vdex_path_str) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001210 out_vdex_wrapper_fd->reset(in_vdex_wrapper_fd->get());
1211 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1212 // wrapper).
1213 in_vdex_wrapper_fd->DisableAutoClose();
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001214 } else {
Calin Juravle7a570e82017-01-14 16:23:30 -08001215 out_vdex_wrapper_fd->reset(
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001216 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1217 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
Calin Juravle7a570e82017-01-14 16:23:30 -08001218 if (out_vdex_wrapper_fd->get() < 0) {
1219 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1220 return false;
Nicolas Geoffrayca122282016-12-20 15:03:56 +00001221 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001222 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001223 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001224 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001225 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1226 return false;
1227 }
1228
1229 // If we got here we successfully opened the vdex files.
1230 return true;
1231}
1232
1233// Opens the output oat file for the given apk.
1234// If successful it stores the output path into out_oat_path and returns true.
1235Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001236 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1237 char* out_oat_path) {
1238 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001239 return Dex2oatFileWrapper();
1240 }
1241 const std::string out_oat_path_str(out_oat_path);
1242 Dex2oatFileWrapper wrapper_fd(
1243 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1244 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1245 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001246 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001247 } else if (!set_permissions_and_ownership(
1248 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1250 wrapper_fd.reset(-1);
1251 }
1252 return wrapper_fd;
1253}
1254
1255// Updates the access times of out_oat_path based on those from apk_path.
1256void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1257 struct stat input_stat;
1258 memset(&input_stat, 0, sizeof(input_stat));
1259 if (stat(apk_path, &input_stat) != 0) {
1260 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1261 return;
1262 }
1263
1264 struct utimbuf ut;
1265 ut.actime = input_stat.st_atime;
1266 ut.modtime = input_stat.st_mtime;
1267 if (utime(out_oat_path, &ut) != 0) {
1268 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1269 }
1270}
1271
Calin Juravle80a21252017-01-17 14:43:25 -08001272// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001273// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1274// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1275// the profile has changed.
1276static void exec_dexoptanalyzer(const std::string& dex_file, const char* instruction_set,
1277 const char* compiler_filter, bool profile_was_updated) {
Calin Juravle80a21252017-01-17 14:43:25 -08001278 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1279 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1280
1281 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
1282 ALOGE("Instruction set %s longer than max length of %d",
1283 instruction_set, MAX_INSTRUCTION_SET_LEN);
1284 return;
1285 }
1286
1287 char dex_file_arg[strlen("--dex-file=") + PKG_PATH_MAX];
1288 char isa_arg[strlen("--isa=") + MAX_INSTRUCTION_SET_LEN];
1289 char compiler_filter_arg[strlen("--compiler-filter=") + kPropertyValueMax];
Calin Juravle114f0812017-03-08 19:05:07 -08001290 const char* assume_profile_changed = "--assume-profile-changed";
Calin Juravle80a21252017-01-17 14:43:25 -08001291
Calin Juravle114f0812017-03-08 19:05:07 -08001292 sprintf(dex_file_arg, "--dex-file=%s", dex_file.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001293 sprintf(isa_arg, "--isa=%s", instruction_set);
1294 sprintf(compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
1295
1296 // program name, dex file, isa, filter, the final NULL
Calin Juravle114f0812017-03-08 19:05:07 -08001297 const char* argv[5 + (profile_was_updated ? 1 : 0)];
Calin Juravle80a21252017-01-17 14:43:25 -08001298 int i = 0;
1299 argv[i++] = DEXOPTANALYZER_BIN;
1300 argv[i++] = dex_file_arg;
1301 argv[i++] = isa_arg;
1302 argv[i++] = compiler_filter_arg;
Calin Juravle114f0812017-03-08 19:05:07 -08001303 if (profile_was_updated) {
1304 argv[i++] = assume_profile_changed;
1305 }
Calin Juravle80a21252017-01-17 14:43:25 -08001306 argv[i] = NULL;
1307
1308 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1309 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1310}
1311
1312// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001313static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1314 const char* instruction_set, std::string* oat_dir_out) {
1315 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001316 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001317 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001318 return false;
1319 }
Calin Juravle114f0812017-03-08 19:05:07 -08001320 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001321
1322 // Assign the gid to the cache gid so that the oat file storage
1323 // is counted towards the app cache.
1324 int32_t cache_gid = multiuser_get_cache_gid(
1325 multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1326 // If UID doesn't have a specific cache GID, use UID value
1327 if (cache_gid == -1) {
1328 cache_gid = uid;
1329 }
1330
1331 // Create oat file output directory.
Calin Juravle114f0812017-03-08 19:05:07 -08001332 if (prepare_app_cache_dir(dex_dir, "oat", 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001333 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001334 return false;
1335 }
1336
1337 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001338 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001339 oat_dir_out->assign(oat_dir);
1340
1341 // Create oat/isa output directory.
1342 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, 02711, uid, cache_gid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001343 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001344 return false;
1345 }
1346
1347 return true;
1348}
1349
1350static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1351
1352// Verifies the result of dexoptanalyzer executed for the apk_path.
1353// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1354// Returns false for errors or unexpected result values.
Calin Juravle114f0812017-03-08 19:05:07 -08001355static bool process_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001356 int* dexopt_needed_out) {
1357 // The result values are defined in dexoptanalyzer.
1358 switch (result) {
1359 case 0: // no_dexopt_needed
1360 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1361 case 1: // dex2oat_from_scratch
1362 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1363 case 5: // dex2oat_for_bootimage_odex
1364 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1365 case 6: // dex2oat_for_filter_odex
1366 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1367 case 7: // dex2oat_for_relocation_odex
1368 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1369 case 2: // dex2oat_for_bootimage_oat
1370 case 3: // dex2oat_for_filter_oat
1371 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001372 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1373 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001374 << " : dexoptanalyzer result=" << result;
1375 return false;
1376 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001377 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001378 << " exec_dexoptanalyzer result=" << result;
1379 return false;
1380 }
1381}
1382
Calin Juravlec9eab382017-01-25 01:17:17 -08001383// 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 -08001384// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1385// successfully.
1386// When returning true, dexopt_needed_out is assigned a valid OatFileAsssitant::DexOptNeeded
Calin Juravle114f0812017-03-08 19:05:07 -08001387// code and oat_dir_out is assigned the oat dir path where the oat file should be stored.
1388static bool process_secondary_dex_dexopt(const char* original_dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001389 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravle114f0812017-03-08 19:05:07 -08001390 const char* compiler_filter, int* dexopt_needed_out, std::string* oat_dir_out,
1391 std::string* dex_path_out) {
Calin Juravle80a21252017-01-17 14:43:25 -08001392 int storage_flag;
1393
1394 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1395 storage_flag = FLAG_STORAGE_CE;
1396 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1397 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1398 return false;
1399 }
1400 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1401 storage_flag = FLAG_STORAGE_DE;
1402 } else {
1403 LOG(ERROR) << "Secondary dex storage flag must be set";
1404 return false;
1405 }
1406
Calin Juravle114f0812017-03-08 19:05:07 -08001407 {
1408 // As opposed to the primary apk, secondary dex files might contain symlinks.
1409 // Resolve the path before passing it to the validate method to
1410 // make sure the verification is done on the real location.
1411 UniqueCPtr<char> dex_real_path_cstr(realpath(original_dex_path, nullptr));
1412 if (dex_real_path_cstr == nullptr) {
1413 PLOG(ERROR) << "Could not get the real path of the secondary dex file "
1414 << original_dex_path;
1415 return false;
1416 } else {
1417 dex_path_out->assign(dex_real_path_cstr.get());
1418 }
1419 }
1420 const std::string& dex_path = *dex_path_out;
Calin Juravlec9eab382017-01-25 01:17:17 -08001421 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1422 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001423 return false;
1424 }
1425
1426 // Check if the path exist. If not, there's nothing to do.
Calin Juravle114f0812017-03-08 19:05:07 -08001427 if (access(dex_path.c_str(), F_OK) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001428 if (errno == ENOENT) {
1429 // Secondary dex files might be deleted any time by the app.
1430 // Nothing to do if that's the case
Calin Juravle114f0812017-03-08 19:05:07 -08001431 ALOGV("Secondary dex does not exist %s", dex_path.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001432 return NO_DEXOPT_NEEDED;
1433 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001434 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001435 }
1436 }
1437
1438 // Prepare the oat directories.
Calin Juravle114f0812017-03-08 19:05:07 -08001439 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, oat_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001440 return false;
1441 }
1442
Calin Juravle114f0812017-03-08 19:05:07 -08001443 // Analyze profiles.
1444 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1445
Calin Juravle80a21252017-01-17 14:43:25 -08001446 pid_t pid = fork();
1447 if (pid == 0) {
1448 // child -- drop privileges before continuing.
1449 drop_capabilities(uid);
1450 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravle114f0812017-03-08 19:05:07 -08001451 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter, profile_was_updated);
Calin Juravle80a21252017-01-17 14:43:25 -08001452 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1453 }
1454
1455 /* parent */
1456
1457 int result = wait_child(pid);
1458 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001459 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001460 return false;
1461 }
1462 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001463 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001464 // Run dexopt only if needed or forced.
1465 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1466 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1467 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1468 // for oat files from dalvik-cache.
1469 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1470 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1471 }
1472
1473 return success;
1474}
1475
Calin Juravlec9eab382017-01-25 01:17:17 -08001476int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001477 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1478 const char* volume_uuid, const char* shared_libraries) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001479 CHECK(pkgname != nullptr);
1480 CHECK(pkgname[0] != 0);
1481 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1482 LOG_FATAL("dexopt flags contains unknown fields\n");
1483 }
1484
1485 bool is_public = ((dexopt_flags & DEXOPT_PUBLIC) != 0);
1486 bool vm_safe_mode = (dexopt_flags & DEXOPT_SAFEMODE) != 0;
1487 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1488 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1489 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001490 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1491
1492 // Check if we're dealing with a secondary dex file and if we need to compile it.
1493 std::string oat_dir_str;
Calin Juravle114f0812017-03-08 19:05:07 -08001494 std::string dex_real_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001495 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001496 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravle114f0812017-03-08 19:05:07 -08001497 instruction_set, compiler_filter, &dexopt_needed, &oat_dir_str, &dex_real_path)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001498 oat_dir = oat_dir_str.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001499 dex_path = dex_real_path.c_str();
Calin Juravle80a21252017-01-17 14:43:25 -08001500 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1501 return 0; // Nothing to do, report success.
1502 }
1503 } else {
1504 return -1; // We had an error, logged in the process method.
1505 }
1506 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001507 // Currently these flags are only use for secondary dex files.
1508 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001509 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1510 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1511 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001512
1513 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001514 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001515 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001516 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001517 return -1;
1518 }
1519
1520 // Create the output OAT file.
1521 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001522 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001523 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001524 if (out_oat_fd.get() < 0) {
1525 return -1;
1526 }
1527
1528 // Open vdex files.
1529 Dex2oatFileWrapper in_vdex_fd;
1530 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffraya2dbefc2017-03-09 13:11:25 +00001531 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public,
1532 profile_guided, uid, is_secondary_dex, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001533 return -1;
1534 }
1535
1536 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001537 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001538
Calin Juravle7a570e82017-01-14 16:23:30 -08001539 // Create the app image file if needed.
1540 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001541 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001542
Calin Juravle7a570e82017-01-14 16:23:30 -08001543 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001544 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1545 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001546
Calin Juravlec9eab382017-01-25 01:17:17 -08001547 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001548
1549 pid_t pid = fork();
1550 if (pid == 0) {
1551 /* child -- drop privileges before continuing */
1552 drop_capabilities(uid);
1553
Richard Uhler76cc0272016-12-08 10:46:35 +00001554 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001555 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1556 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1557 _exit(67);
1558 }
1559
Richard Uhler76cc0272016-12-08 10:46:35 +00001560 run_dex2oat(input_fd.get(),
1561 out_oat_fd.get(),
1562 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001563 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001564 image_fd.get(),
Jeff Hao48874692017-04-05 17:11:39 -07001565 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001566 out_oat_path,
1567 swap_fd.get(),
1568 instruction_set,
1569 compiler_filter,
1570 vm_safe_mode,
1571 debuggable,
1572 boot_complete,
1573 reference_profile_fd.get(),
1574 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001575 _exit(68); /* only get here on exec failure */
1576 } else {
1577 int res = wait_child(pid);
1578 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001579 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001580 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001581 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001582 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001583 }
1584 }
1585
Calin Juravlec9eab382017-01-25 01:17:17 -08001586 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001587
1588 // We've been successful, don't delete output.
1589 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001590 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001591 image_fd.SetCleanup(false);
1592 reference_profile_fd.SetCleanup(false);
1593
1594 return 0;
1595}
1596
Calin Juravlec9eab382017-01-25 01:17:17 -08001597// Try to remove the given directory. Log an error if the directory exists
1598// and is empty but could not be removed.
1599static bool rmdir_if_empty(const char* dir) {
1600 if (rmdir(dir) == 0) {
1601 return true;
1602 }
1603 if (errno == ENOENT || errno == ENOTEMPTY) {
1604 return true;
1605 }
1606 PLOG(ERROR) << "Failed to remove dir: " << dir;
1607 return false;
1608}
1609
1610// Try to unlink the given file. Log an error if the file exists and could not
1611// be unlinked.
1612static bool unlink_if_exists(const std::string& file) {
1613 if (unlink(file.c_str()) == 0) {
1614 return true;
1615 }
1616 if (errno == ENOENT) {
1617 return true;
1618
1619 }
1620 PLOG(ERROR) << "Could not unlink: " << file;
1621 return false;
1622}
1623
1624// Create the oat file structure for the secondary dex 'dex_path' and assign
1625// the individual path component to the 'out_' parameters.
1626static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1627 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1628 size_t dirIndex = dex_path.rfind('/');
1629 if (dirIndex == std::string::npos) {
1630 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1631 return false;
1632 }
1633 // TODO(calin): we have similar computations in at lest 3 other places
1634 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1635 // use string append.
1636 std::string apk_dir = dex_path.substr(0, dirIndex);
1637 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1638 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1639
1640 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001641 /*is_secondary_dex*/true, out_oat_path)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001642 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1643 return false;
1644 }
1645 return true;
1646}
1647
1648// Reconcile the secondary dex 'dex_path' and its generated oat files.
1649// Return true if all the parameters are valid and the secondary dex file was
1650// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1651// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1652// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1653// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1654// Return false if there were errors during processing. In this case
1655// out_secondary_dex_exists will be set to false.
1656bool reconcile_secondary_dex_file(const std::string& dex_path,
1657 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1658 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1659 /*out*/bool* out_secondary_dex_exists) {
1660 // Set out to false to start with, just in case we have validation errors.
1661 *out_secondary_dex_exists = false;
1662 if (isas.size() == 0) {
1663 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1664 return false;
1665 }
1666
1667 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1668 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1669 uid, storage_flag)) {
1670 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1671 return false;
1672 }
1673
1674 if (access(dex_path.c_str(), F_OK) == 0) {
1675 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1676 *out_secondary_dex_exists = true;
1677 return true;
1678 } else if (errno != ENOENT) {
1679 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1680 return false;
1681 }
1682
1683 // The secondary dex does not exist anymore. Clear any generated files.
1684 char oat_path[PKG_PATH_MAX];
1685 char oat_dir[PKG_PATH_MAX];
1686 char oat_isa_dir[PKG_PATH_MAX];
1687 bool result = true;
1688 for (size_t i = 0; i < isas.size(); i++) {
1689 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1690 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1691 result = false;
1692 continue;
1693 }
1694 result = unlink_if_exists(oat_path) && result;
1695 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1696 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1697
1698 // Try removing the directories as well, they might be empty.
1699 result = rmdir_if_empty(oat_isa_dir) && result;
1700 result = rmdir_if_empty(oat_dir) && result;
1701 }
1702
1703 return result;
1704}
1705
Jeff Sharkey90aff262016-12-12 14:28:24 -07001706// Helper for move_ab, so that we can have common failure-case cleanup.
1707static bool unlink_and_rename(const char* from, const char* to) {
1708 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1709 // return a failure.
1710 struct stat s;
1711 if (stat(to, &s) == 0) {
1712 if (!S_ISREG(s.st_mode)) {
1713 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1714 return false;
1715 }
1716 if (unlink(to) != 0) {
1717 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1718 return false;
1719 }
1720 } else {
1721 // This may be a permission problem. We could investigate the error code, but we'll just
1722 // let the rename failure do the work for us.
1723 }
1724
1725 // Try to rename "to" to "from."
1726 if (rename(from, to) != 0) {
1727 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1728 return false;
1729 }
1730 return true;
1731}
1732
1733// Move/rename a B artifact (from) to an A artifact (to).
1734static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1735 // Check whether B exists.
1736 {
1737 struct stat s;
1738 if (stat(b_path.c_str(), &s) != 0) {
1739 // Silently ignore for now. The service calling this isn't smart enough to understand
1740 // lack of artifacts at the moment.
1741 return false;
1742 }
1743 if (!S_ISREG(s.st_mode)) {
1744 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1745 // Try to unlink, but swallow errors.
1746 unlink(b_path.c_str());
1747 return false;
1748 }
1749 }
1750
1751 // Rename B to A.
1752 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1753 // Delete the b_path so we don't try again (or fail earlier).
1754 if (unlink(b_path.c_str()) != 0) {
1755 PLOG(ERROR) << "Could not unlink " << b_path;
1756 }
1757
1758 return false;
1759 }
1760
1761 return true;
1762}
1763
1764bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1765 // Get the current slot suffix. No suffix, no A/B.
1766 std::string slot_suffix;
1767 {
1768 char buf[kPropertyValueMax];
1769 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1770 return false;
1771 }
1772 slot_suffix = buf;
1773
1774 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1775 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1776 return false;
1777 }
1778 }
1779
1780 // Validate other inputs.
1781 if (validate_apk_path(apk_path) != 0) {
1782 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1783 return false;
1784 }
1785 if (validate_apk_path(oat_dir) != 0) {
1786 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1787 return false;
1788 }
1789
1790 char a_path[PKG_PATH_MAX];
1791 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1792 return false;
1793 }
1794 const std::string a_vdex_path = create_vdex_filename(a_path);
1795 const std::string a_image_path = create_image_filename(a_path);
1796
1797 // B path = A path + slot suffix.
1798 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1799 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1800 const std::string b_image_path = StringPrintf("%s.%s",
1801 a_image_path.c_str(),
1802 slot_suffix.c_str());
1803
1804 bool success = true;
1805 if (move_ab_path(b_path, a_path)) {
1806 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1807 // Note: we can live without an app image. As such, ignore failure to move the image file.
1808 // If we decide to require the app image, or the app image being moved correctly,
1809 // then change accordingly.
1810 constexpr bool kIgnoreAppImageFailure = true;
1811
1812 if (!a_image_path.empty()) {
1813 if (!move_ab_path(b_image_path, a_image_path)) {
1814 unlink(a_image_path.c_str());
1815 if (!kIgnoreAppImageFailure) {
1816 success = false;
1817 }
1818 }
1819 }
1820 } else {
1821 // Cleanup: delete B image, ignore errors.
1822 unlink(b_image_path.c_str());
1823 success = false;
1824 }
1825 } else {
1826 // Cleanup: delete B image, ignore errors.
1827 unlink(b_vdex_path.c_str());
1828 unlink(b_image_path.c_str());
1829 success = false;
1830 }
1831 return success;
1832}
1833
1834bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1835 // Delete the oat/odex file.
1836 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001837 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001838 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001839 return false;
1840 }
1841
1842 // In case of a permission failure report the issue. Otherwise just print a warning.
1843 auto unlink_and_check = [](const char* path) -> bool {
1844 int result = unlink(path);
1845 if (result != 0) {
1846 if (errno == EACCES || errno == EPERM) {
1847 PLOG(ERROR) << "Could not unlink " << path;
1848 return false;
1849 }
1850 PLOG(WARNING) << "Could not unlink " << path;
1851 }
1852 return true;
1853 };
1854
1855 // Delete the oat/odex file.
1856 bool return_value_oat = unlink_and_check(out_path);
1857
1858 // Derive and delete the app image.
1859 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1860
1861 // Report success.
1862 return return_value_oat && return_value_art;
1863}
1864
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001865int dexopt(const char* const params[DEXOPT_PARAM_COUNT]) {
1866 return dexopt(params[0], // apk_path
1867 atoi(params[1]), // uid
1868 params[2], // pkgname
1869 params[3], // instruction_set
1870 atoi(params[4]), // dexopt_needed
1871 params[5], // oat_dir
1872 atoi(params[6]), // dexopt_flags
1873 params[7], // compiler_filter
1874 parse_null(params[8]), // volume_uuid
1875 parse_null(params[9])); // shared_libraries
1876 static_assert(DEXOPT_PARAM_COUNT == 10U, "Unexpected dexopt param count");
1877}
1878
1879} // namespace installd
1880} // namespace android