blob: 685fdd8180c6a236db657390717a8a28daef1a2f [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 Hao10b8a6e2017-04-05 17:11:39 -0700180static const char* get_location_from_path(const char* path) {
181 static constexpr char kLocationSeparator = '/';
182 const char *location = strrchr(path, kLocationSeparator);
183 if (location == NULL) {
184 return path;
185 } else {
186 // Skip the separator character.
187 return location + 1;
188 }
189}
190
Jeff Sharkey90aff262016-12-12 14:28:24 -0700191static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
192 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100193 const char* instruction_set, const char* compiler_filter,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700194 bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
195 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
196
197 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
198 ALOGE("Instruction set %s longer than max length of %d",
199 instruction_set, MAX_INSTRUCTION_SET_LEN);
200 return;
201 }
202
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700203 // Get the relative path to the input file.
204 const char* relative_input_file_name = get_location_from_path(input_file_name);
205
Jeff Sharkey90aff262016-12-12 14:28:24 -0700206 char dex2oat_Xms_flag[kPropertyValueMax];
207 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
208
209 char dex2oat_Xmx_flag[kPropertyValueMax];
210 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
211
212 char dex2oat_threads_buf[kPropertyValueMax];
213 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
214 ? "dalvik.vm.dex2oat-threads"
215 : "dalvik.vm.boot-dex2oat-threads",
216 dex2oat_threads_buf,
217 NULL) > 0;
218 char dex2oat_threads_arg[kPropertyValueMax + 2];
219 if (have_dex2oat_threads_flag) {
220 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
221 }
222
223 char dex2oat_isa_features_key[kPropertyKeyMax];
224 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
225 char dex2oat_isa_features[kPropertyValueMax];
226 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
227 dex2oat_isa_features, NULL) > 0;
228
229 char dex2oat_isa_variant_key[kPropertyKeyMax];
230 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
231 char dex2oat_isa_variant[kPropertyValueMax];
232 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
233 dex2oat_isa_variant, NULL) > 0;
234
235 const char *dex2oat_norelocation = "-Xnorelocate";
236 bool have_dex2oat_relocation_skip_flag = false;
237
238 char dex2oat_flags[kPropertyValueMax];
239 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
240 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
241 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
242
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100243 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700244 char vold_decrypt[kPropertyValueMax];
245 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
246 bool skip_compilation = (have_vold_decrypt &&
247 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
248 (strcmp(vold_decrypt, "1") == 0)));
249
250 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
251
252 char app_image_format[kPropertyValueMax];
253 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
254 bool have_app_image_format =
255 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
256 if (have_app_image_format) {
257 sprintf(image_format_arg, "--image-format=%s", app_image_format);
258 }
259
260 char dex2oat_large_app_threshold[kPropertyValueMax];
261 bool have_dex2oat_large_app_threshold =
262 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
263 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
264 if (have_dex2oat_large_app_threshold) {
265 sprintf(dex2oat_large_app_threshold_arg,
266 "--very-large-app-threshold=%s",
267 dex2oat_large_app_threshold);
268 }
269
270 static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
271
272 static const char* RUNTIME_ARG = "--runtime-arg";
273
274 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
275
George Burgess IV36cebe772017-01-25 11:52:01 -0800276 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
277 // use arraysize instead.
278 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
279 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
280 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
281 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
282 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
283 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
284 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
285 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
286 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
287 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
288 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
289 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700290 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800291 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700292 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800293 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700294
295 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700296 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700297 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
298 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
299 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
300 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
301 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
302 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
303 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
304 if (swap_fd >= 0) {
305 have_dex2oat_swap_fd = true;
306 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
307 }
308 if (image_fd >= 0) {
309 have_dex2oat_image_fd = true;
310 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
311 }
312
313 if (have_dex2oat_Xms_flag) {
314 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
315 }
316 if (have_dex2oat_Xmx_flag) {
317 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
318 }
319
320 // Compute compiler filter.
321
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100322 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700323 if (skip_compilation) {
Nicolas Geoffray4b64ed92017-04-25 12:28:28 +0100324 strcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract");
Jeff Sharkey90aff262016-12-12 14:28:24 -0700325 have_dex2oat_compiler_filter_flag = true;
326 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100327 } else if (compiler_filter != nullptr) {
328 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700329 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100330 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
331 have_dex2oat_compiler_filter_flag = true;
332 } else {
333 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
334 compiler_filter,
335 kPropertyValueMax);
336 }
337 }
338
339 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340 char dex2oat_compiler_filter_flag[kPropertyValueMax];
341 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
342 dex2oat_compiler_filter_flag, NULL) > 0;
343 if (have_dex2oat_compiler_filter_flag) {
344 sprintf(dex2oat_compiler_filter_arg,
345 "--compiler-filter=%s",
346 dex2oat_compiler_filter_flag);
347 }
348 }
349
350 // Check whether all apps should be compiled debuggable.
351 if (!debuggable) {
352 char prop_buf[kPropertyValueMax];
353 debuggable =
354 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
355 (prop_buf[0] == '1');
356 }
357 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
358 if (profile_fd != -1) {
359 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
360 }
361
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700362 // Get the directory of the apk to pass as a base classpath directory.
363 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
364 std::string apk_dir(input_file_name);
365 unsigned long dir_index = apk_dir.rfind('/');
366 bool has_base_dir = dir_index != std::string::npos;
367 if (has_base_dir) {
368 apk_dir = apk_dir.substr(0, dir_index);
369 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
370 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700371
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700372
373 ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700374
375 const char* argv[9 // program name, mandatory arguments and the final NULL
376 + (have_dex2oat_isa_variant ? 1 : 0)
377 + (have_dex2oat_isa_features ? 1 : 0)
378 + (have_dex2oat_Xms_flag ? 2 : 0)
379 + (have_dex2oat_Xmx_flag ? 2 : 0)
380 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
381 + (have_dex2oat_threads_flag ? 1 : 0)
382 + (have_dex2oat_swap_fd ? 1 : 0)
383 + (have_dex2oat_image_fd ? 1 : 0)
384 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
385 + (generate_debug_info ? 1 : 0)
386 + (debuggable ? 1 : 0)
387 + (have_app_image_format ? 1 : 0)
388 + dex2oat_flags_count
389 + (profile_fd == -1 ? 0 : 1)
390 + (shared_libraries != nullptr ? 4 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700391 + (has_base_dir ? 1 : 0)
Jeff Sharkey90aff262016-12-12 14:28:24 -0700392 + (have_dex2oat_large_app_threshold ? 1 : 0)];
393 int i = 0;
394 argv[i++] = DEX2OAT_BIN;
395 argv[i++] = zip_fd_arg;
396 argv[i++] = zip_location_arg;
397 argv[i++] = input_vdex_fd_arg;
398 argv[i++] = output_vdex_fd_arg;
399 argv[i++] = oat_fd_arg;
400 argv[i++] = oat_location_arg;
401 argv[i++] = instruction_set_arg;
402 if (have_dex2oat_isa_variant) {
403 argv[i++] = instruction_set_variant_arg;
404 }
405 if (have_dex2oat_isa_features) {
406 argv[i++] = instruction_set_features_arg;
407 }
408 if (have_dex2oat_Xms_flag) {
409 argv[i++] = RUNTIME_ARG;
410 argv[i++] = dex2oat_Xms_arg;
411 }
412 if (have_dex2oat_Xmx_flag) {
413 argv[i++] = RUNTIME_ARG;
414 argv[i++] = dex2oat_Xmx_arg;
415 }
416 if (have_dex2oat_compiler_filter_flag) {
417 argv[i++] = dex2oat_compiler_filter_arg;
418 }
419 if (have_dex2oat_threads_flag) {
420 argv[i++] = dex2oat_threads_arg;
421 }
422 if (have_dex2oat_swap_fd) {
423 argv[i++] = dex2oat_swap_fd;
424 }
425 if (have_dex2oat_image_fd) {
426 argv[i++] = dex2oat_image_fd;
427 }
428 if (generate_debug_info) {
429 argv[i++] = "--generate-debug-info";
430 }
431 if (debuggable) {
432 argv[i++] = "--debuggable";
433 }
434 if (have_app_image_format) {
435 argv[i++] = image_format_arg;
436 }
437 if (have_dex2oat_large_app_threshold) {
438 argv[i++] = dex2oat_large_app_threshold_arg;
439 }
440 if (dex2oat_flags_count) {
441 i += split(dex2oat_flags, argv + i);
442 }
443 if (have_dex2oat_relocation_skip_flag) {
444 argv[i++] = RUNTIME_ARG;
445 argv[i++] = dex2oat_norelocation;
446 }
447 if (profile_fd != -1) {
448 argv[i++] = profile_arg;
449 }
450 if (shared_libraries != nullptr) {
451 argv[i++] = RUNTIME_ARG;
452 argv[i++] = "-classpath";
453 argv[i++] = RUNTIME_ARG;
454 argv[i++] = shared_libraries;
455 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700456 if (has_base_dir) {
457 argv[i++] = base_dir;
458 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700459 // Do not add after dex2oat_flags, they should override others for debugging.
460 argv[i] = NULL;
461
462 execv(DEX2OAT_BIN, (char * const *)argv);
463 ALOGE("execv(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
464}
465
466/*
467 * Whether dexopt should use a swap file when compiling an APK.
468 *
469 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
470 * itself, anyways).
471 *
472 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
473 *
474 * Otherwise, return true if this is a low-mem device.
475 *
476 * Otherwise, return default value.
477 */
478static bool kAlwaysProvideSwapFile = false;
479static bool kDefaultProvideSwapFile = true;
480
481static bool ShouldUseSwapFileForDexopt() {
482 if (kAlwaysProvideSwapFile) {
483 return true;
484 }
485
486 // Check the "override" property. If it exists, return value == "true".
487 char dex2oat_prop_buf[kPropertyValueMax];
488 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
489 if (strcmp(dex2oat_prop_buf, "true") == 0) {
490 return true;
491 } else {
492 return false;
493 }
494 }
495
496 // Shortcut for default value. This is an implementation optimization for the process sketched
497 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
498 // as low-mem is never returning false. The compiler will optimize this away if it can.
499 if (kDefaultProvideSwapFile) {
500 return true;
501 }
502
503 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
504 if (is_low_mem) {
505 return true;
506 }
507
508 // Default value must be false here.
509 return kDefaultProvideSwapFile;
510}
511
Richard Uhler76cc0272016-12-08 10:46:35 +0000512static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700513 if (set_to_bg) {
514 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
515 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
516 exit(70);
517 }
518 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
519 ALOGE("setpriority failed: %s\n", strerror(errno));
520 exit(71);
521 }
522 }
523}
524
Calin Juravle114f0812017-03-08 19:05:07 -0800525static bool create_profile(int uid, const std::string& profile) {
526 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), O_CREAT | O_NOFOLLOW, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800527 if (fd.get() < 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800528 if (errno == EEXIST) {
529 return true;
530 } else {
531 PLOG(ERROR) << "Failed to create profile " << profile;
532 return false;
533 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700534 }
Calin Juravle114f0812017-03-08 19:05:07 -0800535 // Profiles should belong to the app; make sure of that by giving ownership to
536 // the app uid. If we cannot do that, there's no point in returning the fd
537 // since dex2oat/profman will fail with SElinux denials.
538 if (fchown(fd.get(), uid, uid) < 0) {
539 PLOG(ERROR) << "Could not chwon profile " << profile;
540 return false;
541 }
542 return true;
543}
544
545static unique_fd open_profile(int uid, const std::string& profile, bool read_write) {
546 // Check if we need to open the profile for a read-write operation. If so, we
547 // might need to create the profile since the file might not be there. Reference
548 // profiles are created on the fly so they might not exist beforehand.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700549 if (read_write) {
Calin Juravle114f0812017-03-08 19:05:07 -0800550 if (!create_profile(uid, profile)) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800551 return invalid_unique_fd();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552 }
553 }
Calin Juravle114f0812017-03-08 19:05:07 -0800554 int flags = read_write ? O_RDWR : O_RDONLY;
555 // Do not follow symlinks when opening a profile:
556 // - primary profiles should not contain symlinks in their paths
557 // - secondary dex paths should have been already resolved and validated
558 flags |= O_NOFOLLOW;
559
560 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
561 if (fd.get() < 0) {
562 if (errno != ENOENT) {
563 // Profiles might be missing for various reasons. For example, in a
564 // multi-user environment, the profile directory for one user can be created
565 // after we start a merge. In this case the current profile for that user
566 // will not be found.
567 // Also, the secondary dex profiles might be deleted by the app at any time,
568 // so we can't we need to prepare if they are missing.
569 PLOG(ERROR) << "Failed to open profile " << profile;
570 }
571 return invalid_unique_fd();
572 }
573
Jeff Sharkey90aff262016-12-12 14:28:24 -0700574 return fd;
575}
576
Calin Juravle114f0812017-03-08 19:05:07 -0800577static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
578 bool is_secondary_dex) {
579 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
580 return open_profile(uid, profile, /*read_write*/false);
581}
582
583static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
584 bool is_secondary_dex) {
585 std::string profile = create_reference_profile_path(location, is_secondary_dex);
586 return open_profile(uid, profile, read_write);
587}
588
589static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800590 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700591 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800592 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
593 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700594
Calin Juravle114f0812017-03-08 19:05:07 -0800595 // For secondary dex files, we don't really need the user but we use it for sanity checks.
596 // Note: the user owning the dex file should be the current user.
597 std::vector<userid_t> users;
598 if (is_secondary_dex){
599 users.push_back(multiuser_get_user_id(uid));
600 } else {
601 users = get_known_users(/*volume_uuid*/ nullptr);
602 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700603 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800604 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700605 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800606 if (profile_fd.get() >= 0) {
607 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700608 }
609 }
610}
611
612static void drop_capabilities(uid_t uid) {
613 if (setgid(uid) != 0) {
614 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
615 exit(64);
616 }
617 if (setuid(uid) != 0) {
618 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
619 exit(65);
620 }
621 // drop capabilities
622 struct __user_cap_header_struct capheader;
623 struct __user_cap_data_struct capdata[2];
624 memset(&capheader, 0, sizeof(capheader));
625 memset(&capdata, 0, sizeof(capdata));
626 capheader.version = _LINUX_CAPABILITY_VERSION_3;
627 if (capset(&capheader, &capdata[0]) < 0) {
628 ALOGE("capset failed: %s\n", strerror(errno));
629 exit(66);
630 }
631}
632
633static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
634static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
635static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
636static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
637static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
638
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800639static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
640 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700641 static const size_t MAX_INT_LEN = 32;
642 static const char* PROFMAN_BIN = "/system/bin/profman";
643
644 std::vector<std::string> profile_args(profiles_fd.size());
645 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
646 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800647 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700648 profile_args[k].assign(profile_buf);
649 }
650 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800651 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700652
653 // program name, reference profile fd, the final NULL and the profile fds
654 const char* argv[3 + profiles_fd.size()];
655 int i = 0;
656 argv[i++] = PROFMAN_BIN;
657 argv[i++] = reference_profile_arg;
658 for (size_t k = 0; k < profile_args.size(); k++) {
659 argv[i++] = profile_args[k].c_str();
660 }
661 // Do not add after dex2oat_flags, they should override others for debugging.
662 argv[i] = NULL;
663
664 execv(PROFMAN_BIN, (char * const *)argv);
665 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
666 exit(68); /* only get here on exec failure */
667}
668
669// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800670// The location is the package name for primary apks or the dex path for secondary dex files.
671// Returns true if there is enough information in the current profiles that makes it
672// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700673// If the return value is true all the current profiles would have been merged into
674// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800675static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800676 std::vector<unique_fd> profiles_fd;
677 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800678 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800679 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700680 // Skip profile guided compilation because no profiles were found.
681 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700682 return false;
683 }
684
Jeff Sharkey90aff262016-12-12 14:28:24 -0700685 pid_t pid = fork();
686 if (pid == 0) {
687 /* child -- drop privileges before continuing */
688 drop_capabilities(uid);
689 run_profman_merge(profiles_fd, reference_profile_fd);
690 exit(68); /* only get here on exec failure */
691 }
692 /* parent */
693 int return_code = wait_child(pid);
694 bool need_to_compile = false;
695 bool should_clear_current_profiles = false;
696 bool should_clear_reference_profile = false;
697 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800698 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700699 } else {
700 return_code = WEXITSTATUS(return_code);
701 switch (return_code) {
702 case PROFMAN_BIN_RETURN_CODE_COMPILE:
703 need_to_compile = true;
704 should_clear_current_profiles = true;
705 should_clear_reference_profile = false;
706 break;
707 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
708 need_to_compile = false;
709 should_clear_current_profiles = false;
710 should_clear_reference_profile = false;
711 break;
712 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800713 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700714 need_to_compile = false;
715 should_clear_current_profiles = true;
716 should_clear_reference_profile = true;
717 break;
718 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
719 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
720 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800721 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700722 need_to_compile = false;
723 should_clear_current_profiles = false;
724 should_clear_reference_profile = false;
725 break;
726 default:
727 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800728 LOG(WARNING) << "Unknown error code while processing profiles for location "
729 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700730 need_to_compile = false;
731 should_clear_current_profiles = true;
732 should_clear_reference_profile = true;
733 break;
734 }
735 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800736
Jeff Sharkey90aff262016-12-12 14:28:24 -0700737 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800738 if (is_secondary_dex) {
739 // For secondary dex files, the owning user is the current user.
740 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
741 } else {
742 clear_primary_current_profiles(location);
743 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700744 }
745 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800746 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700747 }
748 return need_to_compile;
749}
750
Calin Juravle114f0812017-03-08 19:05:07 -0800751// Decides if profile guided compilation is needed or not based on existing profiles.
752// The analysis is done for the primary apks of the given package.
753// Returns true if there is enough information in the current profiles that makes it
754// worth to recompile the package.
755// If the return value is true all the current profiles would have been merged into
756// the reference profiles accessible with open_reference_profile().
757bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
758 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
759}
760
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800761static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
762 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700763 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800764 const std::vector<unique_fd>& apk_fds,
765 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700766 std::vector<std::string> profman_args;
767 static const char* PROFMAN_BIN = "/system/bin/profman";
768 profman_args.push_back(PROFMAN_BIN);
769 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800770 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700771 if (reference_profile_fd != -1) {
772 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800773 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700774 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800775 for (size_t i = 0; i < profile_fds.size(); i++) {
776 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700777 }
778 for (const std::string& dex_location : dex_locations) {
779 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
780 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800781 for (size_t i = 0; i < apk_fds.size(); i++) {
782 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783 }
784 const char **argv = new const char*[profman_args.size() + 1];
785 size_t i = 0;
786 for (const std::string& profman_arg : profman_args) {
787 argv[i++] = profman_arg.c_str();
788 }
789 argv[i] = NULL;
790
791 execv(PROFMAN_BIN, (char * const *)argv);
792 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
793 exit(68); /* only get here on exec failure */
794}
795
Calin Juravle76268c52017-03-09 13:19:42 -0800796bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800797 std::vector<unique_fd> profile_fds;
798 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800799 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800
Calin Juravle114f0812017-03-08 19:05:07 -0800801 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
802 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700803
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800804 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700805 const bool has_profiles = !profile_fds.empty();
806
807 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800808 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700809 return false;
810 }
811
Calin Juravle114f0812017-03-08 19:05:07 -0800812 unique_fd output_fd(open(out_file_name.c_str(),
813 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
815 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
816 return false;
817 }
818 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
819 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800820 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821 for (const std::string& code_full_path : code_full_paths) {
822 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800823 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700824 if (apk_fd == -1) {
825 ALOGE("installd cannot open '%s'\n", full_path);
826 return false;
827 }
828 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800829 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700830 }
831
832 pid_t pid = fork();
833 if (pid == 0) {
834 /* child -- drop privileges before continuing */
835 drop_capabilities(uid);
836 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
837 apk_fds, output_fd);
838 exit(68); /* only get here on exec failure */
839 }
840 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841 int return_code = wait_child(pid);
842 if (!WIFEXITED(return_code)) {
843 LOG(WARNING) << "profman failed for package " << pkgname << ": "
844 << return_code;
845 return false;
846 }
847 return true;
848}
849
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700850bool copy_system_profile(const std::string& system_profile,
851 uid_t packageUid, const std::string& data_profile_location) {
852 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
853 unique_fd out_fd(open_reference_profile(packageUid,
854 data_profile_location,
855 /*read_write*/ true,
856 /*secondary*/ false));
857 if (in_fd.get() < 0) {
858 PLOG(WARNING) << "Could not open profile " << system_profile;
859 return false;
860 }
861 if (out_fd.get() < 0) {
862 PLOG(WARNING) << "Could not open profile " << data_profile_location;
863 return false;
864 }
865
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700866 // As a security measure we want to write the profile information with the reduced capabilities
867 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700868 pid_t pid = fork();
869 if (pid == 0) {
870 /* child -- drop privileges before continuing */
871 drop_capabilities(packageUid);
872
873 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
874 if (errno != EWOULDBLOCK) {
875 PLOG(WARNING) << "Error locking profile " << data_profile_location;
876 }
877 // This implies that the app owning this profile is running
878 // (and has acquired the lock).
879 //
880 // The app never acquires the lock for the reference profiles of primary apks.
881 // Only dex2oat from installd will do that. Since installd is single threaded
882 // we should not see this case. Nevertheless be prepared for it.
883 PLOG(WARNING) << "Failed to flock " << data_profile_location;
884 return false;
885 }
886
887 bool truncated = ftruncate(out_fd.get(), 0) == 0;
888 if (!truncated) {
889 PLOG(WARNING) << "Could not truncate " << data_profile_location;
890 }
891
892 // Copy over data.
893 static constexpr size_t kBufferSize = 4 * 1024;
894 char buffer[kBufferSize];
895 while (true) {
896 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
897 if (bytes == 0) {
898 break;
899 }
900 write(out_fd.get(), buffer, bytes);
901 }
902 if (flock(out_fd.get(), LOCK_UN) != 0) {
903 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
904 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700905 // Use _exit since we don't want to run the global destructors in the child.
906 // b/62597429
907 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700908 }
909 /* parent */
910 int return_code = wait_child(pid);
911 return return_code == 0;
912}
913
Jeff Sharkey90aff262016-12-12 14:28:24 -0700914static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
915 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
916 if (EndsWith(oat_path, ".dex")) {
917 std::string new_path = oat_path;
918 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
919 CHECK(EndsWith(new_path, new_ext.c_str()));
920 return new_path;
921 }
922
923 // An odex entry. Not that this may not be an extension, e.g., in the OTA
924 // case (where the base name will have an extension for the B artifact).
925 size_t odex_pos = oat_path.rfind(".odex");
926 if (odex_pos != std::string::npos) {
927 std::string new_path = oat_path;
928 new_path.replace(odex_pos, strlen(".odex"), new_ext);
929 CHECK_NE(new_path.find(new_ext), std::string::npos);
930 return new_path;
931 }
932
933 // Don't know how to handle this.
934 return "";
935}
936
937// Translate the given oat path to an art (app image) path. An empty string
938// denotes an error.
939static std::string create_image_filename(const std::string& oat_path) {
940 return replace_file_extension(oat_path, ".art");
941}
942
943// Translate the given oat path to a vdex path. An empty string denotes an error.
944static std::string create_vdex_filename(const std::string& oat_path) {
945 return replace_file_extension(oat_path, ".vdex");
946}
947
948static bool add_extension_to_file_name(char* file_name, const char* extension) {
949 if (strlen(file_name) + strlen(extension) + 1 > PKG_PATH_MAX) {
950 return false;
951 }
952 strcat(file_name, extension);
953 return true;
954}
955
956static int open_output_file(const char* file_name, bool recreate, int permissions) {
957 int flags = O_RDWR | O_CREAT;
958 if (recreate) {
959 if (unlink(file_name) < 0) {
960 if (errno != ENOENT) {
961 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
962 }
963 }
964 flags |= O_EXCL;
965 }
966 return open(file_name, flags, permissions);
967}
968
Calin Juravle2289c0a2017-02-15 12:44:14 -0800969static bool set_permissions_and_ownership(
970 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
971 // Primary apks are owned by the system. Secondary dex files are owned by the app.
972 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 if (fchmod(fd,
974 S_IRUSR|S_IWUSR|S_IRGRP |
975 (is_public ? S_IROTH : 0)) < 0) {
976 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
977 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800978 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700979 ALOGE("installd cannot chown '%s' during dexopt\n", path);
980 return false;
981 }
982 return true;
983}
984
985static bool IsOutputDalvikCache(const char* oat_dir) {
986 // InstallerConnection.java (which invokes installd) transforms Java null arguments
987 // into '!'. Play it safe by handling it both.
988 // TODO: ensure we never get null.
989 // TODO: pass a flag instead of inferring if the output is dalvik cache.
990 return oat_dir == nullptr || oat_dir[0] == '!';
991}
992
Calin Juravled23dee72017-07-06 16:29:11 -0700993// Best-effort check whether we can fit the the path into our buffers.
994// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
995// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
996// extension to the cache path (5 bytes).
997// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
998static bool validate_dex_path_size(const std::string& dex_path) {
999 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1000 LOG(ERROR) << "dex_path too long: " << dex_path;
1001 return false;
1002 }
1003 return true;
1004}
1005
Jeff Sharkey90aff262016-12-12 14:28:24 -07001006static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001007 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001008 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001009 return false;
1010 }
1011
1012 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001013 // Oat dirs for secondary dex files are already validated.
1014 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001015 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1016 return false;
1017 }
1018 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1019 return false;
1020 }
1021 } else {
1022 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1023 return false;
1024 }
1025 }
1026 return true;
1027}
1028
1029// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1030// on destruction. It will also run the given cleanup (unless told not to) after closing.
1031//
1032// Usage example:
1033//
Calin Juravle7a570e82017-01-14 16:23:30 -08001034// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001035// [name]() {
1036// unlink(name.c_str());
1037// });
1038// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1039// wrapper if captured as a reference.
1040//
1041// if (file.get() == -1) {
1042// // Error opening...
1043// }
1044//
1045// ...
1046// if (error) {
1047// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1048// // and delete the file (after the fd is closed).
1049// return -1;
1050// }
1051//
1052// (Success case)
1053// file.SetCleanup(false);
1054// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1055// // (leaving the file around; after the fd is closed).
1056//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001057class Dex2oatFileWrapper {
1058 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001059 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001060 }
1061
Calin Juravle7a570e82017-01-14 16:23:30 -08001062 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1063 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1064
1065 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1066 value_ = other.value_;
1067 cleanup_ = other.cleanup_;
1068 do_cleanup_ = other.do_cleanup_;
1069 auto_close_ = other.auto_close_;
1070 other.release();
1071 }
1072
1073 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1074 value_ = other.value_;
1075 cleanup_ = other.cleanup_;
1076 do_cleanup_ = other.do_cleanup_;
1077 auto_close_ = other.auto_close_;
1078 other.release();
1079 return *this;
1080 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001081
1082 ~Dex2oatFileWrapper() {
1083 reset(-1);
1084 }
1085
1086 int get() {
1087 return value_;
1088 }
1089
1090 void SetCleanup(bool cleanup) {
1091 do_cleanup_ = cleanup;
1092 }
1093
1094 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001095 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001096 close(value_);
1097 }
1098 if (do_cleanup_ && cleanup_ != nullptr) {
1099 cleanup_();
1100 }
1101
1102 value_ = new_value;
1103 }
1104
Calin Juravle7a570e82017-01-14 16:23:30 -08001105 void reset(int new_value, std::function<void ()> new_cleanup) {
1106 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001107 close(value_);
1108 }
1109 if (do_cleanup_ && cleanup_ != nullptr) {
1110 cleanup_();
1111 }
1112
1113 value_ = new_value;
1114 cleanup_ = new_cleanup;
1115 }
1116
Calin Juravle7a570e82017-01-14 16:23:30 -08001117 void DisableAutoClose() {
1118 auto_close_ = false;
1119 }
1120
Jeff Sharkey90aff262016-12-12 14:28:24 -07001121 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001122 void release() {
1123 value_ = -1;
1124 do_cleanup_ = false;
1125 cleanup_ = nullptr;
1126 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001128 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001129 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001130 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131};
1132
Calin Juravle7a570e82017-01-14 16:23:30 -08001133// (re)Creates the app image if needed.
1134Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001135 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001136 // Use app images only if it is enabled (by a set image format) and we are compiling
1137 // profile-guided (so the app image doesn't conservatively contain all classes).
Calin Juravle2289c0a2017-02-15 12:44:14 -08001138 // Note that we don't create an image for secondary dex files.
1139 if (is_secondary_dex || !profile_guided) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 return Dex2oatFileWrapper();
1141 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001142
Calin Juravle7a570e82017-01-14 16:23:30 -08001143 const std::string image_path = create_image_filename(out_oat_path);
1144 if (image_path.empty()) {
1145 // Happens when the out_oat_path has an unknown extension.
1146 return Dex2oatFileWrapper();
1147 }
1148 char app_image_format[kPropertyValueMax];
1149 bool have_app_image_format =
1150 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1151 if (!have_app_image_format) {
1152 return Dex2oatFileWrapper();
1153 }
1154 // Recreate is true since we do not want to modify a mapped image. If the app is
1155 // already running and we modify the image file, it can cause crashes (b/27493510).
1156 Dex2oatFileWrapper wrapper_fd(
1157 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1158 [image_path]() { unlink(image_path.c_str()); });
1159 if (wrapper_fd.get() < 0) {
1160 // Could not create application image file. Go on since we can compile without it.
1161 LOG(ERROR) << "installd could not create '" << image_path
1162 << "' for image file during dexopt";
1163 // If we have a valid image file path but no image fd, explicitly erase the image file.
1164 if (unlink(image_path.c_str()) < 0) {
1165 if (errno != ENOENT) {
1166 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1167 }
1168 }
1169 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001170 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001171 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1172 wrapper_fd.reset(-1);
1173 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001174
Calin Juravle7a570e82017-01-14 16:23:30 -08001175 return wrapper_fd;
1176}
1177
1178// Creates the dexopt swap file if necessary and return its fd.
1179// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001180unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001181 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001182 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001183 }
1184 // Make sure there really is enough space.
1185 char swap_file_name[PKG_PATH_MAX];
1186 strcpy(swap_file_name, out_oat_path);
1187 if (!add_extension_to_file_name(swap_file_name, ".swap")) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001188 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001189 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001190 unique_fd swap_fd(open_output_file(
Calin Juravle7a570e82017-01-14 16:23:30 -08001191 swap_file_name, /*recreate*/true, /*permissions*/0600));
1192 if (swap_fd.get() < 0) {
1193 // Could not create swap file. Optimistically go on and hope that we can compile
1194 // without it.
1195 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
1196 } else {
1197 // Immediately unlink. We don't really want to hit flash.
1198 if (unlink(swap_file_name) < 0) {
1199 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1200 }
1201 }
1202 return swap_fd;
1203}
1204
1205// Opens the reference profiles if needed.
1206// 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 -08001207Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1208 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1209 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001210 // Public apps should not be compiled with profile information ever. Same goes for the special
1211 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001212 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001214 }
Calin Juravle114f0812017-03-08 19:05:07 -08001215
1216 // Open reference profile in read only mode as dex2oat does not get write permissions.
1217 const std::string location = is_secondary_dex ? dex_path : pkgname;
1218 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1219 const auto& cleanup = [location, is_secondary_dex]() {
1220 clear_reference_profile(location.c_str(), is_secondary_dex);
1221 };
1222 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001223}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001224
Calin Juravle7a570e82017-01-14 16:23:30 -08001225// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1226// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1227bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001228 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001229 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001230 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1231 CHECK(in_vdex_wrapper_fd != nullptr);
1232 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001233 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1234 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001235 char in_odex_path[PKG_PATH_MAX];
1236 int dexopt_action = abs(dexopt_needed);
1237 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001238 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001239
1240 // Infer the name of the output VDEX.
1241 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1242 if (out_vdex_path_str.empty()) {
1243 return false;
1244 }
1245
1246 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001247 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001248 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1249 const char* path = nullptr;
1250 if (is_odex_location) {
1251 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1252 path = in_odex_path;
1253 } else {
1254 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001255 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001256 }
1257 } else {
1258 path = out_oat_path;
1259 }
1260 in_vdex_path_str = create_vdex_filename(path);
1261 if (in_vdex_path_str.empty()) {
1262 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001263 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001264 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001265 // We can update in place when all these conditions are met:
1266 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1267 // on /system typically cannot be updated in place).
1268 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1269 // cannot be currently used by a running process.
1270 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1271 // different vdex files to operate.
1272 update_vdex_in_place =
1273 (in_vdex_path_str == out_vdex_path_str) &&
1274 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1275 !profile_guided;
1276 if (update_vdex_in_place) {
1277 // Open the file read-write to be able to update it.
1278 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1279 if (in_vdex_wrapper_fd->get() == -1) {
1280 // If we failed to open the file, we cannot update it in place.
1281 update_vdex_in_place = false;
1282 }
1283 } else {
1284 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1285 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001286 }
1287
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001288 // If we are updating the vdex in place, we do not need to recreate a vdex,
1289 // and can use the same existing one.
1290 if (update_vdex_in_place) {
1291 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1292 // have bogus stale vdex files.
1293 out_vdex_wrapper_fd->reset(
1294 in_vdex_wrapper_fd->get(),
1295 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1296 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1297 // wrapper).
1298 in_vdex_wrapper_fd->DisableAutoClose();
1299 } else {
1300 out_vdex_wrapper_fd->reset(
1301 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1302 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1303 if (out_vdex_wrapper_fd->get() < 0) {
1304 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1305 return false;
1306 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001307 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001308 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001309 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001310 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1311 return false;
1312 }
1313
1314 // If we got here we successfully opened the vdex files.
1315 return true;
1316}
1317
1318// Opens the output oat file for the given apk.
1319// If successful it stores the output path into out_oat_path and returns true.
1320Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001321 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1322 char* out_oat_path) {
1323 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001324 return Dex2oatFileWrapper();
1325 }
1326 const std::string out_oat_path_str(out_oat_path);
1327 Dex2oatFileWrapper wrapper_fd(
1328 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1329 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1330 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001331 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001332 } else if (!set_permissions_and_ownership(
1333 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001334 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1335 wrapper_fd.reset(-1);
1336 }
1337 return wrapper_fd;
1338}
1339
1340// Updates the access times of out_oat_path based on those from apk_path.
1341void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1342 struct stat input_stat;
1343 memset(&input_stat, 0, sizeof(input_stat));
1344 if (stat(apk_path, &input_stat) != 0) {
1345 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1346 return;
1347 }
1348
1349 struct utimbuf ut;
1350 ut.actime = input_stat.st_atime;
1351 ut.modtime = input_stat.st_mtime;
1352 if (utime(out_oat_path, &ut) != 0) {
1353 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1354 }
1355}
1356
Calin Juravle80a21252017-01-17 14:43:25 -08001357// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001358// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1359// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1360// the profile has changed.
Calin Juravled23dee72017-07-06 16:29:11 -07001361static void exec_dexoptanalyzer(const std::string& dex_file, const std::string& instruction_set,
1362 const std::string& compiler_filter, bool profile_was_updated) {
Calin Juravle80a21252017-01-17 14:43:25 -08001363 static const char* DEXOPTANALYZER_BIN = "/system/bin/dexoptanalyzer";
1364 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1365
Calin Juravled23dee72017-07-06 16:29:11 -07001366 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1367 LOG(ERROR) << "Instruction set " << instruction_set
1368 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001369 return;
1370 }
1371
Calin Juravled23dee72017-07-06 16:29:11 -07001372 std::string dex_file_arg = "--dex-file=" + dex_file;
1373 std::string isa_arg = "--isa=" + instruction_set;
1374 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001375 const char* assume_profile_changed = "--assume-profile-changed";
Calin Juravle80a21252017-01-17 14:43:25 -08001376
Calin Juravle80a21252017-01-17 14:43:25 -08001377 // program name, dex file, isa, filter, the final NULL
Calin Juravle114f0812017-03-08 19:05:07 -08001378 const char* argv[5 + (profile_was_updated ? 1 : 0)];
Calin Juravle80a21252017-01-17 14:43:25 -08001379 int i = 0;
1380 argv[i++] = DEXOPTANALYZER_BIN;
Calin Juravled23dee72017-07-06 16:29:11 -07001381 argv[i++] = dex_file_arg.c_str();
1382 argv[i++] = isa_arg.c_str();
1383 argv[i++] = compiler_filter_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001384 if (profile_was_updated) {
1385 argv[i++] = assume_profile_changed;
1386 }
Calin Juravle80a21252017-01-17 14:43:25 -08001387 argv[i] = NULL;
1388
1389 execv(DEXOPTANALYZER_BIN, (char * const *)argv);
1390 ALOGE("execv(%s) failed: %s\n", DEXOPTANALYZER_BIN, strerror(errno));
1391}
1392
1393// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001394static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1395 const char* instruction_set, std::string* oat_dir_out) {
1396 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001397 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001398 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001399 return false;
1400 }
Calin Juravle114f0812017-03-08 19:05:07 -08001401 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001402
Calin Juravle80a21252017-01-17 14:43:25 -08001403 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001404 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1405 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001406 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001407 return false;
1408 }
1409
1410 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001411 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001412 oat_dir_out->assign(oat_dir);
1413
1414 // Create oat/isa output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001415 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001416 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001417 return false;
1418 }
1419
1420 return true;
1421}
1422
1423static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1424
1425// Verifies the result of dexoptanalyzer executed for the apk_path.
1426// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1427// Returns false for errors or unexpected result values.
Calin Juravle114f0812017-03-08 19:05:07 -08001428static bool process_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001429 int* dexopt_needed_out) {
1430 // The result values are defined in dexoptanalyzer.
1431 switch (result) {
1432 case 0: // no_dexopt_needed
1433 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1434 case 1: // dex2oat_from_scratch
1435 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1436 case 5: // dex2oat_for_bootimage_odex
1437 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1438 case 6: // dex2oat_for_filter_odex
1439 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1440 case 7: // dex2oat_for_relocation_odex
1441 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1442 case 2: // dex2oat_for_bootimage_oat
1443 case 3: // dex2oat_for_filter_oat
1444 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001445 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1446 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001447 << " : dexoptanalyzer result=" << result;
1448 return false;
1449 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001450 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001451 << " exec_dexoptanalyzer result=" << result;
1452 return false;
1453 }
1454}
1455
Calin Juravlec9eab382017-01-25 01:17:17 -08001456// 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 -08001457// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1458// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001459// When returning true, the output parameters will be:
1460// - is_public_out: whether or not the oat file should not be made public
1461// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1462// - oat_dir_out: the oat dir path where the oat file should be stored
1463// - dex_path_out: the real path of the dex file
Calin Juravle114f0812017-03-08 19:05:07 -08001464static bool process_secondary_dex_dexopt(const char* original_dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001465 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001466 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
1467 std::string* oat_dir_out, std::string* dex_path_out) {
Calin Juravle80a21252017-01-17 14:43:25 -08001468 int storage_flag;
1469
1470 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1471 storage_flag = FLAG_STORAGE_CE;
1472 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1473 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1474 return false;
1475 }
1476 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1477 storage_flag = FLAG_STORAGE_DE;
1478 } else {
1479 LOG(ERROR) << "Secondary dex storage flag must be set";
1480 return false;
1481 }
1482
Calin Juravle114f0812017-03-08 19:05:07 -08001483 {
1484 // As opposed to the primary apk, secondary dex files might contain symlinks.
1485 // Resolve the path before passing it to the validate method to
1486 // make sure the verification is done on the real location.
1487 UniqueCPtr<char> dex_real_path_cstr(realpath(original_dex_path, nullptr));
1488 if (dex_real_path_cstr == nullptr) {
1489 PLOG(ERROR) << "Could not get the real path of the secondary dex file "
1490 << original_dex_path;
1491 return false;
1492 } else {
1493 dex_path_out->assign(dex_real_path_cstr.get());
1494 }
1495 }
1496 const std::string& dex_path = *dex_path_out;
Calin Juravled23dee72017-07-06 16:29:11 -07001497 if (!validate_dex_path_size(dex_path)) {
1498 return false;
1499 }
Calin Juravlec9eab382017-01-25 01:17:17 -08001500 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1501 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001502 return false;
1503 }
1504
1505 // Check if the path exist. If not, there's nothing to do.
Calin Juravleebc8a792017-04-04 20:21:05 -07001506 struct stat dex_path_stat;
1507 if (stat(dex_path.c_str(), &dex_path_stat) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001508 if (errno == ENOENT) {
1509 // Secondary dex files might be deleted any time by the app.
1510 // Nothing to do if that's the case
Calin Juravle114f0812017-03-08 19:05:07 -08001511 ALOGV("Secondary dex does not exist %s", dex_path.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001512 return NO_DEXOPT_NEEDED;
1513 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001514 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001515 }
1516 }
1517
Calin Juravleebc8a792017-04-04 20:21:05 -07001518 // Check if we should make the oat file public.
1519 // Note that if the dex file is not public the compiled code cannot be made public.
1520 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) &&
1521 ((dex_path_stat.st_mode & S_IROTH) != 0);
1522
Calin Juravle80a21252017-01-17 14:43:25 -08001523 // Prepare the oat directories.
Calin Juravle114f0812017-03-08 19:05:07 -08001524 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, oat_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001525 return false;
1526 }
1527
Calin Juravle114f0812017-03-08 19:05:07 -08001528 // Analyze profiles.
1529 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1530
Calin Juravle80a21252017-01-17 14:43:25 -08001531 pid_t pid = fork();
1532 if (pid == 0) {
1533 // child -- drop privileges before continuing.
1534 drop_capabilities(uid);
1535 // Run dexoptanalyzer to get dexopt_needed code.
Calin Juravle114f0812017-03-08 19:05:07 -08001536 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter, profile_was_updated);
Calin Juravle80a21252017-01-17 14:43:25 -08001537 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1538 }
1539
1540 /* parent */
1541
1542 int result = wait_child(pid);
1543 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001544 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001545 return false;
1546 }
1547 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001548 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001549 // Run dexopt only if needed or forced.
1550 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1551 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1552 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1553 // for oat files from dalvik-cache.
1554 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1555 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1556 }
1557
1558 return success;
1559}
1560
Calin Juravlec9eab382017-01-25 01:17:17 -08001561int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001562 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravlecb556e32017-04-04 20:22:50 -07001563 const char* volume_uuid, const char* shared_libraries, const char* se_info) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001564 CHECK(pkgname != nullptr);
1565 CHECK(pkgname[0] != 0);
1566 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1567 LOG_FATAL("dexopt flags contains unknown fields\n");
1568 }
1569
Calin Juravled23dee72017-07-06 16:29:11 -07001570 if (!validate_dex_path_size(dex_path)) {
1571 return false;
1572 }
1573
Calin Juravleebc8a792017-04-04 20:21:05 -07001574 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001575 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1576 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1577 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001578 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1579
1580 // Check if we're dealing with a secondary dex file and if we need to compile it.
1581 std::string oat_dir_str;
Calin Juravle114f0812017-03-08 19:05:07 -08001582 std::string dex_real_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001583 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001584 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001585 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
1586 &dex_real_path)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001587 oat_dir = oat_dir_str.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001588 dex_path = dex_real_path.c_str();
Calin Juravle80a21252017-01-17 14:43:25 -08001589 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1590 return 0; // Nothing to do, report success.
1591 }
1592 } else {
1593 return -1; // We had an error, logged in the process method.
1594 }
1595 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001596 // Currently these flags are only use for secondary dex files.
1597 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001598 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1599 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1600 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001601
1602 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001603 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001604 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001605 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001606 return -1;
1607 }
1608
1609 // Create the output OAT file.
1610 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001611 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001612 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001613 if (out_oat_fd.get() < 0) {
1614 return -1;
1615 }
1616
1617 // Open vdex files.
1618 Dex2oatFileWrapper in_vdex_fd;
1619 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001620 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001621 is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001622 return -1;
1623 }
1624
Calin Juravlecb556e32017-04-04 20:22:50 -07001625 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1626 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1627 // fully inherit their parent context).
1628 // Note that for primary apk the oat files are created before, in a separate installd
1629 // call which also does the restorecon. TODO(calin): unify the paths.
1630 if (is_secondary_dex) {
1631 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1632 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1633 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1634 return -1;
1635 }
1636 }
1637
Jeff Sharkey90aff262016-12-12 14:28:24 -07001638 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001639 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001640
Calin Juravle7a570e82017-01-14 16:23:30 -08001641 // Create the app image file if needed.
1642 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001643 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001644
Calin Juravle7a570e82017-01-14 16:23:30 -08001645 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001646 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1647 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001648
Calin Juravlec9eab382017-01-25 01:17:17 -08001649 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001650
1651 pid_t pid = fork();
1652 if (pid == 0) {
1653 /* child -- drop privileges before continuing */
1654 drop_capabilities(uid);
1655
Richard Uhler76cc0272016-12-08 10:46:35 +00001656 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001657 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1658 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1659 _exit(67);
1660 }
1661
Richard Uhler76cc0272016-12-08 10:46:35 +00001662 run_dex2oat(input_fd.get(),
1663 out_oat_fd.get(),
1664 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001665 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001666 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001667 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001668 out_oat_path,
1669 swap_fd.get(),
1670 instruction_set,
1671 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001672 debuggable,
1673 boot_complete,
1674 reference_profile_fd.get(),
1675 shared_libraries);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001676 _exit(68); /* only get here on exec failure */
1677 } else {
1678 int res = wait_child(pid);
1679 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001680 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001681 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001682 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001683 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001684 }
1685 }
1686
Calin Juravlec9eab382017-01-25 01:17:17 -08001687 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001688
1689 // We've been successful, don't delete output.
1690 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001691 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001692 image_fd.SetCleanup(false);
1693 reference_profile_fd.SetCleanup(false);
1694
1695 return 0;
1696}
1697
Calin Juravlec9eab382017-01-25 01:17:17 -08001698// Try to remove the given directory. Log an error if the directory exists
1699// and is empty but could not be removed.
1700static bool rmdir_if_empty(const char* dir) {
1701 if (rmdir(dir) == 0) {
1702 return true;
1703 }
1704 if (errno == ENOENT || errno == ENOTEMPTY) {
1705 return true;
1706 }
1707 PLOG(ERROR) << "Failed to remove dir: " << dir;
1708 return false;
1709}
1710
1711// Try to unlink the given file. Log an error if the file exists and could not
1712// be unlinked.
1713static bool unlink_if_exists(const std::string& file) {
1714 if (unlink(file.c_str()) == 0) {
1715 return true;
1716 }
1717 if (errno == ENOENT) {
1718 return true;
1719
1720 }
1721 PLOG(ERROR) << "Could not unlink: " << file;
1722 return false;
1723}
1724
1725// Create the oat file structure for the secondary dex 'dex_path' and assign
1726// the individual path component to the 'out_' parameters.
1727static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1728 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1729 size_t dirIndex = dex_path.rfind('/');
1730 if (dirIndex == std::string::npos) {
1731 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1732 return false;
1733 }
1734 // TODO(calin): we have similar computations in at lest 3 other places
1735 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1736 // use string append.
1737 std::string apk_dir = dex_path.substr(0, dirIndex);
1738 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1739 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1740
1741 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001742 /*is_secondary_dex*/true, out_oat_path)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001743 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1744 return false;
1745 }
1746 return true;
1747}
1748
1749// Reconcile the secondary dex 'dex_path' and its generated oat files.
1750// Return true if all the parameters are valid and the secondary dex file was
1751// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1752// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1753// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1754// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1755// Return false if there were errors during processing. In this case
1756// out_secondary_dex_exists will be set to false.
1757bool reconcile_secondary_dex_file(const std::string& dex_path,
1758 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1759 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1760 /*out*/bool* out_secondary_dex_exists) {
1761 // Set out to false to start with, just in case we have validation errors.
1762 *out_secondary_dex_exists = false;
Calin Juravled23dee72017-07-06 16:29:11 -07001763 if (!validate_dex_path_size(dex_path)) {
1764 return false;
1765 }
1766
Calin Juravlec9eab382017-01-25 01:17:17 -08001767 if (isas.size() == 0) {
1768 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1769 return false;
1770 }
1771
1772 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1773 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1774 uid, storage_flag)) {
1775 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1776 return false;
1777 }
1778
1779 if (access(dex_path.c_str(), F_OK) == 0) {
1780 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1781 *out_secondary_dex_exists = true;
1782 return true;
1783 } else if (errno != ENOENT) {
1784 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1785 return false;
1786 }
1787
1788 // The secondary dex does not exist anymore. Clear any generated files.
1789 char oat_path[PKG_PATH_MAX];
1790 char oat_dir[PKG_PATH_MAX];
1791 char oat_isa_dir[PKG_PATH_MAX];
1792 bool result = true;
1793 for (size_t i = 0; i < isas.size(); i++) {
1794 if (!create_secondary_dex_oat_layout(dex_path, isas[i], oat_dir, oat_isa_dir, oat_path)) {
1795 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1796 result = false;
1797 continue;
1798 }
Calin Juravle51314092017-05-18 15:33:05 -07001799
1800 // Delete oat/vdex/art files.
Calin Juravlec9eab382017-01-25 01:17:17 -08001801 result = unlink_if_exists(oat_path) && result;
1802 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1803 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1804
Calin Juravle51314092017-05-18 15:33:05 -07001805 // Delete profiles.
1806 std::string current_profile = create_current_profile_path(
1807 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
1808 std::string reference_profile = create_reference_profile_path(
1809 dex_path, /*is_secondary*/true);
1810 result = unlink_if_exists(current_profile) && result;
1811 result = unlink_if_exists(reference_profile) && result;
1812
Calin Juravlec9eab382017-01-25 01:17:17 -08001813 // Try removing the directories as well, they might be empty.
1814 result = rmdir_if_empty(oat_isa_dir) && result;
1815 result = rmdir_if_empty(oat_dir) && result;
1816 }
1817
1818 return result;
1819}
1820
Jeff Sharkey90aff262016-12-12 14:28:24 -07001821// Helper for move_ab, so that we can have common failure-case cleanup.
1822static bool unlink_and_rename(const char* from, const char* to) {
1823 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1824 // return a failure.
1825 struct stat s;
1826 if (stat(to, &s) == 0) {
1827 if (!S_ISREG(s.st_mode)) {
1828 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1829 return false;
1830 }
1831 if (unlink(to) != 0) {
1832 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1833 return false;
1834 }
1835 } else {
1836 // This may be a permission problem. We could investigate the error code, but we'll just
1837 // let the rename failure do the work for us.
1838 }
1839
1840 // Try to rename "to" to "from."
1841 if (rename(from, to) != 0) {
1842 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1843 return false;
1844 }
1845 return true;
1846}
1847
1848// Move/rename a B artifact (from) to an A artifact (to).
1849static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1850 // Check whether B exists.
1851 {
1852 struct stat s;
1853 if (stat(b_path.c_str(), &s) != 0) {
1854 // Silently ignore for now. The service calling this isn't smart enough to understand
1855 // lack of artifacts at the moment.
1856 return false;
1857 }
1858 if (!S_ISREG(s.st_mode)) {
1859 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1860 // Try to unlink, but swallow errors.
1861 unlink(b_path.c_str());
1862 return false;
1863 }
1864 }
1865
1866 // Rename B to A.
1867 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1868 // Delete the b_path so we don't try again (or fail earlier).
1869 if (unlink(b_path.c_str()) != 0) {
1870 PLOG(ERROR) << "Could not unlink " << b_path;
1871 }
1872
1873 return false;
1874 }
1875
1876 return true;
1877}
1878
1879bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1880 // Get the current slot suffix. No suffix, no A/B.
1881 std::string slot_suffix;
1882 {
1883 char buf[kPropertyValueMax];
1884 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1885 return false;
1886 }
1887 slot_suffix = buf;
1888
1889 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1890 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1891 return false;
1892 }
1893 }
1894
1895 // Validate other inputs.
1896 if (validate_apk_path(apk_path) != 0) {
1897 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1898 return false;
1899 }
1900 if (validate_apk_path(oat_dir) != 0) {
1901 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1902 return false;
1903 }
1904
1905 char a_path[PKG_PATH_MAX];
1906 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1907 return false;
1908 }
1909 const std::string a_vdex_path = create_vdex_filename(a_path);
1910 const std::string a_image_path = create_image_filename(a_path);
1911
1912 // B path = A path + slot suffix.
1913 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1914 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1915 const std::string b_image_path = StringPrintf("%s.%s",
1916 a_image_path.c_str(),
1917 slot_suffix.c_str());
1918
1919 bool success = true;
1920 if (move_ab_path(b_path, a_path)) {
1921 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1922 // Note: we can live without an app image. As such, ignore failure to move the image file.
1923 // If we decide to require the app image, or the app image being moved correctly,
1924 // then change accordingly.
1925 constexpr bool kIgnoreAppImageFailure = true;
1926
1927 if (!a_image_path.empty()) {
1928 if (!move_ab_path(b_image_path, a_image_path)) {
1929 unlink(a_image_path.c_str());
1930 if (!kIgnoreAppImageFailure) {
1931 success = false;
1932 }
1933 }
1934 }
1935 } else {
1936 // Cleanup: delete B image, ignore errors.
1937 unlink(b_image_path.c_str());
1938 success = false;
1939 }
1940 } else {
1941 // Cleanup: delete B image, ignore errors.
1942 unlink(b_vdex_path.c_str());
1943 unlink(b_image_path.c_str());
1944 success = false;
1945 }
1946 return success;
1947}
1948
1949bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1950 // Delete the oat/odex file.
1951 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08001952 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001953 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001954 return false;
1955 }
1956
1957 // In case of a permission failure report the issue. Otherwise just print a warning.
1958 auto unlink_and_check = [](const char* path) -> bool {
1959 int result = unlink(path);
1960 if (result != 0) {
1961 if (errno == EACCES || errno == EPERM) {
1962 PLOG(ERROR) << "Could not unlink " << path;
1963 return false;
1964 }
1965 PLOG(WARNING) << "Could not unlink " << path;
1966 }
1967 return true;
1968 };
1969
1970 // Delete the oat/odex file.
1971 bool return_value_oat = unlink_and_check(out_path);
1972
1973 // Derive and delete the app image.
1974 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
1975
Nicolas Geoffray192fb962017-05-25 13:58:06 +01001976 // Derive and delete the vdex file.
1977 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
1978
Jeff Sharkey90aff262016-12-12 14:28:24 -07001979 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01001980 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001981}
1982
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001983} // namespace installd
1984} // namespace android