blob: 6a7d84580da0eb852fd0fcb0e522a2bdf9ecbebd [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>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070031#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070032#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070033#include <android-base/strings.h>
34#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080035#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070036#include <cutils/properties.h>
37#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkey90aff262016-12-12 14:28:24 -070039#include <private/android_filesystem_config.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070040#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070041#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070042
43#include "dexopt.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060044#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include "installd_deps.h"
46#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070047#include "utils.h"
48
49using android::base::StringPrintf;
Jeff Sharkey90aff262016-12-12 14:28:24 -070050using android::base::EndsWith;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080051using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070052
53namespace android {
54namespace installd {
55
Calin Juravle114f0812017-03-08 19:05:07 -080056// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
57struct FreeDelete {
58 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
59 void operator()(const void* ptr) const {
60 free(const_cast<void*>(ptr));
61 }
62};
63
64// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
65template <typename T>
66using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
67
Calin Juravle1a0af3b2017-03-09 14:33:33 -080068static unique_fd invalid_unique_fd() {
69 return unique_fd(-1);
70}
71
Andreas Gampe6a9cf722017-07-24 16:49:10 -070072static bool is_debug_runtime() {
73 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
74}
75
Jeff Sharkey90aff262016-12-12 14:28:24 -070076static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080077 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070078 if (ufd.get() < 0) {
79 if (errno != ENOENT) {
80 PLOG(WARNING) << "Could not open profile " << profile;
81 return false;
82 } else {
83 // Nothing to clear. That's ok.
84 return true;
85 }
86 }
87
88 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
89 if (errno != EWOULDBLOCK) {
90 PLOG(WARNING) << "Error locking profile " << profile;
91 }
92 // This implies that the app owning this profile is running
93 // (and has acquired the lock).
94 //
95 // If we can't acquire the lock bail out since clearing is useless anyway
96 // (the app will write again to the profile).
97 //
98 // Note:
99 // This does not impact the this is not an issue for the profiling correctness.
100 // In case this is needed because of an app upgrade, profiles will still be
101 // eventually cleared by the app itself due to checksum mismatch.
102 // If this is needed because profman advised, then keeping the data around
103 // until the next run is again not an issue.
104 //
105 // If the app attempts to acquire a lock while we've held one here,
106 // it will simply skip the current write cycle.
107 return false;
108 }
109
110 bool truncated = ftruncate(ufd.get(), 0) == 0;
111 if (!truncated) {
112 PLOG(WARNING) << "Could not truncate " << profile;
113 }
114 if (flock(ufd.get(), LOCK_UN) != 0) {
115 PLOG(WARNING) << "Error unlocking profile " << profile;
116 }
117 return truncated;
118}
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_reference_profile(const std::string& location, bool is_secondary_dex) {
123 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700124}
125
Calin Juravle114f0812017-03-08 19:05:07 -0800126// Clear the reference profile for the given location.
127// The location is the package name for primary apks or the dex path for secondary dex files.
128static bool clear_current_profile(const std::string& pkgname, userid_t user,
129 bool is_secondary_dex) {
130 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700131}
132
Calin Juravle114f0812017-03-08 19:05:07 -0800133// Clear the reference profile for the primary apk of the given package.
134bool clear_primary_reference_profile(const std::string& pkgname) {
135 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
136}
137
138// Clear all current profile for the primary apk of the given package.
139bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700140 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800141 // 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 -0700142 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
143 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800144 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700145 }
146 return success;
147}
148
Calin Juravle114f0812017-03-08 19:05:07 -0800149// Clear the current profile for the primary apk of the given package and user.
150bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
151 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
152}
153
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154static int split_count(const char *str)
155{
156 char *ctx;
157 int count = 0;
158 char buf[kPropertyValueMax];
159
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600160 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700161 char *pBuf = buf;
162
163 while(strtok_r(pBuf, " ", &ctx) != NULL) {
164 count++;
165 pBuf = NULL;
166 }
167
168 return count;
169}
170
171static int split(char *buf, const char **argv)
172{
173 char *ctx;
174 int count = 0;
175 char *tok;
176 char *pBuf = buf;
177
178 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
179 argv[count++] = tok;
180 pBuf = NULL;
181 }
182
183 return count;
184}
185
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700186static const char* get_location_from_path(const char* path) {
187 static constexpr char kLocationSeparator = '/';
188 const char *location = strrchr(path, kLocationSeparator);
189 if (location == NULL) {
190 return path;
191 } else {
192 // Skip the separator character.
193 return location + 1;
194 }
195}
196
Jeff Sharkey90aff262016-12-12 14:28:24 -0700197static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
198 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100199 const char* instruction_set, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -0700200 bool debuggable, bool post_bootcomplete, int profile_fd, const char* class_loader_context) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700201 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
202
203 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
204 ALOGE("Instruction set %s longer than max length of %d",
205 instruction_set, MAX_INSTRUCTION_SET_LEN);
206 return;
207 }
208
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700209 // Get the relative path to the input file.
210 const char* relative_input_file_name = get_location_from_path(input_file_name);
211
Jeff Sharkey90aff262016-12-12 14:28:24 -0700212 char dex2oat_Xms_flag[kPropertyValueMax];
213 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
214
215 char dex2oat_Xmx_flag[kPropertyValueMax];
216 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
217
218 char dex2oat_threads_buf[kPropertyValueMax];
219 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
220 ? "dalvik.vm.dex2oat-threads"
221 : "dalvik.vm.boot-dex2oat-threads",
222 dex2oat_threads_buf,
223 NULL) > 0;
224 char dex2oat_threads_arg[kPropertyValueMax + 2];
225 if (have_dex2oat_threads_flag) {
226 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
227 }
228
229 char dex2oat_isa_features_key[kPropertyKeyMax];
230 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
231 char dex2oat_isa_features[kPropertyValueMax];
232 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
233 dex2oat_isa_features, NULL) > 0;
234
235 char dex2oat_isa_variant_key[kPropertyKeyMax];
236 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
237 char dex2oat_isa_variant[kPropertyValueMax];
238 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
239 dex2oat_isa_variant, NULL) > 0;
240
241 const char *dex2oat_norelocation = "-Xnorelocate";
242 bool have_dex2oat_relocation_skip_flag = false;
243
244 char dex2oat_flags[kPropertyValueMax];
245 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
246 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
247 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
248
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100249 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700250 char vold_decrypt[kPropertyValueMax];
251 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
252 bool skip_compilation = (have_vold_decrypt &&
253 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
254 (strcmp(vold_decrypt, "1") == 0)));
255
256 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
257
258 char app_image_format[kPropertyValueMax];
259 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
260 bool have_app_image_format =
261 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
262 if (have_app_image_format) {
263 sprintf(image_format_arg, "--image-format=%s", app_image_format);
264 }
265
266 char dex2oat_large_app_threshold[kPropertyValueMax];
267 bool have_dex2oat_large_app_threshold =
268 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
269 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
270 if (have_dex2oat_large_app_threshold) {
271 sprintf(dex2oat_large_app_threshold_arg,
272 "--very-large-app-threshold=%s",
273 dex2oat_large_app_threshold);
274 }
275
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700276 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
277 const char* dex2oat_bin = is_debug_runtime() ? "/system/bin/dex2oatd" : "/system/bin/dex2oat";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700278
279 static const char* RUNTIME_ARG = "--runtime-arg";
280
281 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
282
George Burgess IV36cebe772017-01-25 11:52:01 -0800283 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
284 // use arraysize instead.
285 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
286 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
287 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
288 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
289 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
290 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
291 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
292 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
293 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
294 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
295 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
296 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700297 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800298 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700299 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800300 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700301 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
302 char class_loader_context_arg[class_loader_context_size];
303 if (class_loader_context != nullptr) {
304 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
305 class_loader_context);
306 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700307
308 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700309 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700310 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
311 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
312 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
313 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
314 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
315 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
316 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
317 if (swap_fd >= 0) {
318 have_dex2oat_swap_fd = true;
319 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
320 }
321 if (image_fd >= 0) {
322 have_dex2oat_image_fd = true;
323 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
324 }
325
326 if (have_dex2oat_Xms_flag) {
327 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
328 }
329 if (have_dex2oat_Xmx_flag) {
330 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
331 }
332
333 // Compute compiler filter.
334
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100335 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700336 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600337 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
338 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700339 have_dex2oat_compiler_filter_flag = true;
340 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100341 } else if (compiler_filter != nullptr) {
342 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700343 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100344 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
345 have_dex2oat_compiler_filter_flag = true;
346 } else {
347 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
348 compiler_filter,
349 kPropertyValueMax);
350 }
351 }
352
353 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700354 char dex2oat_compiler_filter_flag[kPropertyValueMax];
355 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
356 dex2oat_compiler_filter_flag, NULL) > 0;
357 if (have_dex2oat_compiler_filter_flag) {
358 sprintf(dex2oat_compiler_filter_arg,
359 "--compiler-filter=%s",
360 dex2oat_compiler_filter_flag);
361 }
362 }
363
364 // Check whether all apps should be compiled debuggable.
365 if (!debuggable) {
366 char prop_buf[kPropertyValueMax];
367 debuggable =
368 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
369 (prop_buf[0] == '1');
370 }
371 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
372 if (profile_fd != -1) {
373 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
374 }
375
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700376 // Get the directory of the apk to pass as a base classpath directory.
377 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
378 std::string apk_dir(input_file_name);
379 unsigned long dir_index = apk_dir.rfind('/');
380 bool has_base_dir = dir_index != std::string::npos;
381 if (has_base_dir) {
382 apk_dir = apk_dir.substr(0, dir_index);
383 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
384 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700385
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700386
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700387 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700388
389 const char* argv[9 // program name, mandatory arguments and the final NULL
390 + (have_dex2oat_isa_variant ? 1 : 0)
391 + (have_dex2oat_isa_features ? 1 : 0)
392 + (have_dex2oat_Xms_flag ? 2 : 0)
393 + (have_dex2oat_Xmx_flag ? 2 : 0)
394 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
395 + (have_dex2oat_threads_flag ? 1 : 0)
396 + (have_dex2oat_swap_fd ? 1 : 0)
397 + (have_dex2oat_image_fd ? 1 : 0)
398 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
399 + (generate_debug_info ? 1 : 0)
400 + (debuggable ? 1 : 0)
401 + (have_app_image_format ? 1 : 0)
402 + dex2oat_flags_count
403 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700404 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700405 + (has_base_dir ? 1 : 0)
Jeff Sharkey90aff262016-12-12 14:28:24 -0700406 + (have_dex2oat_large_app_threshold ? 1 : 0)];
407 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700408 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700409 argv[i++] = zip_fd_arg;
410 argv[i++] = zip_location_arg;
411 argv[i++] = input_vdex_fd_arg;
412 argv[i++] = output_vdex_fd_arg;
413 argv[i++] = oat_fd_arg;
414 argv[i++] = oat_location_arg;
415 argv[i++] = instruction_set_arg;
416 if (have_dex2oat_isa_variant) {
417 argv[i++] = instruction_set_variant_arg;
418 }
419 if (have_dex2oat_isa_features) {
420 argv[i++] = instruction_set_features_arg;
421 }
422 if (have_dex2oat_Xms_flag) {
423 argv[i++] = RUNTIME_ARG;
424 argv[i++] = dex2oat_Xms_arg;
425 }
426 if (have_dex2oat_Xmx_flag) {
427 argv[i++] = RUNTIME_ARG;
428 argv[i++] = dex2oat_Xmx_arg;
429 }
430 if (have_dex2oat_compiler_filter_flag) {
431 argv[i++] = dex2oat_compiler_filter_arg;
432 }
433 if (have_dex2oat_threads_flag) {
434 argv[i++] = dex2oat_threads_arg;
435 }
436 if (have_dex2oat_swap_fd) {
437 argv[i++] = dex2oat_swap_fd;
438 }
439 if (have_dex2oat_image_fd) {
440 argv[i++] = dex2oat_image_fd;
441 }
442 if (generate_debug_info) {
443 argv[i++] = "--generate-debug-info";
444 }
445 if (debuggable) {
446 argv[i++] = "--debuggable";
447 }
448 if (have_app_image_format) {
449 argv[i++] = image_format_arg;
450 }
451 if (have_dex2oat_large_app_threshold) {
452 argv[i++] = dex2oat_large_app_threshold_arg;
453 }
454 if (dex2oat_flags_count) {
455 i += split(dex2oat_flags, argv + i);
456 }
457 if (have_dex2oat_relocation_skip_flag) {
458 argv[i++] = RUNTIME_ARG;
459 argv[i++] = dex2oat_norelocation;
460 }
461 if (profile_fd != -1) {
462 argv[i++] = profile_arg;
463 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700464 if (has_base_dir) {
465 argv[i++] = base_dir;
466 }
Calin Juravle52c45822017-07-13 22:50:21 -0700467 if (class_loader_context != nullptr) {
468 argv[i++] = class_loader_context_arg;
469 }
470
Jeff Sharkey90aff262016-12-12 14:28:24 -0700471 // Do not add after dex2oat_flags, they should override others for debugging.
472 argv[i] = NULL;
473
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700474 execv(dex2oat_bin, (char * const *)argv);
475 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700476}
477
478/*
479 * Whether dexopt should use a swap file when compiling an APK.
480 *
481 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
482 * itself, anyways).
483 *
484 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
485 *
486 * Otherwise, return true if this is a low-mem device.
487 *
488 * Otherwise, return default value.
489 */
490static bool kAlwaysProvideSwapFile = false;
491static bool kDefaultProvideSwapFile = true;
492
493static bool ShouldUseSwapFileForDexopt() {
494 if (kAlwaysProvideSwapFile) {
495 return true;
496 }
497
498 // Check the "override" property. If it exists, return value == "true".
499 char dex2oat_prop_buf[kPropertyValueMax];
500 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
501 if (strcmp(dex2oat_prop_buf, "true") == 0) {
502 return true;
503 } else {
504 return false;
505 }
506 }
507
508 // Shortcut for default value. This is an implementation optimization for the process sketched
509 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
510 // as low-mem is never returning false. The compiler will optimize this away if it can.
511 if (kDefaultProvideSwapFile) {
512 return true;
513 }
514
515 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
516 if (is_low_mem) {
517 return true;
518 }
519
520 // Default value must be false here.
521 return kDefaultProvideSwapFile;
522}
523
Richard Uhler76cc0272016-12-08 10:46:35 +0000524static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700525 if (set_to_bg) {
526 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
527 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
528 exit(70);
529 }
530 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
531 ALOGE("setpriority failed: %s\n", strerror(errno));
532 exit(71);
533 }
534 }
535}
536
Calin Juravle114f0812017-03-08 19:05:07 -0800537static bool create_profile(int uid, const std::string& profile) {
538 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), O_CREAT | O_NOFOLLOW, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800539 if (fd.get() < 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800540 if (errno == EEXIST) {
541 return true;
542 } else {
543 PLOG(ERROR) << "Failed to create profile " << profile;
544 return false;
545 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700546 }
Calin Juravle114f0812017-03-08 19:05:07 -0800547 // Profiles should belong to the app; make sure of that by giving ownership to
548 // the app uid. If we cannot do that, there's no point in returning the fd
549 // since dex2oat/profman will fail with SElinux denials.
550 if (fchown(fd.get(), uid, uid) < 0) {
551 PLOG(ERROR) << "Could not chwon profile " << profile;
552 return false;
553 }
554 return true;
555}
556
557static unique_fd open_profile(int uid, const std::string& profile, bool read_write) {
558 // Check if we need to open the profile for a read-write operation. If so, we
559 // might need to create the profile since the file might not be there. Reference
560 // profiles are created on the fly so they might not exist beforehand.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700561 if (read_write) {
Calin Juravle114f0812017-03-08 19:05:07 -0800562 if (!create_profile(uid, profile)) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800563 return invalid_unique_fd();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700564 }
565 }
Calin Juravle114f0812017-03-08 19:05:07 -0800566 int flags = read_write ? O_RDWR : O_RDONLY;
567 // Do not follow symlinks when opening a profile:
568 // - primary profiles should not contain symlinks in their paths
569 // - secondary dex paths should have been already resolved and validated
570 flags |= O_NOFOLLOW;
571
572 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
573 if (fd.get() < 0) {
574 if (errno != ENOENT) {
575 // Profiles might be missing for various reasons. For example, in a
576 // multi-user environment, the profile directory for one user can be created
577 // after we start a merge. In this case the current profile for that user
578 // will not be found.
579 // Also, the secondary dex profiles might be deleted by the app at any time,
580 // so we can't we need to prepare if they are missing.
581 PLOG(ERROR) << "Failed to open profile " << profile;
582 }
583 return invalid_unique_fd();
584 }
585
Jeff Sharkey90aff262016-12-12 14:28:24 -0700586 return fd;
587}
588
Calin Juravle114f0812017-03-08 19:05:07 -0800589static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
590 bool is_secondary_dex) {
591 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
592 return open_profile(uid, profile, /*read_write*/false);
593}
594
595static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
596 bool is_secondary_dex) {
597 std::string profile = create_reference_profile_path(location, is_secondary_dex);
598 return open_profile(uid, profile, read_write);
599}
600
601static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800602 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700603 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800604 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
605 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700606
Calin Juravle114f0812017-03-08 19:05:07 -0800607 // For secondary dex files, we don't really need the user but we use it for sanity checks.
608 // Note: the user owning the dex file should be the current user.
609 std::vector<userid_t> users;
610 if (is_secondary_dex){
611 users.push_back(multiuser_get_user_id(uid));
612 } else {
613 users = get_known_users(/*volume_uuid*/ nullptr);
614 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700615 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800616 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800618 if (profile_fd.get() >= 0) {
619 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700620 }
621 }
622}
623
624static void drop_capabilities(uid_t uid) {
625 if (setgid(uid) != 0) {
626 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
627 exit(64);
628 }
629 if (setuid(uid) != 0) {
630 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
631 exit(65);
632 }
633 // drop capabilities
634 struct __user_cap_header_struct capheader;
635 struct __user_cap_data_struct capdata[2];
636 memset(&capheader, 0, sizeof(capheader));
637 memset(&capdata, 0, sizeof(capdata));
638 capheader.version = _LINUX_CAPABILITY_VERSION_3;
639 if (capset(&capheader, &capdata[0]) < 0) {
640 ALOGE("capset failed: %s\n", strerror(errno));
641 exit(66);
642 }
643}
644
645static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
646static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
647static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
648static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
649static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
650
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800651static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
652 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700653 static const size_t MAX_INT_LEN = 32;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700654 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700655
656 std::vector<std::string> profile_args(profiles_fd.size());
657 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
658 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800659 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700660 profile_args[k].assign(profile_buf);
661 }
662 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800663 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664
665 // program name, reference profile fd, the final NULL and the profile fds
666 const char* argv[3 + profiles_fd.size()];
667 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700668 argv[i++] = profman_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700669 argv[i++] = reference_profile_arg;
670 for (size_t k = 0; k < profile_args.size(); k++) {
671 argv[i++] = profile_args[k].c_str();
672 }
673 // Do not add after dex2oat_flags, they should override others for debugging.
674 argv[i] = NULL;
675
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700676 execv(profman_bin, (char * const *)argv);
677 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700678 exit(68); /* only get here on exec failure */
679}
680
681// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800682// The location is the package name for primary apks or the dex path for secondary dex files.
683// Returns true if there is enough information in the current profiles that makes it
684// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700685// If the return value is true all the current profiles would have been merged into
686// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800687static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800688 std::vector<unique_fd> profiles_fd;
689 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800690 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800691 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692 // Skip profile guided compilation because no profiles were found.
693 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694 return false;
695 }
696
Jeff Sharkey90aff262016-12-12 14:28:24 -0700697 pid_t pid = fork();
698 if (pid == 0) {
699 /* child -- drop privileges before continuing */
700 drop_capabilities(uid);
701 run_profman_merge(profiles_fd, reference_profile_fd);
702 exit(68); /* only get here on exec failure */
703 }
704 /* parent */
705 int return_code = wait_child(pid);
706 bool need_to_compile = false;
707 bool should_clear_current_profiles = false;
708 bool should_clear_reference_profile = false;
709 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800710 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711 } else {
712 return_code = WEXITSTATUS(return_code);
713 switch (return_code) {
714 case PROFMAN_BIN_RETURN_CODE_COMPILE:
715 need_to_compile = true;
716 should_clear_current_profiles = true;
717 should_clear_reference_profile = false;
718 break;
719 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
720 need_to_compile = false;
721 should_clear_current_profiles = false;
722 should_clear_reference_profile = false;
723 break;
724 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800725 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700726 need_to_compile = false;
727 should_clear_current_profiles = true;
728 should_clear_reference_profile = true;
729 break;
730 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
731 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
732 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800733 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700734 need_to_compile = false;
735 should_clear_current_profiles = false;
736 should_clear_reference_profile = false;
737 break;
738 default:
739 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800740 LOG(WARNING) << "Unknown error code while processing profiles for location "
741 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700742 need_to_compile = false;
743 should_clear_current_profiles = true;
744 should_clear_reference_profile = true;
745 break;
746 }
747 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800748
Jeff Sharkey90aff262016-12-12 14:28:24 -0700749 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800750 if (is_secondary_dex) {
751 // For secondary dex files, the owning user is the current user.
752 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
753 } else {
754 clear_primary_current_profiles(location);
755 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 }
757 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800758 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700759 }
760 return need_to_compile;
761}
762
Calin Juravle114f0812017-03-08 19:05:07 -0800763// Decides if profile guided compilation is needed or not based on existing profiles.
764// The analysis is done for the primary apks of the given package.
765// Returns true if there is enough information in the current profiles that makes it
766// worth to recompile the package.
767// If the return value is true all the current profiles would have been merged into
768// the reference profiles accessible with open_reference_profile().
769bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
770 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
771}
772
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800773static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
774 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800776 const std::vector<unique_fd>& apk_fds,
777 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700778 std::vector<std::string> profman_args;
779 static const char* PROFMAN_BIN = "/system/bin/profman";
780 profman_args.push_back(PROFMAN_BIN);
781 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800782 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783 if (reference_profile_fd != -1) {
784 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800785 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700786 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800787 for (size_t i = 0; i < profile_fds.size(); i++) {
788 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789 }
790 for (const std::string& dex_location : dex_locations) {
791 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
792 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800793 for (size_t i = 0; i < apk_fds.size(); i++) {
794 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700795 }
796 const char **argv = new const char*[profman_args.size() + 1];
797 size_t i = 0;
798 for (const std::string& profman_arg : profman_args) {
799 argv[i++] = profman_arg.c_str();
800 }
801 argv[i] = NULL;
802
803 execv(PROFMAN_BIN, (char * const *)argv);
804 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
805 exit(68); /* only get here on exec failure */
806}
807
Calin Juravle76268c52017-03-09 13:19:42 -0800808bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800809 std::vector<unique_fd> profile_fds;
810 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800811 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700812
Calin Juravle114f0812017-03-08 19:05:07 -0800813 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
814 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700815
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800816 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 const bool has_profiles = !profile_fds.empty();
818
819 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800820 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821 return false;
822 }
823
Calin Juravle114f0812017-03-08 19:05:07 -0800824 unique_fd output_fd(open(out_file_name.c_str(),
825 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700826 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
827 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
828 return false;
829 }
830 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
831 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800832 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 for (const std::string& code_full_path : code_full_paths) {
834 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800835 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836 if (apk_fd == -1) {
837 ALOGE("installd cannot open '%s'\n", full_path);
838 return false;
839 }
840 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800841 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842 }
843
844 pid_t pid = fork();
845 if (pid == 0) {
846 /* child -- drop privileges before continuing */
847 drop_capabilities(uid);
848 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
849 apk_fds, output_fd);
850 exit(68); /* only get here on exec failure */
851 }
852 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 int return_code = wait_child(pid);
854 if (!WIFEXITED(return_code)) {
855 LOG(WARNING) << "profman failed for package " << pkgname << ": "
856 << return_code;
857 return false;
858 }
859 return true;
860}
861
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700862bool copy_system_profile(const std::string& system_profile,
863 uid_t packageUid, const std::string& data_profile_location) {
864 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
865 unique_fd out_fd(open_reference_profile(packageUid,
866 data_profile_location,
867 /*read_write*/ true,
868 /*secondary*/ false));
869 if (in_fd.get() < 0) {
870 PLOG(WARNING) << "Could not open profile " << system_profile;
871 return false;
872 }
873 if (out_fd.get() < 0) {
874 PLOG(WARNING) << "Could not open profile " << data_profile_location;
875 return false;
876 }
877
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700878 // As a security measure we want to write the profile information with the reduced capabilities
879 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700880 pid_t pid = fork();
881 if (pid == 0) {
882 /* child -- drop privileges before continuing */
883 drop_capabilities(packageUid);
884
885 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
886 if (errno != EWOULDBLOCK) {
887 PLOG(WARNING) << "Error locking profile " << data_profile_location;
888 }
889 // This implies that the app owning this profile is running
890 // (and has acquired the lock).
891 //
892 // The app never acquires the lock for the reference profiles of primary apks.
893 // Only dex2oat from installd will do that. Since installd is single threaded
894 // we should not see this case. Nevertheless be prepared for it.
895 PLOG(WARNING) << "Failed to flock " << data_profile_location;
896 return false;
897 }
898
899 bool truncated = ftruncate(out_fd.get(), 0) == 0;
900 if (!truncated) {
901 PLOG(WARNING) << "Could not truncate " << data_profile_location;
902 }
903
904 // Copy over data.
905 static constexpr size_t kBufferSize = 4 * 1024;
906 char buffer[kBufferSize];
907 while (true) {
908 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
909 if (bytes == 0) {
910 break;
911 }
912 write(out_fd.get(), buffer, bytes);
913 }
914 if (flock(out_fd.get(), LOCK_UN) != 0) {
915 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
916 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700917 // Use _exit since we don't want to run the global destructors in the child.
918 // b/62597429
919 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700920 }
921 /* parent */
922 int return_code = wait_child(pid);
923 return return_code == 0;
924}
925
Jeff Sharkey90aff262016-12-12 14:28:24 -0700926static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
927 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
928 if (EndsWith(oat_path, ".dex")) {
929 std::string new_path = oat_path;
930 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
931 CHECK(EndsWith(new_path, new_ext.c_str()));
932 return new_path;
933 }
934
935 // An odex entry. Not that this may not be an extension, e.g., in the OTA
936 // case (where the base name will have an extension for the B artifact).
937 size_t odex_pos = oat_path.rfind(".odex");
938 if (odex_pos != std::string::npos) {
939 std::string new_path = oat_path;
940 new_path.replace(odex_pos, strlen(".odex"), new_ext);
941 CHECK_NE(new_path.find(new_ext), std::string::npos);
942 return new_path;
943 }
944
945 // Don't know how to handle this.
946 return "";
947}
948
949// Translate the given oat path to an art (app image) path. An empty string
950// denotes an error.
951static std::string create_image_filename(const std::string& oat_path) {
952 return replace_file_extension(oat_path, ".art");
953}
954
955// Translate the given oat path to a vdex path. An empty string denotes an error.
956static std::string create_vdex_filename(const std::string& oat_path) {
957 return replace_file_extension(oat_path, ".vdex");
958}
959
Jeff Sharkey90aff262016-12-12 14:28:24 -0700960static int open_output_file(const char* file_name, bool recreate, int permissions) {
961 int flags = O_RDWR | O_CREAT;
962 if (recreate) {
963 if (unlink(file_name) < 0) {
964 if (errno != ENOENT) {
965 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
966 }
967 }
968 flags |= O_EXCL;
969 }
970 return open(file_name, flags, permissions);
971}
972
Calin Juravle2289c0a2017-02-15 12:44:14 -0800973static bool set_permissions_and_ownership(
974 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
975 // Primary apks are owned by the system. Secondary dex files are owned by the app.
976 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700977 if (fchmod(fd,
978 S_IRUSR|S_IWUSR|S_IRGRP |
979 (is_public ? S_IROTH : 0)) < 0) {
980 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
981 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -0800982 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700983 ALOGE("installd cannot chown '%s' during dexopt\n", path);
984 return false;
985 }
986 return true;
987}
988
989static bool IsOutputDalvikCache(const char* oat_dir) {
990 // InstallerConnection.java (which invokes installd) transforms Java null arguments
991 // into '!'. Play it safe by handling it both.
992 // TODO: ensure we never get null.
993 // TODO: pass a flag instead of inferring if the output is dalvik cache.
994 return oat_dir == nullptr || oat_dir[0] == '!';
995}
996
Calin Juravled23dee72017-07-06 16:29:11 -0700997// Best-effort check whether we can fit the the path into our buffers.
998// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
999// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1000// extension to the cache path (5 bytes).
1001// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1002static bool validate_dex_path_size(const std::string& dex_path) {
1003 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1004 LOG(ERROR) << "dex_path too long: " << dex_path;
1005 return false;
1006 }
1007 return true;
1008}
1009
Jeff Sharkey90aff262016-12-12 14:28:24 -07001010static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001011 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001012 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001013 return false;
1014 }
1015
1016 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001017 // Oat dirs for secondary dex files are already validated.
1018 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001019 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1020 return false;
1021 }
1022 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1023 return false;
1024 }
1025 } else {
1026 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1027 return false;
1028 }
1029 }
1030 return true;
1031}
1032
1033// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1034// on destruction. It will also run the given cleanup (unless told not to) after closing.
1035//
1036// Usage example:
1037//
Calin Juravle7a570e82017-01-14 16:23:30 -08001038// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001039// [name]() {
1040// unlink(name.c_str());
1041// });
1042// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1043// wrapper if captured as a reference.
1044//
1045// if (file.get() == -1) {
1046// // Error opening...
1047// }
1048//
1049// ...
1050// if (error) {
1051// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1052// // and delete the file (after the fd is closed).
1053// return -1;
1054// }
1055//
1056// (Success case)
1057// file.SetCleanup(false);
1058// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1059// // (leaving the file around; after the fd is closed).
1060//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001061class Dex2oatFileWrapper {
1062 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001063 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001064 }
1065
Calin Juravle7a570e82017-01-14 16:23:30 -08001066 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1067 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1068
1069 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1070 value_ = other.value_;
1071 cleanup_ = other.cleanup_;
1072 do_cleanup_ = other.do_cleanup_;
1073 auto_close_ = other.auto_close_;
1074 other.release();
1075 }
1076
1077 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1078 value_ = other.value_;
1079 cleanup_ = other.cleanup_;
1080 do_cleanup_ = other.do_cleanup_;
1081 auto_close_ = other.auto_close_;
1082 other.release();
1083 return *this;
1084 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001085
1086 ~Dex2oatFileWrapper() {
1087 reset(-1);
1088 }
1089
1090 int get() {
1091 return value_;
1092 }
1093
1094 void SetCleanup(bool cleanup) {
1095 do_cleanup_ = cleanup;
1096 }
1097
1098 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001099 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001100 close(value_);
1101 }
1102 if (do_cleanup_ && cleanup_ != nullptr) {
1103 cleanup_();
1104 }
1105
1106 value_ = new_value;
1107 }
1108
Calin Juravle7a570e82017-01-14 16:23:30 -08001109 void reset(int new_value, std::function<void ()> new_cleanup) {
1110 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001111 close(value_);
1112 }
1113 if (do_cleanup_ && cleanup_ != nullptr) {
1114 cleanup_();
1115 }
1116
1117 value_ = new_value;
1118 cleanup_ = new_cleanup;
1119 }
1120
Calin Juravle7a570e82017-01-14 16:23:30 -08001121 void DisableAutoClose() {
1122 auto_close_ = false;
1123 }
1124
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001126 void release() {
1127 value_ = -1;
1128 do_cleanup_ = false;
1129 cleanup_ = nullptr;
1130 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001132 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001133 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001134 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135};
1136
Calin Juravle7a570e82017-01-14 16:23:30 -08001137// (re)Creates the app image if needed.
1138Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001139 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001140
1141 // We don't create an image for secondary dex files.
1142 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001143 return Dex2oatFileWrapper();
1144 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001145
Calin Juravle7a570e82017-01-14 16:23:30 -08001146 const std::string image_path = create_image_filename(out_oat_path);
1147 if (image_path.empty()) {
1148 // Happens when the out_oat_path has an unknown extension.
1149 return Dex2oatFileWrapper();
1150 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001151
1152 // Use app images only if it is enabled (by a set image format) and we are compiling
1153 // profile-guided (so the app image doesn't conservatively contain all classes).
1154 if (!profile_guided) {
1155 // In case there is a stale image, remove it now. Ignore any error.
1156 unlink(image_path.c_str());
1157 return Dex2oatFileWrapper();
1158 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001159 char app_image_format[kPropertyValueMax];
1160 bool have_app_image_format =
1161 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1162 if (!have_app_image_format) {
1163 return Dex2oatFileWrapper();
1164 }
1165 // Recreate is true since we do not want to modify a mapped image. If the app is
1166 // already running and we modify the image file, it can cause crashes (b/27493510).
1167 Dex2oatFileWrapper wrapper_fd(
1168 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1169 [image_path]() { unlink(image_path.c_str()); });
1170 if (wrapper_fd.get() < 0) {
1171 // Could not create application image file. Go on since we can compile without it.
1172 LOG(ERROR) << "installd could not create '" << image_path
1173 << "' for image file during dexopt";
1174 // If we have a valid image file path but no image fd, explicitly erase the image file.
1175 if (unlink(image_path.c_str()) < 0) {
1176 if (errno != ENOENT) {
1177 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1178 }
1179 }
1180 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001181 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001182 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1183 wrapper_fd.reset(-1);
1184 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001185
Calin Juravle7a570e82017-01-14 16:23:30 -08001186 return wrapper_fd;
1187}
1188
1189// Creates the dexopt swap file if necessary and return its fd.
1190// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001191unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001193 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001194 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001195 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001196 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001197 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001198 if (swap_fd.get() < 0) {
1199 // Could not create swap file. Optimistically go on and hope that we can compile
1200 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001201 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001202 } else {
1203 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001204 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001205 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1206 }
1207 }
1208 return swap_fd;
1209}
1210
1211// Opens the reference profiles if needed.
1212// 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 -08001213Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1214 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1215 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001216 // Public apps should not be compiled with profile information ever. Same goes for the special
1217 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001218 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001219 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001220 }
Calin Juravle114f0812017-03-08 19:05:07 -08001221
1222 // Open reference profile in read only mode as dex2oat does not get write permissions.
1223 const std::string location = is_secondary_dex ? dex_path : pkgname;
1224 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1225 const auto& cleanup = [location, is_secondary_dex]() {
1226 clear_reference_profile(location.c_str(), is_secondary_dex);
1227 };
1228 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001229}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001230
Calin Juravle7a570e82017-01-14 16:23:30 -08001231// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1232// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
1233bool open_vdex_files(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001234 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001235 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001236 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1237 CHECK(in_vdex_wrapper_fd != nullptr);
1238 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001239 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1240 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001241 char in_odex_path[PKG_PATH_MAX];
1242 int dexopt_action = abs(dexopt_needed);
1243 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001244 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001245
1246 // Infer the name of the output VDEX.
1247 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1248 if (out_vdex_path_str.empty()) {
1249 return false;
1250 }
1251
1252 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001253 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001254 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1255 const char* path = nullptr;
1256 if (is_odex_location) {
1257 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1258 path = in_odex_path;
1259 } else {
1260 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001261 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001262 }
1263 } else {
1264 path = out_oat_path;
1265 }
1266 in_vdex_path_str = create_vdex_filename(path);
1267 if (in_vdex_path_str.empty()) {
1268 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001269 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001270 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001271 // We can update in place when all these conditions are met:
1272 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1273 // on /system typically cannot be updated in place).
1274 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1275 // cannot be currently used by a running process.
1276 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1277 // different vdex files to operate.
1278 update_vdex_in_place =
1279 (in_vdex_path_str == out_vdex_path_str) &&
1280 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1281 !profile_guided;
1282 if (update_vdex_in_place) {
1283 // Open the file read-write to be able to update it.
1284 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1285 if (in_vdex_wrapper_fd->get() == -1) {
1286 // If we failed to open the file, we cannot update it in place.
1287 update_vdex_in_place = false;
1288 }
1289 } else {
1290 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1291 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292 }
1293
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001294 // If we are updating the vdex in place, we do not need to recreate a vdex,
1295 // and can use the same existing one.
1296 if (update_vdex_in_place) {
1297 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1298 // have bogus stale vdex files.
1299 out_vdex_wrapper_fd->reset(
1300 in_vdex_wrapper_fd->get(),
1301 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1302 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1303 // wrapper).
1304 in_vdex_wrapper_fd->DisableAutoClose();
1305 } else {
1306 out_vdex_wrapper_fd->reset(
1307 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1308 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1309 if (out_vdex_wrapper_fd->get() < 0) {
1310 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1311 return false;
1312 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001313 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001314 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001315 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001316 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1317 return false;
1318 }
1319
1320 // If we got here we successfully opened the vdex files.
1321 return true;
1322}
1323
1324// Opens the output oat file for the given apk.
1325// If successful it stores the output path into out_oat_path and returns true.
1326Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001327 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1328 char* out_oat_path) {
1329 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001330 return Dex2oatFileWrapper();
1331 }
1332 const std::string out_oat_path_str(out_oat_path);
1333 Dex2oatFileWrapper wrapper_fd(
1334 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1335 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1336 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001337 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001338 } else if (!set_permissions_and_ownership(
1339 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001340 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1341 wrapper_fd.reset(-1);
1342 }
1343 return wrapper_fd;
1344}
1345
1346// Updates the access times of out_oat_path based on those from apk_path.
1347void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1348 struct stat input_stat;
1349 memset(&input_stat, 0, sizeof(input_stat));
1350 if (stat(apk_path, &input_stat) != 0) {
1351 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1352 return;
1353 }
1354
1355 struct utimbuf ut;
1356 ut.actime = input_stat.st_atime;
1357 ut.modtime = input_stat.st_mtime;
1358 if (utime(out_oat_path, &ut) != 0) {
1359 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1360 }
1361}
1362
Calin Juravle80a21252017-01-17 14:43:25 -08001363// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001364// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1365// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1366// the profile has changed.
Calin Juravled23dee72017-07-06 16:29:11 -07001367static void exec_dexoptanalyzer(const std::string& dex_file, const std::string& instruction_set,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001368 const std::string& compiler_filter, bool profile_was_updated, bool downgrade) {
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001369 const char* dexoptanalyzer_bin =
1370 is_debug_runtime()
1371 ? "/system/bin/dexoptanalyzerd"
1372 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001373 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1374
Calin Juravled23dee72017-07-06 16:29:11 -07001375 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1376 LOG(ERROR) << "Instruction set " << instruction_set
1377 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001378 return;
1379 }
1380
Calin Juravled23dee72017-07-06 16:29:11 -07001381 std::string dex_file_arg = "--dex-file=" + dex_file;
1382 std::string isa_arg = "--isa=" + instruction_set;
1383 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001384 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001385 const char* downgrade_flag = "--downgrade";
Calin Juravle80a21252017-01-17 14:43:25 -08001386
Calin Juravle80a21252017-01-17 14:43:25 -08001387 // program name, dex file, isa, filter, the final NULL
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001388 const int argc = 5 +
1389 (profile_was_updated ? 1 : 0) +
1390 (downgrade ? 1 : 0);
1391 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001392 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001393 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001394 argv[i++] = dex_file_arg.c_str();
1395 argv[i++] = isa_arg.c_str();
1396 argv[i++] = compiler_filter_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001397 if (profile_was_updated) {
1398 argv[i++] = assume_profile_changed;
1399 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001400 if (downgrade) {
1401 argv[i++] = downgrade_flag;
1402 }
Calin Juravle80a21252017-01-17 14:43:25 -08001403 argv[i] = NULL;
1404
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001405 execv(dexoptanalyzer_bin, (char * const *)argv);
1406 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001407}
1408
1409// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001410static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1411 const char* instruction_set, std::string* oat_dir_out) {
1412 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001413 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001414 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001415 return false;
1416 }
Calin Juravle114f0812017-03-08 19:05:07 -08001417 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001418
Calin Juravle80a21252017-01-17 14:43:25 -08001419 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001420 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1421 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001422 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001423 return false;
1424 }
1425
1426 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001427 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001428 oat_dir_out->assign(oat_dir);
1429
1430 // Create oat/isa output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001431 if (prepare_app_cache_dir(*oat_dir_out, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001432 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001433 return false;
1434 }
1435
1436 return true;
1437}
1438
1439static int constexpr DEXOPTANALYZER_BIN_EXEC_ERROR = 200;
1440
1441// Verifies the result of dexoptanalyzer executed for the apk_path.
1442// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1443// Returns false for errors or unexpected result values.
Calin Juravle114f0812017-03-08 19:05:07 -08001444static bool process_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001445 int* dexopt_needed_out) {
1446 // The result values are defined in dexoptanalyzer.
1447 switch (result) {
1448 case 0: // no_dexopt_needed
1449 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1450 case 1: // dex2oat_from_scratch
1451 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1452 case 5: // dex2oat_for_bootimage_odex
1453 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1454 case 6: // dex2oat_for_filter_odex
1455 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1456 case 7: // dex2oat_for_relocation_odex
1457 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
1458 case 2: // dex2oat_for_bootimage_oat
1459 case 3: // dex2oat_for_filter_oat
1460 case 4: // dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001461 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1462 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001463 << " : dexoptanalyzer result=" << result;
1464 return false;
1465 default:
Calin Juravlec9eab382017-01-25 01:17:17 -08001466 LOG(ERROR) << "Unexpected result for dexoptanalyzer " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001467 << " exec_dexoptanalyzer result=" << result;
1468 return false;
1469 }
1470}
1471
Calin Juravlec9eab382017-01-25 01:17:17 -08001472// 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 -08001473// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1474// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001475// When returning true, the output parameters will be:
1476// - is_public_out: whether or not the oat file should not be made public
1477// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1478// - oat_dir_out: the oat dir path where the oat file should be stored
1479// - dex_path_out: the real path of the dex file
Calin Juravle114f0812017-03-08 19:05:07 -08001480static bool process_secondary_dex_dexopt(const char* original_dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001481 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001482 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001483 std::string* oat_dir_out, std::string* dex_path_out, bool downgrade) {
Calin Juravle80a21252017-01-17 14:43:25 -08001484 int storage_flag;
1485
1486 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1487 storage_flag = FLAG_STORAGE_CE;
1488 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1489 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1490 return false;
1491 }
1492 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1493 storage_flag = FLAG_STORAGE_DE;
1494 } else {
1495 LOG(ERROR) << "Secondary dex storage flag must be set";
1496 return false;
1497 }
1498
Calin Juravle114f0812017-03-08 19:05:07 -08001499 {
1500 // As opposed to the primary apk, secondary dex files might contain symlinks.
1501 // Resolve the path before passing it to the validate method to
1502 // make sure the verification is done on the real location.
1503 UniqueCPtr<char> dex_real_path_cstr(realpath(original_dex_path, nullptr));
1504 if (dex_real_path_cstr == nullptr) {
1505 PLOG(ERROR) << "Could not get the real path of the secondary dex file "
1506 << original_dex_path;
1507 return false;
1508 } else {
1509 dex_path_out->assign(dex_real_path_cstr.get());
1510 }
1511 }
1512 const std::string& dex_path = *dex_path_out;
Calin Juravled23dee72017-07-06 16:29:11 -07001513 if (!validate_dex_path_size(dex_path)) {
1514 return false;
1515 }
Calin Juravlec9eab382017-01-25 01:17:17 -08001516 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1517 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001518 return false;
1519 }
1520
1521 // Check if the path exist. If not, there's nothing to do.
Calin Juravleebc8a792017-04-04 20:21:05 -07001522 struct stat dex_path_stat;
1523 if (stat(dex_path.c_str(), &dex_path_stat) != 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001524 if (errno == ENOENT) {
1525 // Secondary dex files might be deleted any time by the app.
1526 // Nothing to do if that's the case
Calin Juravle114f0812017-03-08 19:05:07 -08001527 ALOGV("Secondary dex does not exist %s", dex_path.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001528 return NO_DEXOPT_NEEDED;
1529 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001530 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001531 }
1532 }
1533
Calin Juravleebc8a792017-04-04 20:21:05 -07001534 // Check if we should make the oat file public.
1535 // Note that if the dex file is not public the compiled code cannot be made public.
1536 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) &&
1537 ((dex_path_stat.st_mode & S_IROTH) != 0);
1538
Calin Juravle80a21252017-01-17 14:43:25 -08001539 // Prepare the oat directories.
Calin Juravle114f0812017-03-08 19:05:07 -08001540 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set, oat_dir_out)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001541 return false;
1542 }
1543
Calin Juravle114f0812017-03-08 19:05:07 -08001544 // Analyze profiles.
1545 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1546
Calin Juravle80a21252017-01-17 14:43:25 -08001547 pid_t pid = fork();
1548 if (pid == 0) {
1549 // child -- drop privileges before continuing.
1550 drop_capabilities(uid);
1551 // Run dexoptanalyzer to get dexopt_needed code.
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001552 exec_dexoptanalyzer(dex_path, instruction_set, compiler_filter, profile_was_updated,
1553 downgrade);
Calin Juravle80a21252017-01-17 14:43:25 -08001554 exit(DEXOPTANALYZER_BIN_EXEC_ERROR);
1555 }
1556
1557 /* parent */
1558
1559 int result = wait_child(pid);
1560 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001561 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001562 return false;
1563 }
1564 result = WEXITSTATUS(result);
Calin Juravlec9eab382017-01-25 01:17:17 -08001565 bool success = process_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
Calin Juravle80a21252017-01-17 14:43:25 -08001566 // Run dexopt only if needed or forced.
1567 // Note that dexoptanalyzer is executed even if force compilation is enabled.
1568 // We ignore its valid dexopNeeded result, but still check (in process_dexoptanalyzer_result)
1569 // that we only get results for odex files (apk_dir/oat/isa/code.odex) and not
1570 // for oat files from dalvik-cache.
1571 if (success && ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1572 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1573 }
1574
1575 return success;
1576}
1577
Calin Juravlec9eab382017-01-25 01:17:17 -08001578int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001579 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001580 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001581 bool downgrade) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001582 CHECK(pkgname != nullptr);
1583 CHECK(pkgname[0] != 0);
1584 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1585 LOG_FATAL("dexopt flags contains unknown fields\n");
1586 }
1587
Calin Juravled23dee72017-07-06 16:29:11 -07001588 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001589 return -1;
1590 }
1591
1592 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1593 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1594 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001595 }
1596
Calin Juravleebc8a792017-04-04 20:21:05 -07001597 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001598 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1599 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1600 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001601 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1602
1603 // Check if we're dealing with a secondary dex file and if we need to compile it.
1604 std::string oat_dir_str;
Calin Juravle114f0812017-03-08 19:05:07 -08001605 std::string dex_real_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001606 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001607 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001608 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001609 &dex_real_path,
1610 downgrade)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001611 oat_dir = oat_dir_str.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001612 dex_path = dex_real_path.c_str();
Calin Juravle80a21252017-01-17 14:43:25 -08001613 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1614 return 0; // Nothing to do, report success.
1615 }
1616 } else {
1617 return -1; // We had an error, logged in the process method.
1618 }
1619 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001620 // Currently these flags are only use for secondary dex files.
1621 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001622 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1623 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1624 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001625
1626 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001627 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001628 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001629 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001630 return -1;
1631 }
1632
1633 // Create the output OAT file.
1634 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001635 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001636 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001637 if (out_oat_fd.get() < 0) {
1638 return -1;
1639 }
1640
1641 // Open vdex files.
1642 Dex2oatFileWrapper in_vdex_fd;
1643 Dex2oatFileWrapper out_vdex_fd;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001644 if (!open_vdex_files(dex_path, out_oat_path, dexopt_needed, instruction_set, is_public, uid,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001645 is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001646 return -1;
1647 }
1648
Calin Juravlecb556e32017-04-04 20:22:50 -07001649 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1650 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1651 // fully inherit their parent context).
1652 // Note that for primary apk the oat files are created before, in a separate installd
1653 // call which also does the restorecon. TODO(calin): unify the paths.
1654 if (is_secondary_dex) {
1655 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1656 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1657 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1658 return -1;
1659 }
1660 }
1661
Jeff Sharkey90aff262016-12-12 14:28:24 -07001662 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001663 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001664
Calin Juravle7a570e82017-01-14 16:23:30 -08001665 // Create the app image file if needed.
1666 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001667 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001668
Calin Juravle7a570e82017-01-14 16:23:30 -08001669 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001670 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1671 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001672
Calin Juravlec9eab382017-01-25 01:17:17 -08001673 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001674
1675 pid_t pid = fork();
1676 if (pid == 0) {
1677 /* child -- drop privileges before continuing */
1678 drop_capabilities(uid);
1679
Richard Uhler76cc0272016-12-08 10:46:35 +00001680 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001681 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1682 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1683 _exit(67);
1684 }
1685
Richard Uhler76cc0272016-12-08 10:46:35 +00001686 run_dex2oat(input_fd.get(),
1687 out_oat_fd.get(),
1688 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001689 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001690 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001691 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001692 out_oat_path,
1693 swap_fd.get(),
1694 instruction_set,
1695 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001696 debuggable,
1697 boot_complete,
1698 reference_profile_fd.get(),
Calin Juravle52c45822017-07-13 22:50:21 -07001699 class_loader_context);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001700 _exit(68); /* only get here on exec failure */
1701 } else {
1702 int res = wait_child(pid);
1703 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001704 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001705 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001706 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001707 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001708 }
1709 }
1710
Calin Juravlec9eab382017-01-25 01:17:17 -08001711 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001712
1713 // We've been successful, don't delete output.
1714 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001715 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001716 image_fd.SetCleanup(false);
1717 reference_profile_fd.SetCleanup(false);
1718
1719 return 0;
1720}
1721
Calin Juravlec9eab382017-01-25 01:17:17 -08001722// Try to remove the given directory. Log an error if the directory exists
1723// and is empty but could not be removed.
1724static bool rmdir_if_empty(const char* dir) {
1725 if (rmdir(dir) == 0) {
1726 return true;
1727 }
1728 if (errno == ENOENT || errno == ENOTEMPTY) {
1729 return true;
1730 }
1731 PLOG(ERROR) << "Failed to remove dir: " << dir;
1732 return false;
1733}
1734
1735// Try to unlink the given file. Log an error if the file exists and could not
1736// be unlinked.
1737static bool unlink_if_exists(const std::string& file) {
1738 if (unlink(file.c_str()) == 0) {
1739 return true;
1740 }
1741 if (errno == ENOENT) {
1742 return true;
1743
1744 }
1745 PLOG(ERROR) << "Could not unlink: " << file;
1746 return false;
1747}
1748
1749// Create the oat file structure for the secondary dex 'dex_path' and assign
1750// the individual path component to the 'out_' parameters.
1751static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1752 /*out*/char* out_oat_dir, /*out*/char* out_oat_isa_dir, /*out*/char* out_oat_path) {
1753 size_t dirIndex = dex_path.rfind('/');
1754 if (dirIndex == std::string::npos) {
1755 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1756 return false;
1757 }
1758 // TODO(calin): we have similar computations in at lest 3 other places
1759 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1760 // use string append.
1761 std::string apk_dir = dex_path.substr(0, dirIndex);
1762 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1763 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1764
1765 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08001766 /*is_secondary_dex*/true, out_oat_path)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001767 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1768 return false;
1769 }
1770 return true;
1771}
1772
1773// Reconcile the secondary dex 'dex_path' and its generated oat files.
1774// Return true if all the parameters are valid and the secondary dex file was
1775// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1776// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1777// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1778// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1779// Return false if there were errors during processing. In this case
1780// out_secondary_dex_exists will be set to false.
1781bool reconcile_secondary_dex_file(const std::string& dex_path,
1782 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1783 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1784 /*out*/bool* out_secondary_dex_exists) {
1785 // Set out to false to start with, just in case we have validation errors.
1786 *out_secondary_dex_exists = false;
Calin Juravled23dee72017-07-06 16:29:11 -07001787 if (!validate_dex_path_size(dex_path)) {
1788 return false;
1789 }
1790
Calin Juravlec9eab382017-01-25 01:17:17 -08001791 if (isas.size() == 0) {
1792 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1793 return false;
1794 }
1795
1796 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
Calin Juravledd42e272017-09-11 11:50:36 -07001797
1798 // Note that we cannot validate the package path here because the file might not exist
1799 // and we cannot call realpath to resolve system symlinks. Since /data/user/0 symlinks to
1800 // /data/data/ a lot of validations will fail if we attempt to check the package path.
1801 // It is still ok to be more relaxed because any file removal is done after forking and
1802 // dropping capabilities.
Calin Juravlec9eab382017-01-25 01:17:17 -08001803 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
Calin Juravledd42e272017-09-11 11:50:36 -07001804 uid, storage_flag, /*validate_package_path*/ false)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001805 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1806 return false;
1807 }
1808
1809 if (access(dex_path.c_str(), F_OK) == 0) {
1810 // The path exists, nothing to do. The odex files (if any) will be left untouched.
1811 *out_secondary_dex_exists = true;
1812 return true;
1813 } else if (errno != ENOENT) {
1814 PLOG(ERROR) << "Failed to check access to secondary dex " << dex_path;
1815 return false;
1816 }
1817
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001818 // As a security measure we want to unlink art artifacts with the reduced capabilities
1819 // of the package user id. So we fork and drop capabilities in the child.
1820 pid_t pid = fork();
1821 if (pid == 0) {
1822 // The secondary dex does not exist anymore. Clear any generated files.
1823 char oat_path[PKG_PATH_MAX];
1824 char oat_dir[PKG_PATH_MAX];
1825 char oat_isa_dir[PKG_PATH_MAX];
1826 bool result = true;
1827 /* child -- drop privileges before continuing */
1828 drop_capabilities(uid);
1829 for (size_t i = 0; i < isas.size(); i++) {
1830 if (!create_secondary_dex_oat_layout(dex_path,
1831 isas[i],
1832 oat_dir,
1833 oat_isa_dir,
1834 oat_path)) {
1835 LOG(ERROR) << "Could not create secondary odex layout: "
1836 << dex_path;
1837 result = false;
1838 continue;
1839 }
Calin Juravle51314092017-05-18 15:33:05 -07001840
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001841 // Delete oat/vdex/art files.
1842 result = unlink_if_exists(oat_path) && result;
1843 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1844 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08001845
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001846 // Delete profiles.
1847 std::string current_profile = create_current_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07001848 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001849 std::string reference_profile = create_reference_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07001850 dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001851 result = unlink_if_exists(current_profile) && result;
1852 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07001853
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001854 // We upgraded once the location of current profile for secondary dex files.
1855 // Check for any previous left-overs and remove them as well.
1856 std::string old_current_profile = dex_path + ".prof";
1857 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07001858
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001859 // Try removing the directories as well, they might be empty.
1860 result = rmdir_if_empty(oat_isa_dir) && result;
1861 result = rmdir_if_empty(oat_dir) && result;
1862 }
1863 result ? _exit(0) : _exit(1);
Calin Juravlec9eab382017-01-25 01:17:17 -08001864 }
1865
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001866 int return_code = wait_child(pid);
1867 return return_code == 0;
Calin Juravlec9eab382017-01-25 01:17:17 -08001868}
1869
Jeff Sharkey90aff262016-12-12 14:28:24 -07001870// Helper for move_ab, so that we can have common failure-case cleanup.
1871static bool unlink_and_rename(const char* from, const char* to) {
1872 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
1873 // return a failure.
1874 struct stat s;
1875 if (stat(to, &s) == 0) {
1876 if (!S_ISREG(s.st_mode)) {
1877 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
1878 return false;
1879 }
1880 if (unlink(to) != 0) {
1881 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
1882 return false;
1883 }
1884 } else {
1885 // This may be a permission problem. We could investigate the error code, but we'll just
1886 // let the rename failure do the work for us.
1887 }
1888
1889 // Try to rename "to" to "from."
1890 if (rename(from, to) != 0) {
1891 PLOG(ERROR) << "Could not rename " << from << " to " << to;
1892 return false;
1893 }
1894 return true;
1895}
1896
1897// Move/rename a B artifact (from) to an A artifact (to).
1898static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
1899 // Check whether B exists.
1900 {
1901 struct stat s;
1902 if (stat(b_path.c_str(), &s) != 0) {
1903 // Silently ignore for now. The service calling this isn't smart enough to understand
1904 // lack of artifacts at the moment.
1905 return false;
1906 }
1907 if (!S_ISREG(s.st_mode)) {
1908 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
1909 // Try to unlink, but swallow errors.
1910 unlink(b_path.c_str());
1911 return false;
1912 }
1913 }
1914
1915 // Rename B to A.
1916 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
1917 // Delete the b_path so we don't try again (or fail earlier).
1918 if (unlink(b_path.c_str()) != 0) {
1919 PLOG(ERROR) << "Could not unlink " << b_path;
1920 }
1921
1922 return false;
1923 }
1924
1925 return true;
1926}
1927
1928bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1929 // Get the current slot suffix. No suffix, no A/B.
1930 std::string slot_suffix;
1931 {
1932 char buf[kPropertyValueMax];
1933 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
1934 return false;
1935 }
1936 slot_suffix = buf;
1937
1938 if (!ValidateTargetSlotSuffix(slot_suffix)) {
1939 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
1940 return false;
1941 }
1942 }
1943
1944 // Validate other inputs.
1945 if (validate_apk_path(apk_path) != 0) {
1946 LOG(ERROR) << "Invalid apk_path: " << apk_path;
1947 return false;
1948 }
1949 if (validate_apk_path(oat_dir) != 0) {
1950 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
1951 return false;
1952 }
1953
1954 char a_path[PKG_PATH_MAX];
1955 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
1956 return false;
1957 }
1958 const std::string a_vdex_path = create_vdex_filename(a_path);
1959 const std::string a_image_path = create_image_filename(a_path);
1960
1961 // B path = A path + slot suffix.
1962 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
1963 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
1964 const std::string b_image_path = StringPrintf("%s.%s",
1965 a_image_path.c_str(),
1966 slot_suffix.c_str());
1967
1968 bool success = true;
1969 if (move_ab_path(b_path, a_path)) {
1970 if (move_ab_path(b_vdex_path, a_vdex_path)) {
1971 // Note: we can live without an app image. As such, ignore failure to move the image file.
1972 // If we decide to require the app image, or the app image being moved correctly,
1973 // then change accordingly.
1974 constexpr bool kIgnoreAppImageFailure = true;
1975
1976 if (!a_image_path.empty()) {
1977 if (!move_ab_path(b_image_path, a_image_path)) {
1978 unlink(a_image_path.c_str());
1979 if (!kIgnoreAppImageFailure) {
1980 success = false;
1981 }
1982 }
1983 }
1984 } else {
1985 // Cleanup: delete B image, ignore errors.
1986 unlink(b_image_path.c_str());
1987 success = false;
1988 }
1989 } else {
1990 // Cleanup: delete B image, ignore errors.
1991 unlink(b_vdex_path.c_str());
1992 unlink(b_image_path.c_str());
1993 success = false;
1994 }
1995 return success;
1996}
1997
1998bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
1999 // Delete the oat/odex file.
2000 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002001 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002002 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002003 return false;
2004 }
2005
2006 // In case of a permission failure report the issue. Otherwise just print a warning.
2007 auto unlink_and_check = [](const char* path) -> bool {
2008 int result = unlink(path);
2009 if (result != 0) {
2010 if (errno == EACCES || errno == EPERM) {
2011 PLOG(ERROR) << "Could not unlink " << path;
2012 return false;
2013 }
2014 PLOG(WARNING) << "Could not unlink " << path;
2015 }
2016 return true;
2017 };
2018
2019 // Delete the oat/odex file.
2020 bool return_value_oat = unlink_and_check(out_path);
2021
2022 // Derive and delete the app image.
2023 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2024
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002025 // Derive and delete the vdex file.
2026 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2027
Jeff Sharkey90aff262016-12-12 14:28:24 -07002028 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002029 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002030}
2031
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002032static bool is_absolute_path(const std::string& path) {
2033 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2034 LOG(ERROR) << "Invalid absolute path " << path;
2035 return false;
2036 } else {
2037 return true;
2038 }
2039}
2040
2041static bool is_valid_instruction_set(const std::string& instruction_set) {
2042 // TODO: add explicit whitelisting of instruction sets
2043 if (instruction_set.find('/') != std::string::npos) {
2044 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2045 return false;
2046 } else {
2047 return true;
2048 }
2049}
2050
2051bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2052 const char *apk_path, const char *instruction_set) {
2053 std::string oat_dir_ = oat_dir;
2054 std::string apk_path_ = apk_path;
2055 std::string instruction_set_ = instruction_set;
2056
2057 if (!is_absolute_path(oat_dir_)) return false;
2058 if (!is_absolute_path(apk_path_)) return false;
2059 if (!is_valid_instruction_set(instruction_set_)) return false;
2060
2061 std::string::size_type end = apk_path_.rfind('.');
2062 std::string::size_type start = apk_path_.rfind('/', end);
2063 if (end == std::string::npos || start == std::string::npos) {
2064 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2065 return false;
2066 }
2067
2068 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2069 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2070 const char* res = res_.c_str();
2071 if (strlen(res) >= PKG_PATH_MAX) {
2072 LOG(ERROR) << "Result too large";
2073 return false;
2074 } else {
2075 strlcpy(path, res, PKG_PATH_MAX);
2076 return true;
2077 }
2078}
2079
2080bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2081 const char *instruction_set) {
2082 std::string apk_path_ = apk_path;
2083 std::string instruction_set_ = instruction_set;
2084
2085 if (!is_absolute_path(apk_path_)) return false;
2086 if (!is_valid_instruction_set(instruction_set_)) return false;
2087
2088 std::string::size_type end = apk_path_.rfind('.');
2089 std::string::size_type start = apk_path_.rfind('/', end);
2090 if (end == std::string::npos || start == std::string::npos) {
2091 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2092 return false;
2093 }
2094
2095 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2096 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2097}
2098
2099bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2100 const char *instruction_set) {
2101 std::string src_ = src;
2102 std::string instruction_set_ = instruction_set;
2103
2104 if (!is_absolute_path(src_)) return false;
2105 if (!is_valid_instruction_set(instruction_set_)) return false;
2106
2107 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2108 if (*it == '/') {
2109 *it = '@';
2110 }
2111 }
2112
2113 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2114 + DALVIK_CACHE_POSTFIX;
2115 const char* res = res_.c_str();
2116 if (strlen(res) >= PKG_PATH_MAX) {
2117 LOG(ERROR) << "Result too large";
2118 return false;
2119 } else {
2120 strlcpy(path, res, PKG_PATH_MAX);
2121 return true;
2122 }
2123}
2124
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002125} // namespace installd
2126} // namespace android