blob: 6c069b2214e637eadfadc4ad3c0935b77ea310ea [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
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070056// Should minidebug info be included in compiled artifacts? Even if this value is
57// "true," usage might still be conditional to other constraints, e.g., system
58// property overrides.
59static constexpr bool kEnableMinidebugInfo = true;
60
61static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
62static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
63static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080064static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070065
Calin Juravle114f0812017-03-08 19:05:07 -080066// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
67struct FreeDelete {
68 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
69 void operator()(const void* ptr) const {
70 free(const_cast<void*>(ptr));
71 }
72};
73
74// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
75template <typename T>
76using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
77
Calin Juravle1a0af3b2017-03-09 14:33:33 -080078static unique_fd invalid_unique_fd() {
79 return unique_fd(-1);
80}
81
Andreas Gampe6a9cf722017-07-24 16:49:10 -070082static bool is_debug_runtime() {
83 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
84}
85
David Sehra3b5ab62017-10-25 14:27:29 -070086static bool is_debuggable_build() {
87 return android::base::GetBoolProperty("ro.debuggable", false);
88}
89
Jeff Sharkey90aff262016-12-12 14:28:24 -070090static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080091 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070092 if (ufd.get() < 0) {
93 if (errno != ENOENT) {
94 PLOG(WARNING) << "Could not open profile " << profile;
95 return false;
96 } else {
97 // Nothing to clear. That's ok.
98 return true;
99 }
100 }
101
102 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
103 if (errno != EWOULDBLOCK) {
104 PLOG(WARNING) << "Error locking profile " << profile;
105 }
106 // This implies that the app owning this profile is running
107 // (and has acquired the lock).
108 //
109 // If we can't acquire the lock bail out since clearing is useless anyway
110 // (the app will write again to the profile).
111 //
112 // Note:
113 // This does not impact the this is not an issue for the profiling correctness.
114 // In case this is needed because of an app upgrade, profiles will still be
115 // eventually cleared by the app itself due to checksum mismatch.
116 // If this is needed because profman advised, then keeping the data around
117 // until the next run is again not an issue.
118 //
119 // If the app attempts to acquire a lock while we've held one here,
120 // it will simply skip the current write cycle.
121 return false;
122 }
123
124 bool truncated = ftruncate(ufd.get(), 0) == 0;
125 if (!truncated) {
126 PLOG(WARNING) << "Could not truncate " << profile;
127 }
128 if (flock(ufd.get(), LOCK_UN) != 0) {
129 PLOG(WARNING) << "Error unlocking profile " << profile;
130 }
131 return truncated;
132}
133
Calin Juravle114f0812017-03-08 19:05:07 -0800134// Clear the reference profile for the given location.
135// The location is the package name for primary apks or the dex path for secondary dex files.
136static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
137 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700138}
139
Calin Juravle114f0812017-03-08 19:05:07 -0800140// Clear the reference profile for the given location.
141// The location is the package name for primary apks or the dex path for secondary dex files.
142static bool clear_current_profile(const std::string& pkgname, userid_t user,
143 bool is_secondary_dex) {
144 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700145}
146
Calin Juravle114f0812017-03-08 19:05:07 -0800147// Clear the reference profile for the primary apk of the given package.
148bool clear_primary_reference_profile(const std::string& pkgname) {
149 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
150}
151
152// Clear all current profile for the primary apk of the given package.
153bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700154 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800155 // 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 -0700156 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
157 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800158 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700159 }
160 return success;
161}
162
Calin Juravle114f0812017-03-08 19:05:07 -0800163// Clear the current profile for the primary apk of the given package and user.
164bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
165 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
166}
167
Jeff Sharkey90aff262016-12-12 14:28:24 -0700168static int split_count(const char *str)
169{
170 char *ctx;
171 int count = 0;
172 char buf[kPropertyValueMax];
173
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600174 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700175 char *pBuf = buf;
176
177 while(strtok_r(pBuf, " ", &ctx) != NULL) {
178 count++;
179 pBuf = NULL;
180 }
181
182 return count;
183}
184
185static int split(char *buf, const char **argv)
186{
187 char *ctx;
188 int count = 0;
189 char *tok;
190 char *pBuf = buf;
191
192 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
193 argv[count++] = tok;
194 pBuf = NULL;
195 }
196
197 return count;
198}
199
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700200static const char* get_location_from_path(const char* path) {
201 static constexpr char kLocationSeparator = '/';
202 const char *location = strrchr(path, kLocationSeparator);
203 if (location == NULL) {
204 return path;
205 } else {
206 // Skip the separator character.
207 return location + 1;
208 }
209}
210
Jeff Sharkey90aff262016-12-12 14:28:24 -0700211static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
212 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100213 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700214 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
David Sehra3b5ab62017-10-25 14:27:29 -0700215 const char* class_loader_context) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700216 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
217
218 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
219 ALOGE("Instruction set %s longer than max length of %d",
220 instruction_set, MAX_INSTRUCTION_SET_LEN);
221 return;
222 }
223
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700224 // Get the relative path to the input file.
225 const char* relative_input_file_name = get_location_from_path(input_file_name);
226
Jeff Sharkey90aff262016-12-12 14:28:24 -0700227 char dex2oat_Xms_flag[kPropertyValueMax];
228 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
229
230 char dex2oat_Xmx_flag[kPropertyValueMax];
231 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
232
233 char dex2oat_threads_buf[kPropertyValueMax];
234 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
235 ? "dalvik.vm.dex2oat-threads"
236 : "dalvik.vm.boot-dex2oat-threads",
237 dex2oat_threads_buf,
238 NULL) > 0;
239 char dex2oat_threads_arg[kPropertyValueMax + 2];
240 if (have_dex2oat_threads_flag) {
241 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
242 }
243
244 char dex2oat_isa_features_key[kPropertyKeyMax];
245 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
246 char dex2oat_isa_features[kPropertyValueMax];
247 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
248 dex2oat_isa_features, NULL) > 0;
249
250 char dex2oat_isa_variant_key[kPropertyKeyMax];
251 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
252 char dex2oat_isa_variant[kPropertyValueMax];
253 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
254 dex2oat_isa_variant, NULL) > 0;
255
256 const char *dex2oat_norelocation = "-Xnorelocate";
257 bool have_dex2oat_relocation_skip_flag = false;
258
259 char dex2oat_flags[kPropertyValueMax];
260 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
261 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
262 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
263
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100264 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700265 char vold_decrypt[kPropertyValueMax];
266 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
267 bool skip_compilation = (have_vold_decrypt &&
268 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
269 (strcmp(vold_decrypt, "1") == 0)));
270
271 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
272
273 char app_image_format[kPropertyValueMax];
274 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
275 bool have_app_image_format =
276 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
277 if (have_app_image_format) {
278 sprintf(image_format_arg, "--image-format=%s", app_image_format);
279 }
280
281 char dex2oat_large_app_threshold[kPropertyValueMax];
282 bool have_dex2oat_large_app_threshold =
283 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
284 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
285 if (have_dex2oat_large_app_threshold) {
286 sprintf(dex2oat_large_app_threshold_arg,
287 "--very-large-app-threshold=%s",
288 dex2oat_large_app_threshold);
289 }
290
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700291 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700292 const char* dex2oat_bin = "/system/bin/dex2oat";
293 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700294 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700295 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
296 dex2oat_bin = kDex2oatDebugPath;
297 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700298
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700299 bool generate_minidebug_info = kEnableMinidebugInfo &&
300 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
301 kMinidebugInfoSystemPropertyDefault);
302
Jeff Sharkey90aff262016-12-12 14:28:24 -0700303 static const char* RUNTIME_ARG = "--runtime-arg";
304
305 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
306
George Burgess IV36cebe772017-01-25 11:52:01 -0800307 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
308 // use arraysize instead.
309 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
310 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
311 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
312 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
313 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
314 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
315 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
316 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
317 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
318 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
319 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
320 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700321 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800322 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700323 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800324 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700325 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
326 char class_loader_context_arg[class_loader_context_size];
327 if (class_loader_context != nullptr) {
328 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
329 class_loader_context);
330 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700331
332 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700333 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700334 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
335 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
336 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
337 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
338 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
339 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
340 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
341 if (swap_fd >= 0) {
342 have_dex2oat_swap_fd = true;
343 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
344 }
345 if (image_fd >= 0) {
346 have_dex2oat_image_fd = true;
347 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
348 }
349
350 if (have_dex2oat_Xms_flag) {
351 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
352 }
353 if (have_dex2oat_Xmx_flag) {
354 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
355 }
356
357 // Compute compiler filter.
358
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100359 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700360 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600361 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
362 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700363 have_dex2oat_compiler_filter_flag = true;
364 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100365 } else if (compiler_filter != nullptr) {
366 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700367 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100368 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
369 have_dex2oat_compiler_filter_flag = true;
370 } else {
371 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
372 compiler_filter,
373 kPropertyValueMax);
374 }
375 }
376
377 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700378 char dex2oat_compiler_filter_flag[kPropertyValueMax];
379 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
380 dex2oat_compiler_filter_flag, NULL) > 0;
381 if (have_dex2oat_compiler_filter_flag) {
382 sprintf(dex2oat_compiler_filter_arg,
383 "--compiler-filter=%s",
384 dex2oat_compiler_filter_flag);
385 }
386 }
387
388 // Check whether all apps should be compiled debuggable.
389 if (!debuggable) {
390 char prop_buf[kPropertyValueMax];
391 debuggable =
392 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
393 (prop_buf[0] == '1');
394 }
395 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
396 if (profile_fd != -1) {
397 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
398 }
399
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700400 // Get the directory of the apk to pass as a base classpath directory.
401 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
402 std::string apk_dir(input_file_name);
403 unsigned long dir_index = apk_dir.rfind('/');
404 bool has_base_dir = dir_index != std::string::npos;
405 if (has_base_dir) {
406 apk_dir = apk_dir.substr(0, dir_index);
407 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
408 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700409
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700410
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700411 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700412
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800413 // Disable cdex if update input vdex is true since this combination of options is not
414 // supported.
Mathieu Chartier1fb463e2018-01-09 15:16:10 -0800415 // Disable cdex for non-background compiles since we don't want to regress app install until
416 // there are enough benefits to justify the tradeoff.
417 const bool disable_cdex = !background_job_compile || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800418
Jeff Sharkey90aff262016-12-12 14:28:24 -0700419 const char* argv[9 // program name, mandatory arguments and the final NULL
420 + (have_dex2oat_isa_variant ? 1 : 0)
421 + (have_dex2oat_isa_features ? 1 : 0)
422 + (have_dex2oat_Xms_flag ? 2 : 0)
423 + (have_dex2oat_Xmx_flag ? 2 : 0)
424 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
425 + (have_dex2oat_threads_flag ? 1 : 0)
426 + (have_dex2oat_swap_fd ? 1 : 0)
427 + (have_dex2oat_image_fd ? 1 : 0)
428 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
429 + (generate_debug_info ? 1 : 0)
430 + (debuggable ? 1 : 0)
431 + (have_app_image_format ? 1 : 0)
432 + dex2oat_flags_count
433 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700434 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700435 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700436 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800437 + (disable_cdex ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700438 + (generate_minidebug_info ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700439 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700440 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700441 argv[i++] = zip_fd_arg;
442 argv[i++] = zip_location_arg;
443 argv[i++] = input_vdex_fd_arg;
444 argv[i++] = output_vdex_fd_arg;
445 argv[i++] = oat_fd_arg;
446 argv[i++] = oat_location_arg;
447 argv[i++] = instruction_set_arg;
448 if (have_dex2oat_isa_variant) {
449 argv[i++] = instruction_set_variant_arg;
450 }
451 if (have_dex2oat_isa_features) {
452 argv[i++] = instruction_set_features_arg;
453 }
454 if (have_dex2oat_Xms_flag) {
455 argv[i++] = RUNTIME_ARG;
456 argv[i++] = dex2oat_Xms_arg;
457 }
458 if (have_dex2oat_Xmx_flag) {
459 argv[i++] = RUNTIME_ARG;
460 argv[i++] = dex2oat_Xmx_arg;
461 }
462 if (have_dex2oat_compiler_filter_flag) {
463 argv[i++] = dex2oat_compiler_filter_arg;
464 }
465 if (have_dex2oat_threads_flag) {
466 argv[i++] = dex2oat_threads_arg;
467 }
468 if (have_dex2oat_swap_fd) {
469 argv[i++] = dex2oat_swap_fd;
470 }
471 if (have_dex2oat_image_fd) {
472 argv[i++] = dex2oat_image_fd;
473 }
474 if (generate_debug_info) {
475 argv[i++] = "--generate-debug-info";
476 }
477 if (debuggable) {
478 argv[i++] = "--debuggable";
479 }
480 if (have_app_image_format) {
481 argv[i++] = image_format_arg;
482 }
483 if (have_dex2oat_large_app_threshold) {
484 argv[i++] = dex2oat_large_app_threshold_arg;
485 }
486 if (dex2oat_flags_count) {
487 i += split(dex2oat_flags, argv + i);
488 }
489 if (have_dex2oat_relocation_skip_flag) {
490 argv[i++] = RUNTIME_ARG;
491 argv[i++] = dex2oat_norelocation;
492 }
493 if (profile_fd != -1) {
494 argv[i++] = profile_arg;
495 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700496 if (has_base_dir) {
497 argv[i++] = base_dir;
498 }
Calin Juravle52c45822017-07-13 22:50:21 -0700499 if (class_loader_context != nullptr) {
500 argv[i++] = class_loader_context_arg;
501 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700502 if (generate_minidebug_info) {
503 argv[i++] = kMinidebugDex2oatFlag;
504 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800505 if (disable_cdex) {
506 argv[i++] = kDisableCompactDexFlag;
507 }
Calin Juravle52c45822017-07-13 22:50:21 -0700508
Jeff Sharkey90aff262016-12-12 14:28:24 -0700509 // Do not add after dex2oat_flags, they should override others for debugging.
510 argv[i] = NULL;
511
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700512 execv(dex2oat_bin, (char * const *)argv);
513 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700514}
515
516/*
517 * Whether dexopt should use a swap file when compiling an APK.
518 *
519 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
520 * itself, anyways).
521 *
522 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
523 *
524 * Otherwise, return true if this is a low-mem device.
525 *
526 * Otherwise, return default value.
527 */
528static bool kAlwaysProvideSwapFile = false;
529static bool kDefaultProvideSwapFile = true;
530
531static bool ShouldUseSwapFileForDexopt() {
532 if (kAlwaysProvideSwapFile) {
533 return true;
534 }
535
536 // Check the "override" property. If it exists, return value == "true".
537 char dex2oat_prop_buf[kPropertyValueMax];
538 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
539 if (strcmp(dex2oat_prop_buf, "true") == 0) {
540 return true;
541 } else {
542 return false;
543 }
544 }
545
546 // Shortcut for default value. This is an implementation optimization for the process sketched
547 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
548 // as low-mem is never returning false. The compiler will optimize this away if it can.
549 if (kDefaultProvideSwapFile) {
550 return true;
551 }
552
553 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
554 if (is_low_mem) {
555 return true;
556 }
557
558 // Default value must be false here.
559 return kDefaultProvideSwapFile;
560}
561
Richard Uhler76cc0272016-12-08 10:46:35 +0000562static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700563 if (set_to_bg) {
564 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
565 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
566 exit(70);
567 }
568 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
569 ALOGE("setpriority failed: %s\n", strerror(errno));
570 exit(71);
571 }
572 }
573}
574
Calin Juravle29591732017-11-20 17:46:19 -0800575static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
576 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800577 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800578 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800579 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800580 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800581 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700582 }
Calin Juravle114f0812017-03-08 19:05:07 -0800583 // Profiles should belong to the app; make sure of that by giving ownership to
584 // the app uid. If we cannot do that, there's no point in returning the fd
585 // since dex2oat/profman will fail with SElinux denials.
586 if (fchown(fd.get(), uid, uid) < 0) {
587 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800588 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800589 }
Calin Juravle29591732017-11-20 17:46:19 -0800590 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800591}
592
Calin Juravle29591732017-11-20 17:46:19 -0800593static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800594 // Do not follow symlinks when opening a profile:
595 // - primary profiles should not contain symlinks in their paths
596 // - secondary dex paths should have been already resolved and validated
597 flags |= O_NOFOLLOW;
598
Calin Juravle29591732017-11-20 17:46:19 -0800599 // Check if we need to create the profile
600 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
601 unique_fd fd;
602 if ((flags & O_CREAT) != 0) {
603 fd = create_profile(uid, profile, flags);
604 } else {
605 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
606 }
607
Calin Juravle114f0812017-03-08 19:05:07 -0800608 if (fd.get() < 0) {
609 if (errno != ENOENT) {
610 // Profiles might be missing for various reasons. For example, in a
611 // multi-user environment, the profile directory for one user can be created
612 // after we start a merge. In this case the current profile for that user
613 // will not be found.
614 // Also, the secondary dex profiles might be deleted by the app at any time,
615 // so we can't we need to prepare if they are missing.
616 PLOG(ERROR) << "Failed to open profile " << profile;
617 }
618 return invalid_unique_fd();
619 }
620
Jeff Sharkey90aff262016-12-12 14:28:24 -0700621 return fd;
622}
623
Calin Juravle114f0812017-03-08 19:05:07 -0800624static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
625 bool is_secondary_dex) {
626 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800627 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800628}
629
630static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
631 bool is_secondary_dex) {
632 std::string profile = create_reference_profile_path(location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800633 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
634}
635
636static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
637 const std::string& code_path) {
638 std::string profile = create_snapshot_profile_path(package_name, code_path);
639 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800640}
641
642static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800643 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700644 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800645 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
646 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700647
Calin Juravle114f0812017-03-08 19:05:07 -0800648 // For secondary dex files, we don't really need the user but we use it for sanity checks.
649 // Note: the user owning the dex file should be the current user.
650 std::vector<userid_t> users;
651 if (is_secondary_dex){
652 users.push_back(multiuser_get_user_id(uid));
653 } else {
654 users = get_known_users(/*volume_uuid*/ nullptr);
655 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700656 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800657 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700658 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800659 if (profile_fd.get() >= 0) {
660 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 }
662 }
663}
664
665static void drop_capabilities(uid_t uid) {
666 if (setgid(uid) != 0) {
667 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
668 exit(64);
669 }
670 if (setuid(uid) != 0) {
671 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
672 exit(65);
673 }
674 // drop capabilities
675 struct __user_cap_header_struct capheader;
676 struct __user_cap_data_struct capdata[2];
677 memset(&capheader, 0, sizeof(capheader));
678 memset(&capdata, 0, sizeof(capdata));
679 capheader.version = _LINUX_CAPABILITY_VERSION_3;
680 if (capset(&capheader, &capdata[0]) < 0) {
681 ALOGE("capset failed: %s\n", strerror(errno));
682 exit(66);
683 }
684}
685
686static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
687static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
688static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
689static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
690static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
691
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800692static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
693 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694 static const size_t MAX_INT_LEN = 32;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700695 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700696
697 std::vector<std::string> profile_args(profiles_fd.size());
698 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
699 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800700 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700701 profile_args[k].assign(profile_buf);
702 }
703 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800704 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705
706 // program name, reference profile fd, the final NULL and the profile fds
707 const char* argv[3 + profiles_fd.size()];
708 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700709 argv[i++] = profman_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700710 argv[i++] = reference_profile_arg;
711 for (size_t k = 0; k < profile_args.size(); k++) {
712 argv[i++] = profile_args[k].c_str();
713 }
714 // Do not add after dex2oat_flags, they should override others for debugging.
715 argv[i] = NULL;
716
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700717 execv(profman_bin, (char * const *)argv);
718 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700719 exit(68); /* only get here on exec failure */
720}
721
722// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800723// The location is the package name for primary apks or the dex path for secondary dex files.
724// Returns true if there is enough information in the current profiles that makes it
725// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700726// If the return value is true all the current profiles would have been merged into
727// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800728static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800729 std::vector<unique_fd> profiles_fd;
730 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800731 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800732 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700733 // Skip profile guided compilation because no profiles were found.
734 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700735 return false;
736 }
737
Jeff Sharkey90aff262016-12-12 14:28:24 -0700738 pid_t pid = fork();
739 if (pid == 0) {
740 /* child -- drop privileges before continuing */
741 drop_capabilities(uid);
742 run_profman_merge(profiles_fd, reference_profile_fd);
743 exit(68); /* only get here on exec failure */
744 }
745 /* parent */
746 int return_code = wait_child(pid);
747 bool need_to_compile = false;
748 bool should_clear_current_profiles = false;
749 bool should_clear_reference_profile = false;
750 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800751 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700752 } else {
753 return_code = WEXITSTATUS(return_code);
754 switch (return_code) {
755 case PROFMAN_BIN_RETURN_CODE_COMPILE:
756 need_to_compile = true;
757 should_clear_current_profiles = true;
758 should_clear_reference_profile = false;
759 break;
760 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
761 need_to_compile = false;
762 should_clear_current_profiles = false;
763 should_clear_reference_profile = false;
764 break;
765 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800766 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700767 need_to_compile = false;
768 should_clear_current_profiles = true;
769 should_clear_reference_profile = true;
770 break;
771 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
772 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
773 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800774 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 need_to_compile = false;
776 should_clear_current_profiles = false;
777 should_clear_reference_profile = false;
778 break;
779 default:
780 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800781 LOG(WARNING) << "Unknown error code while processing profiles for location "
782 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700783 need_to_compile = false;
784 should_clear_current_profiles = true;
785 should_clear_reference_profile = true;
786 break;
787 }
788 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800789
Jeff Sharkey90aff262016-12-12 14:28:24 -0700790 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800791 if (is_secondary_dex) {
792 // For secondary dex files, the owning user is the current user.
793 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
794 } else {
795 clear_primary_current_profiles(location);
796 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700797 }
798 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800799 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800 }
801 return need_to_compile;
802}
803
Calin Juravle114f0812017-03-08 19:05:07 -0800804// Decides if profile guided compilation is needed or not based on existing profiles.
805// The analysis is done for the primary apks of the given package.
806// Returns true if there is enough information in the current profiles that makes it
807// worth to recompile the package.
808// If the return value is true all the current profiles would have been merged into
809// the reference profiles accessible with open_reference_profile().
810bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
811 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
812}
813
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800814static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
815 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800817 const std::vector<unique_fd>& apk_fds,
818 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700819 std::vector<std::string> profman_args;
820 static const char* PROFMAN_BIN = "/system/bin/profman";
821 profman_args.push_back(PROFMAN_BIN);
822 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800823 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700824 if (reference_profile_fd != -1) {
825 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800826 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800828 for (size_t i = 0; i < profile_fds.size(); i++) {
829 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700830 }
831 for (const std::string& dex_location : dex_locations) {
832 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
833 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800834 for (size_t i = 0; i < apk_fds.size(); i++) {
835 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836 }
837 const char **argv = new const char*[profman_args.size() + 1];
838 size_t i = 0;
839 for (const std::string& profman_arg : profman_args) {
840 argv[i++] = profman_arg.c_str();
841 }
842 argv[i] = NULL;
843
844 execv(PROFMAN_BIN, (char * const *)argv);
845 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
846 exit(68); /* only get here on exec failure */
847}
848
Calin Juravle76268c52017-03-09 13:19:42 -0800849bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800850 std::vector<unique_fd> profile_fds;
851 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800852 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853
Calin Juravle114f0812017-03-08 19:05:07 -0800854 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
855 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800857 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700858 const bool has_profiles = !profile_fds.empty();
859
860 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800861 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700862 return false;
863 }
864
Calin Juravle114f0812017-03-08 19:05:07 -0800865 unique_fd output_fd(open(out_file_name.c_str(),
866 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700867 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
868 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
869 return false;
870 }
871 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
872 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800873 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700874 for (const std::string& code_full_path : code_full_paths) {
875 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800876 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877 if (apk_fd == -1) {
878 ALOGE("installd cannot open '%s'\n", full_path);
879 return false;
880 }
881 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800882 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883 }
884
885 pid_t pid = fork();
886 if (pid == 0) {
887 /* child -- drop privileges before continuing */
888 drop_capabilities(uid);
889 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
890 apk_fds, output_fd);
891 exit(68); /* only get here on exec failure */
892 }
893 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 int return_code = wait_child(pid);
895 if (!WIFEXITED(return_code)) {
896 LOG(WARNING) << "profman failed for package " << pkgname << ": "
897 << return_code;
898 return false;
899 }
900 return true;
901}
902
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700903bool copy_system_profile(const std::string& system_profile,
904 uid_t packageUid, const std::string& data_profile_location) {
905 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
906 unique_fd out_fd(open_reference_profile(packageUid,
907 data_profile_location,
908 /*read_write*/ true,
909 /*secondary*/ false));
910 if (in_fd.get() < 0) {
911 PLOG(WARNING) << "Could not open profile " << system_profile;
912 return false;
913 }
914 if (out_fd.get() < 0) {
915 PLOG(WARNING) << "Could not open profile " << data_profile_location;
916 return false;
917 }
918
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700919 // As a security measure we want to write the profile information with the reduced capabilities
920 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700921 pid_t pid = fork();
922 if (pid == 0) {
923 /* child -- drop privileges before continuing */
924 drop_capabilities(packageUid);
925
926 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
927 if (errno != EWOULDBLOCK) {
928 PLOG(WARNING) << "Error locking profile " << data_profile_location;
929 }
930 // This implies that the app owning this profile is running
931 // (and has acquired the lock).
932 //
933 // The app never acquires the lock for the reference profiles of primary apks.
934 // Only dex2oat from installd will do that. Since installd is single threaded
935 // we should not see this case. Nevertheless be prepared for it.
936 PLOG(WARNING) << "Failed to flock " << data_profile_location;
937 return false;
938 }
939
940 bool truncated = ftruncate(out_fd.get(), 0) == 0;
941 if (!truncated) {
942 PLOG(WARNING) << "Could not truncate " << data_profile_location;
943 }
944
945 // Copy over data.
946 static constexpr size_t kBufferSize = 4 * 1024;
947 char buffer[kBufferSize];
948 while (true) {
949 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
950 if (bytes == 0) {
951 break;
952 }
953 write(out_fd.get(), buffer, bytes);
954 }
955 if (flock(out_fd.get(), LOCK_UN) != 0) {
956 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
957 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700958 // Use _exit since we don't want to run the global destructors in the child.
959 // b/62597429
960 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700961 }
962 /* parent */
963 int return_code = wait_child(pid);
964 return return_code == 0;
965}
966
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
968 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
969 if (EndsWith(oat_path, ".dex")) {
970 std::string new_path = oat_path;
971 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800972 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 return new_path;
974 }
975
976 // An odex entry. Not that this may not be an extension, e.g., in the OTA
977 // case (where the base name will have an extension for the B artifact).
978 size_t odex_pos = oat_path.rfind(".odex");
979 if (odex_pos != std::string::npos) {
980 std::string new_path = oat_path;
981 new_path.replace(odex_pos, strlen(".odex"), new_ext);
982 CHECK_NE(new_path.find(new_ext), std::string::npos);
983 return new_path;
984 }
985
986 // Don't know how to handle this.
987 return "";
988}
989
990// Translate the given oat path to an art (app image) path. An empty string
991// denotes an error.
992static std::string create_image_filename(const std::string& oat_path) {
993 return replace_file_extension(oat_path, ".art");
994}
995
996// Translate the given oat path to a vdex path. An empty string denotes an error.
997static std::string create_vdex_filename(const std::string& oat_path) {
998 return replace_file_extension(oat_path, ".vdex");
999}
1000
Jeff Sharkey90aff262016-12-12 14:28:24 -07001001static int open_output_file(const char* file_name, bool recreate, int permissions) {
1002 int flags = O_RDWR | O_CREAT;
1003 if (recreate) {
1004 if (unlink(file_name) < 0) {
1005 if (errno != ENOENT) {
1006 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1007 }
1008 }
1009 flags |= O_EXCL;
1010 }
1011 return open(file_name, flags, permissions);
1012}
1013
Calin Juravle2289c0a2017-02-15 12:44:14 -08001014static bool set_permissions_and_ownership(
1015 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1016 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1017 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018 if (fchmod(fd,
1019 S_IRUSR|S_IWUSR|S_IRGRP |
1020 (is_public ? S_IROTH : 0)) < 0) {
1021 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1022 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001023 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001024 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1025 return false;
1026 }
1027 return true;
1028}
1029
1030static bool IsOutputDalvikCache(const char* oat_dir) {
1031 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1032 // into '!'. Play it safe by handling it both.
1033 // TODO: ensure we never get null.
1034 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1035 return oat_dir == nullptr || oat_dir[0] == '!';
1036}
1037
Calin Juravled23dee72017-07-06 16:29:11 -07001038// Best-effort check whether we can fit the the path into our buffers.
1039// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1040// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1041// extension to the cache path (5 bytes).
1042// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1043static bool validate_dex_path_size(const std::string& dex_path) {
1044 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1045 LOG(ERROR) << "dex_path too long: " << dex_path;
1046 return false;
1047 }
1048 return true;
1049}
1050
Jeff Sharkey90aff262016-12-12 14:28:24 -07001051static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001052 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001053 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001054 return false;
1055 }
1056
1057 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001058 // Oat dirs for secondary dex files are already validated.
1059 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001060 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1061 return false;
1062 }
1063 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1064 return false;
1065 }
1066 } else {
1067 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1068 return false;
1069 }
1070 }
1071 return true;
1072}
1073
1074// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1075// on destruction. It will also run the given cleanup (unless told not to) after closing.
1076//
1077// Usage example:
1078//
Calin Juravle7a570e82017-01-14 16:23:30 -08001079// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001080// [name]() {
1081// unlink(name.c_str());
1082// });
1083// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1084// wrapper if captured as a reference.
1085//
1086// if (file.get() == -1) {
1087// // Error opening...
1088// }
1089//
1090// ...
1091// if (error) {
1092// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1093// // and delete the file (after the fd is closed).
1094// return -1;
1095// }
1096//
1097// (Success case)
1098// file.SetCleanup(false);
1099// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1100// // (leaving the file around; after the fd is closed).
1101//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001102class Dex2oatFileWrapper {
1103 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001104 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001105 }
1106
Calin Juravle7a570e82017-01-14 16:23:30 -08001107 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1108 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1109
1110 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1111 value_ = other.value_;
1112 cleanup_ = other.cleanup_;
1113 do_cleanup_ = other.do_cleanup_;
1114 auto_close_ = other.auto_close_;
1115 other.release();
1116 }
1117
1118 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1119 value_ = other.value_;
1120 cleanup_ = other.cleanup_;
1121 do_cleanup_ = other.do_cleanup_;
1122 auto_close_ = other.auto_close_;
1123 other.release();
1124 return *this;
1125 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001126
1127 ~Dex2oatFileWrapper() {
1128 reset(-1);
1129 }
1130
1131 int get() {
1132 return value_;
1133 }
1134
1135 void SetCleanup(bool cleanup) {
1136 do_cleanup_ = cleanup;
1137 }
1138
1139 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001140 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001141 close(value_);
1142 }
1143 if (do_cleanup_ && cleanup_ != nullptr) {
1144 cleanup_();
1145 }
1146
1147 value_ = new_value;
1148 }
1149
Calin Juravle7a570e82017-01-14 16:23:30 -08001150 void reset(int new_value, std::function<void ()> new_cleanup) {
1151 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001152 close(value_);
1153 }
1154 if (do_cleanup_ && cleanup_ != nullptr) {
1155 cleanup_();
1156 }
1157
1158 value_ = new_value;
1159 cleanup_ = new_cleanup;
1160 }
1161
Calin Juravle7a570e82017-01-14 16:23:30 -08001162 void DisableAutoClose() {
1163 auto_close_ = false;
1164 }
1165
Jeff Sharkey90aff262016-12-12 14:28:24 -07001166 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 void release() {
1168 value_ = -1;
1169 do_cleanup_ = false;
1170 cleanup_ = nullptr;
1171 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001172 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001173 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001174 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001175 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001176};
1177
Calin Juravle7a570e82017-01-14 16:23:30 -08001178// (re)Creates the app image if needed.
1179Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001180 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001181
1182 // We don't create an image for secondary dex files.
1183 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 return Dex2oatFileWrapper();
1185 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001186
Calin Juravle7a570e82017-01-14 16:23:30 -08001187 const std::string image_path = create_image_filename(out_oat_path);
1188 if (image_path.empty()) {
1189 // Happens when the out_oat_path has an unknown extension.
1190 return Dex2oatFileWrapper();
1191 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001192
1193 // Use app images only if it is enabled (by a set image format) and we are compiling
1194 // profile-guided (so the app image doesn't conservatively contain all classes).
1195 if (!profile_guided) {
1196 // In case there is a stale image, remove it now. Ignore any error.
1197 unlink(image_path.c_str());
1198 return Dex2oatFileWrapper();
1199 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001200 char app_image_format[kPropertyValueMax];
1201 bool have_app_image_format =
1202 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1203 if (!have_app_image_format) {
1204 return Dex2oatFileWrapper();
1205 }
1206 // Recreate is true since we do not want to modify a mapped image. If the app is
1207 // already running and we modify the image file, it can cause crashes (b/27493510).
1208 Dex2oatFileWrapper wrapper_fd(
1209 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1210 [image_path]() { unlink(image_path.c_str()); });
1211 if (wrapper_fd.get() < 0) {
1212 // Could not create application image file. Go on since we can compile without it.
1213 LOG(ERROR) << "installd could not create '" << image_path
1214 << "' for image file during dexopt";
1215 // If we have a valid image file path but no image fd, explicitly erase the image file.
1216 if (unlink(image_path.c_str()) < 0) {
1217 if (errno != ENOENT) {
1218 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1219 }
1220 }
1221 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001222 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001223 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1224 wrapper_fd.reset(-1);
1225 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001226
Calin Juravle7a570e82017-01-14 16:23:30 -08001227 return wrapper_fd;
1228}
1229
1230// Creates the dexopt swap file if necessary and return its fd.
1231// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001232unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001234 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001235 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001236 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001237 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001238 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001239 if (swap_fd.get() < 0) {
1240 // Could not create swap file. Optimistically go on and hope that we can compile
1241 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001242 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001243 } else {
1244 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001245 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001246 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1247 }
1248 }
1249 return swap_fd;
1250}
1251
1252// Opens the reference profiles if needed.
1253// 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 -08001254Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1255 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1256 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001257 // Public apps should not be compiled with profile information ever. Same goes for the special
1258 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001259 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001260 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001261 }
Calin Juravle114f0812017-03-08 19:05:07 -08001262
1263 // Open reference profile in read only mode as dex2oat does not get write permissions.
1264 const std::string location = is_secondary_dex ? dex_path : pkgname;
1265 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1266 const auto& cleanup = [location, is_secondary_dex]() {
1267 clear_reference_profile(location.c_str(), is_secondary_dex);
1268 };
1269 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001270}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001271
Calin Juravle7a570e82017-01-14 16:23:30 -08001272// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1273// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001274bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001275 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001276 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001277 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1278 CHECK(in_vdex_wrapper_fd != nullptr);
1279 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001280 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1281 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001282 char in_odex_path[PKG_PATH_MAX];
1283 int dexopt_action = abs(dexopt_needed);
1284 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001285 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001286
1287 // Infer the name of the output VDEX.
1288 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1289 if (out_vdex_path_str.empty()) {
1290 return false;
1291 }
1292
1293 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001294 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001295 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1296 const char* path = nullptr;
1297 if (is_odex_location) {
1298 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1299 path = in_odex_path;
1300 } else {
1301 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001302 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001303 }
1304 } else {
1305 path = out_oat_path;
1306 }
1307 in_vdex_path_str = create_vdex_filename(path);
1308 if (in_vdex_path_str.empty()) {
1309 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001310 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001311 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001312 // We can update in place when all these conditions are met:
1313 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1314 // on /system typically cannot be updated in place).
1315 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1316 // cannot be currently used by a running process.
1317 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1318 // different vdex files to operate.
1319 update_vdex_in_place =
1320 (in_vdex_path_str == out_vdex_path_str) &&
1321 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1322 !profile_guided;
1323 if (update_vdex_in_place) {
1324 // Open the file read-write to be able to update it.
1325 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1326 if (in_vdex_wrapper_fd->get() == -1) {
1327 // If we failed to open the file, we cannot update it in place.
1328 update_vdex_in_place = false;
1329 }
1330 } else {
1331 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1332 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001333 }
1334
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001335 // If we are updating the vdex in place, we do not need to recreate a vdex,
1336 // and can use the same existing one.
1337 if (update_vdex_in_place) {
1338 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1339 // have bogus stale vdex files.
1340 out_vdex_wrapper_fd->reset(
1341 in_vdex_wrapper_fd->get(),
1342 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1343 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1344 // wrapper).
1345 in_vdex_wrapper_fd->DisableAutoClose();
1346 } else {
1347 out_vdex_wrapper_fd->reset(
1348 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1349 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1350 if (out_vdex_wrapper_fd->get() < 0) {
1351 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1352 return false;
1353 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001354 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001355 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001356 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001357 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1358 return false;
1359 }
1360
1361 // If we got here we successfully opened the vdex files.
1362 return true;
1363}
1364
1365// Opens the output oat file for the given apk.
1366// If successful it stores the output path into out_oat_path and returns true.
1367Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001368 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1369 char* out_oat_path) {
1370 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001371 return Dex2oatFileWrapper();
1372 }
1373 const std::string out_oat_path_str(out_oat_path);
1374 Dex2oatFileWrapper wrapper_fd(
1375 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1376 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1377 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001378 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001379 } else if (!set_permissions_and_ownership(
1380 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001381 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1382 wrapper_fd.reset(-1);
1383 }
1384 return wrapper_fd;
1385}
1386
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001387// Creates RDONLY fds for oat and vdex files, if exist.
1388// Returns false if it fails to create oat out path for the given apk path.
1389// Note that the method returns true even if the files could not be opened.
1390bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1391 const std::string& oat_dir,
1392 const std::string& instruction_set,
1393 bool is_secondary_dex,
1394 unique_fd* oat_file_fd,
1395 unique_fd* vdex_file_fd) {
1396 char oat_path[PKG_PATH_MAX];
1397 if (!create_oat_out_path(apk_path.c_str(),
1398 instruction_set.c_str(),
1399 oat_dir.c_str(),
1400 is_secondary_dex,
1401 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001402 LOG(ERROR) << "Could not create oat out path for "
1403 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001404 return false;
1405 }
1406 oat_file_fd->reset(open(oat_path, O_RDONLY));
1407 if (oat_file_fd->get() < 0) {
1408 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1409 }
1410
1411 std::string vdex_filename = create_vdex_filename(oat_path);
1412 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1413 if (vdex_file_fd->get() < 0) {
1414 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1415 }
1416
1417 return true;
1418}
1419
Calin Juravle7a570e82017-01-14 16:23:30 -08001420// Updates the access times of out_oat_path based on those from apk_path.
1421void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1422 struct stat input_stat;
1423 memset(&input_stat, 0, sizeof(input_stat));
1424 if (stat(apk_path, &input_stat) != 0) {
1425 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1426 return;
1427 }
1428
1429 struct utimbuf ut;
1430 ut.actime = input_stat.st_atime;
1431 ut.modtime = input_stat.st_mtime;
1432 if (utime(out_oat_path, &ut) != 0) {
1433 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1434 }
1435}
1436
Calin Juravle80a21252017-01-17 14:43:25 -08001437// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001438// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1439// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1440// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001441static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1442 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1443 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001444 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001445 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001446 const char* dexoptanalyzer_bin =
1447 is_debug_runtime()
1448 ? "/system/bin/dexoptanalyzerd"
1449 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001450 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1451
Calin Juravled23dee72017-07-06 16:29:11 -07001452 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1453 LOG(ERROR) << "Instruction set " << instruction_set
1454 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001455 return;
1456 }
1457
Calin Juravled23dee72017-07-06 16:29:11 -07001458 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001459 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1460 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1461 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001462 std::string isa_arg = "--isa=" + instruction_set;
1463 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001464 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001465 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001466 std::string class_loader_context_arg = "--class-loader-context=";
1467 if (class_loader_context != nullptr) {
1468 class_loader_context_arg += class_loader_context;
1469 }
Calin Juravle80a21252017-01-17 14:43:25 -08001470
Calin Juravle80a21252017-01-17 14:43:25 -08001471 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001472 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001473 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001474 (vdex_fd >= 0 ? 1 : 0) +
1475 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001476 (downgrade ? 1 : 0) +
1477 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001478 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001479 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001480 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001481 argv[i++] = dex_file_arg.c_str();
1482 argv[i++] = isa_arg.c_str();
1483 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001484 if (oat_fd >= 0) {
1485 argv[i++] = oat_fd_arg.c_str();
1486 }
1487 if (vdex_fd >= 0) {
1488 argv[i++] = vdex_fd_arg.c_str();
1489 }
1490 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001491 if (profile_was_updated) {
1492 argv[i++] = assume_profile_changed;
1493 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001494 if (downgrade) {
1495 argv[i++] = downgrade_flag;
1496 }
Calin Juravle58cab072017-09-12 01:02:26 -07001497 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001498 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001499 }
Calin Juravle80a21252017-01-17 14:43:25 -08001500 argv[i] = NULL;
1501
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001502 execv(dexoptanalyzer_bin, (char * const *)argv);
1503 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001504}
1505
1506// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001507static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001508 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001509 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001510 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001511 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001512 return false;
1513 }
Calin Juravle114f0812017-03-08 19:05:07 -08001514 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001515
Calin Juravle80a21252017-01-17 14:43:25 -08001516 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001517 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1518 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001519 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001520 return false;
1521 }
1522
1523 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001524 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001525
Calin Juravle7d765462017-09-04 15:57:10 -07001526 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001527 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001528 return false;
1529 }
1530
1531 return true;
1532}
1533
Calin Juravle7d765462017-09-04 15:57:10 -07001534// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1535// secondary dex files. This return codes are returned by the child process created for
1536// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001537
Calin Juravle7d765462017-09-04 15:57:10 -07001538// The dexoptanalyzer was not invoked because of validation or IO errors.
1539static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1540// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1541static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1542
1543// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001544// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1545// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001546// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1547// of dexoptanalyzer.
1548static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001549 int* dexopt_needed_out) {
1550 // The result values are defined in dexoptanalyzer.
1551 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001552 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001553 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001554 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001555 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001556 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001557 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001558 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001559 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001560 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001561 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001562 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1563 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1564 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001565 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1566 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001567 << " : dexoptanalyzer result=" << result;
1568 return false;
Calin Juravle7d765462017-09-04 15:57:10 -07001569 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1570 // If the file does not exist there's no need for dexopt.
1571 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1572 return true;
1573 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1574 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001575 default:
Calin Juravle7d765462017-09-04 15:57:10 -07001576 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1577 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001578 return false;
1579 }
1580}
1581
Calin Juravle7d765462017-09-04 15:57:10 -07001582enum SecondaryDexAccess {
1583 kSecondaryDexAccessReadOk = 0,
1584 kSecondaryDexAccessDoesNotExist = 1,
1585 kSecondaryDexAccessPermissionError = 2,
1586 kSecondaryDexAccessIOError = 3
1587};
1588
1589static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1590 // Check if the path exists and can be read. If not, there's nothing to do.
1591 if (access(dex_path.c_str(), R_OK) == 0) {
1592 return kSecondaryDexAccessReadOk;
1593 } else {
1594 if (errno == ENOENT) {
1595 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1596 return kSecondaryDexAccessDoesNotExist;
1597 } else {
1598 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1599 return errno == EACCES
1600 ? kSecondaryDexAccessPermissionError
1601 : kSecondaryDexAccessIOError;
1602 }
1603 }
1604}
1605
1606static bool is_file_public(const std::string& filename) {
1607 struct stat file_stat;
1608 if (stat(filename.c_str(), &file_stat) == 0) {
1609 return (file_stat.st_mode & S_IROTH) != 0;
1610 }
1611 return false;
1612}
1613
1614// Create the oat file structure for the secondary dex 'dex_path' and assign
1615// the individual path component to the 'out_' parameters.
1616static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1617 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1618 size_t dirIndex = dex_path.rfind('/');
1619 if (dirIndex == std::string::npos) {
1620 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1621 return false;
1622 }
1623 // TODO(calin): we have similar computations in at lest 3 other places
1624 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1625 // using string append.
1626 std::string apk_dir = dex_path.substr(0, dirIndex);
1627 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1628 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1629
1630 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1631 /*is_secondary_dex*/true, out_oat_path)) {
1632 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1633 return false;
1634 }
1635 return true;
1636}
1637
1638// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1639// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1640static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1641 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1642 *out_storage_flag = FLAG_STORAGE_CE;
1643 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1644 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1645 return false;
1646 }
1647 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1648 *out_storage_flag = FLAG_STORAGE_DE;
1649 } else {
1650 LOG(ERROR) << "Secondary dex storage flag must be set";
1651 return false;
1652 }
1653 return true;
1654}
1655
Calin Juravlec9eab382017-01-25 01:17:17 -08001656// 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 -08001657// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1658// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001659// When returning true, the output parameters will be:
1660// - is_public_out: whether or not the oat file should not be made public
1661// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1662// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001663static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001664 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001665 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle7d765462017-09-04 15:57:10 -07001666 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1667 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001668 int storage_flag;
Calin Juravle7d765462017-09-04 15:57:10 -07001669 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001670 return false;
1671 }
Calin Juravle7d765462017-09-04 15:57:10 -07001672 // Compute the oat dir as it's not easy to extract it from the child computation.
1673 char oat_path[PKG_PATH_MAX];
1674 char oat_dir[PKG_PATH_MAX];
1675 char oat_isa_dir[PKG_PATH_MAX];
1676 if (!create_secondary_dex_oat_layout(
1677 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1678 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001679 return false;
1680 }
Calin Juravle7d765462017-09-04 15:57:10 -07001681 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001682
Calin Juravle80a21252017-01-17 14:43:25 -08001683 pid_t pid = fork();
1684 if (pid == 0) {
1685 // child -- drop privileges before continuing.
1686 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001687
1688 // Validate the path structure.
1689 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1690 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1691 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1692 }
1693
1694 // Open the dex file.
1695 unique_fd zip_fd;
1696 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1697 if (zip_fd.get() < 0) {
1698 if (errno == ENOENT) {
1699 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1700 } else {
1701 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1702 }
1703 }
1704
1705 // Prepare the oat directories.
1706 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1707 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1708 }
1709
1710 // Open the vdex/oat files if any.
1711 unique_fd oat_file_fd;
1712 unique_fd vdex_file_fd;
1713 if (!maybe_open_oat_and_vdex_file(dex_path,
1714 *oat_dir_out,
1715 instruction_set,
1716 true /* is_secondary_dex */,
1717 &oat_file_fd,
1718 &vdex_file_fd)) {
1719 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1720 }
1721
1722 // Analyze profiles.
1723 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1724
1725 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001726 exec_dexoptanalyzer(dex_path,
1727 vdex_file_fd.get(),
1728 oat_file_fd.get(),
1729 zip_fd.get(),
1730 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001731 compiler_filter, profile_was_updated,
1732 downgrade,
1733 class_loader_context);
1734 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1735 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001736 }
1737
1738 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001739 int result = wait_child(pid);
1740 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001741 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001742 return false;
1743 }
1744 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001745 // Check that we successfully executed dexoptanalyzer.
1746 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1747
1748 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1749
Calin Juravle80a21252017-01-17 14:43:25 -08001750 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001751 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1752 // makes the code simpler; force compilation is only needed during tests).
1753 if (success &&
1754 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1755 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001756 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1757 }
1758
Calin Juravle7d765462017-09-04 15:57:10 -07001759 // Check if we should make the oat file public.
1760 // Note that if the dex file is not public the compiled code cannot be made public.
1761 // It is ok to check this flag outside in the parent process.
1762 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1763
Calin Juravle80a21252017-01-17 14:43:25 -08001764 return success;
1765}
1766
Calin Juravlec9eab382017-01-25 01:17:17 -08001767int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001768 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001769 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001770 bool downgrade) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001771 CHECK(pkgname != nullptr);
1772 CHECK(pkgname[0] != 0);
1773 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1774 LOG_FATAL("dexopt flags contains unknown fields\n");
1775 }
1776
Calin Juravled23dee72017-07-06 16:29:11 -07001777 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001778 return -1;
1779 }
1780
1781 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1782 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1783 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001784 }
1785
Calin Juravleebc8a792017-04-04 20:21:05 -07001786 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001787 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1788 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1789 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001790 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001791 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001792
1793 // Check if we're dealing with a secondary dex file and if we need to compile it.
1794 std::string oat_dir_str;
1795 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001796 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001797 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle7d765462017-09-04 15:57:10 -07001798 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001799 oat_dir = oat_dir_str.c_str();
1800 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1801 return 0; // Nothing to do, report success.
1802 }
1803 } else {
1804 return -1; // We had an error, logged in the process method.
1805 }
1806 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001807 // Currently these flags are only use for secondary dex files.
1808 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001809 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1810 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1811 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001812
1813 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001814 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001815 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001816 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001817 return -1;
1818 }
1819
1820 // Create the output OAT file.
1821 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001822 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001823 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001824 if (out_oat_fd.get() < 0) {
1825 return -1;
1826 }
1827
1828 // Open vdex files.
1829 Dex2oatFileWrapper in_vdex_fd;
1830 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001831 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1832 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001833 return -1;
1834 }
1835
Calin Juravlecb556e32017-04-04 20:22:50 -07001836 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1837 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1838 // fully inherit their parent context).
1839 // Note that for primary apk the oat files are created before, in a separate installd
1840 // call which also does the restorecon. TODO(calin): unify the paths.
1841 if (is_secondary_dex) {
1842 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1843 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1844 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1845 return -1;
1846 }
1847 }
1848
Jeff Sharkey90aff262016-12-12 14:28:24 -07001849 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001850 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001851
Calin Juravle7a570e82017-01-14 16:23:30 -08001852 // Create the app image file if needed.
1853 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001854 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001855
Calin Juravle7a570e82017-01-14 16:23:30 -08001856 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001857 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1858 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001859
Calin Juravlec9eab382017-01-25 01:17:17 -08001860 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001861
1862 pid_t pid = fork();
1863 if (pid == 0) {
1864 /* child -- drop privileges before continuing */
1865 drop_capabilities(uid);
1866
Richard Uhler76cc0272016-12-08 10:46:35 +00001867 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001868 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1869 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1870 _exit(67);
1871 }
1872
Richard Uhler76cc0272016-12-08 10:46:35 +00001873 run_dex2oat(input_fd.get(),
1874 out_oat_fd.get(),
1875 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001876 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001877 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001878 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001879 out_oat_path,
1880 swap_fd.get(),
1881 instruction_set,
1882 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001883 debuggable,
1884 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001885 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00001886 reference_profile_fd.get(),
Calin Juravle52c45822017-07-13 22:50:21 -07001887 class_loader_context);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001888 _exit(68); /* only get here on exec failure */
1889 } else {
1890 int res = wait_child(pid);
1891 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001892 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001893 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001894 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001895 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001896 }
1897 }
1898
Calin Juravlec9eab382017-01-25 01:17:17 -08001899 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001900
1901 // We've been successful, don't delete output.
1902 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001903 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001904 image_fd.SetCleanup(false);
1905 reference_profile_fd.SetCleanup(false);
1906
1907 return 0;
1908}
1909
Calin Juravlec9eab382017-01-25 01:17:17 -08001910// Try to remove the given directory. Log an error if the directory exists
1911// and is empty but could not be removed.
1912static bool rmdir_if_empty(const char* dir) {
1913 if (rmdir(dir) == 0) {
1914 return true;
1915 }
1916 if (errno == ENOENT || errno == ENOTEMPTY) {
1917 return true;
1918 }
1919 PLOG(ERROR) << "Failed to remove dir: " << dir;
1920 return false;
1921}
1922
1923// Try to unlink the given file. Log an error if the file exists and could not
1924// be unlinked.
1925static bool unlink_if_exists(const std::string& file) {
1926 if (unlink(file.c_str()) == 0) {
1927 return true;
1928 }
1929 if (errno == ENOENT) {
1930 return true;
1931
1932 }
1933 PLOG(ERROR) << "Could not unlink: " << file;
1934 return false;
1935}
1936
Calin Juravle7d765462017-09-04 15:57:10 -07001937enum ReconcileSecondaryDexResult {
1938 kReconcileSecondaryDexExists = 0,
1939 kReconcileSecondaryDexCleanedUp = 1,
1940 kReconcileSecondaryDexValidationError = 2,
1941 kReconcileSecondaryDexCleanUpError = 3,
1942 kReconcileSecondaryDexAccessIOError = 4,
1943};
Calin Juravlec9eab382017-01-25 01:17:17 -08001944
1945// Reconcile the secondary dex 'dex_path' and its generated oat files.
1946// Return true if all the parameters are valid and the secondary dex file was
1947// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1948// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1949// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1950// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1951// Return false if there were errors during processing. In this case
1952// out_secondary_dex_exists will be set to false.
1953bool reconcile_secondary_dex_file(const std::string& dex_path,
1954 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1955 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1956 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001957 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001958 if (isas.size() == 0) {
1959 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1960 return false;
1961 }
1962
Calin Juravle7d765462017-09-04 15:57:10 -07001963 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1964 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1965 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001966 return false;
1967 }
1968
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001969 // As a security measure we want to unlink art artifacts with the reduced capabilities
1970 // of the package user id. So we fork and drop capabilities in the child.
1971 pid_t pid = fork();
1972 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001973 /* child -- drop privileges before continuing */
1974 drop_capabilities(uid);
1975
1976 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1977 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1978 uid, storage_flag)) {
1979 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1980 _exit(kReconcileSecondaryDexValidationError);
1981 }
1982
1983 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1984 switch (access_check) {
1985 case kSecondaryDexAccessDoesNotExist:
1986 // File does not exist. Proceed with cleaning.
1987 break;
1988 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1989 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1990 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1991 default:
1992 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
1993 _exit(kReconcileSecondaryDexValidationError);
1994 }
1995
1996 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001997 char oat_path[PKG_PATH_MAX];
1998 char oat_dir[PKG_PATH_MAX];
1999 char oat_isa_dir[PKG_PATH_MAX];
2000 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002001 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle7d765462017-09-04 15:57:10 -07002002 if (!create_secondary_dex_oat_layout(
2003 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
2004 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
2005 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002006 }
Calin Juravle51314092017-05-18 15:33:05 -07002007
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002008 // Delete oat/vdex/art files.
2009 result = unlink_if_exists(oat_path) && result;
2010 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2011 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002012
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002013 // Delete profiles.
2014 std::string current_profile = create_current_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002015 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002016 std::string reference_profile = create_reference_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002017 dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002018 result = unlink_if_exists(current_profile) && result;
2019 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002020
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002021 // We upgraded once the location of current profile for secondary dex files.
2022 // Check for any previous left-overs and remove them as well.
2023 std::string old_current_profile = dex_path + ".prof";
2024 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002025
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002026 // Try removing the directories as well, they might be empty.
2027 result = rmdir_if_empty(oat_isa_dir) && result;
2028 result = rmdir_if_empty(oat_dir) && result;
2029 }
Calin Juravle7d765462017-09-04 15:57:10 -07002030 if (!result) {
2031 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2032 }
2033 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002034 }
2035
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002036 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002037 if (!WIFEXITED(return_code)) {
2038 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2039 } else {
2040 return_code = WEXITSTATUS(return_code);
2041 }
2042
2043 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2044
2045 switch (return_code) {
2046 case kReconcileSecondaryDexCleanedUp:
2047 case kReconcileSecondaryDexValidationError:
2048 // If we couldn't validate assume the dex file does not exist.
2049 // This will purge the entry from the PM records.
2050 *out_secondary_dex_exists = false;
2051 return true;
2052 case kReconcileSecondaryDexExists:
2053 *out_secondary_dex_exists = true;
2054 return true;
2055 case kReconcileSecondaryDexAccessIOError:
2056 // We had an access IO error.
2057 // Return false so that we can try again.
2058 // The value of out_secondary_dex_exists does not matter in this case and by convention
2059 // is set to false.
2060 *out_secondary_dex_exists = false;
2061 return false;
2062 default:
2063 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2064 *out_secondary_dex_exists = false;
2065 return false;
2066 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002067}
2068
Jeff Sharkey90aff262016-12-12 14:28:24 -07002069// Helper for move_ab, so that we can have common failure-case cleanup.
2070static bool unlink_and_rename(const char* from, const char* to) {
2071 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2072 // return a failure.
2073 struct stat s;
2074 if (stat(to, &s) == 0) {
2075 if (!S_ISREG(s.st_mode)) {
2076 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2077 return false;
2078 }
2079 if (unlink(to) != 0) {
2080 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2081 return false;
2082 }
2083 } else {
2084 // This may be a permission problem. We could investigate the error code, but we'll just
2085 // let the rename failure do the work for us.
2086 }
2087
2088 // Try to rename "to" to "from."
2089 if (rename(from, to) != 0) {
2090 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2091 return false;
2092 }
2093 return true;
2094}
2095
2096// Move/rename a B artifact (from) to an A artifact (to).
2097static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2098 // Check whether B exists.
2099 {
2100 struct stat s;
2101 if (stat(b_path.c_str(), &s) != 0) {
2102 // Silently ignore for now. The service calling this isn't smart enough to understand
2103 // lack of artifacts at the moment.
2104 return false;
2105 }
2106 if (!S_ISREG(s.st_mode)) {
2107 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2108 // Try to unlink, but swallow errors.
2109 unlink(b_path.c_str());
2110 return false;
2111 }
2112 }
2113
2114 // Rename B to A.
2115 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2116 // Delete the b_path so we don't try again (or fail earlier).
2117 if (unlink(b_path.c_str()) != 0) {
2118 PLOG(ERROR) << "Could not unlink " << b_path;
2119 }
2120
2121 return false;
2122 }
2123
2124 return true;
2125}
2126
2127bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2128 // Get the current slot suffix. No suffix, no A/B.
2129 std::string slot_suffix;
2130 {
2131 char buf[kPropertyValueMax];
2132 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2133 return false;
2134 }
2135 slot_suffix = buf;
2136
2137 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2138 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2139 return false;
2140 }
2141 }
2142
2143 // Validate other inputs.
2144 if (validate_apk_path(apk_path) != 0) {
2145 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2146 return false;
2147 }
2148 if (validate_apk_path(oat_dir) != 0) {
2149 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2150 return false;
2151 }
2152
2153 char a_path[PKG_PATH_MAX];
2154 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2155 return false;
2156 }
2157 const std::string a_vdex_path = create_vdex_filename(a_path);
2158 const std::string a_image_path = create_image_filename(a_path);
2159
2160 // B path = A path + slot suffix.
2161 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2162 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2163 const std::string b_image_path = StringPrintf("%s.%s",
2164 a_image_path.c_str(),
2165 slot_suffix.c_str());
2166
2167 bool success = true;
2168 if (move_ab_path(b_path, a_path)) {
2169 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2170 // Note: we can live without an app image. As such, ignore failure to move the image file.
2171 // If we decide to require the app image, or the app image being moved correctly,
2172 // then change accordingly.
2173 constexpr bool kIgnoreAppImageFailure = true;
2174
2175 if (!a_image_path.empty()) {
2176 if (!move_ab_path(b_image_path, a_image_path)) {
2177 unlink(a_image_path.c_str());
2178 if (!kIgnoreAppImageFailure) {
2179 success = false;
2180 }
2181 }
2182 }
2183 } else {
2184 // Cleanup: delete B image, ignore errors.
2185 unlink(b_image_path.c_str());
2186 success = false;
2187 }
2188 } else {
2189 // Cleanup: delete B image, ignore errors.
2190 unlink(b_vdex_path.c_str());
2191 unlink(b_image_path.c_str());
2192 success = false;
2193 }
2194 return success;
2195}
2196
2197bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2198 // Delete the oat/odex file.
2199 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002200 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002201 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002202 return false;
2203 }
2204
2205 // In case of a permission failure report the issue. Otherwise just print a warning.
2206 auto unlink_and_check = [](const char* path) -> bool {
2207 int result = unlink(path);
2208 if (result != 0) {
2209 if (errno == EACCES || errno == EPERM) {
2210 PLOG(ERROR) << "Could not unlink " << path;
2211 return false;
2212 }
2213 PLOG(WARNING) << "Could not unlink " << path;
2214 }
2215 return true;
2216 };
2217
2218 // Delete the oat/odex file.
2219 bool return_value_oat = unlink_and_check(out_path);
2220
2221 // Derive and delete the app image.
2222 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2223
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002224 // Derive and delete the vdex file.
2225 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2226
Jeff Sharkey90aff262016-12-12 14:28:24 -07002227 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002228 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002229}
2230
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002231static bool is_absolute_path(const std::string& path) {
2232 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2233 LOG(ERROR) << "Invalid absolute path " << path;
2234 return false;
2235 } else {
2236 return true;
2237 }
2238}
2239
2240static bool is_valid_instruction_set(const std::string& instruction_set) {
2241 // TODO: add explicit whitelisting of instruction sets
2242 if (instruction_set.find('/') != std::string::npos) {
2243 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2244 return false;
2245 } else {
2246 return true;
2247 }
2248}
2249
2250bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2251 const char *apk_path, const char *instruction_set) {
2252 std::string oat_dir_ = oat_dir;
2253 std::string apk_path_ = apk_path;
2254 std::string instruction_set_ = instruction_set;
2255
2256 if (!is_absolute_path(oat_dir_)) return false;
2257 if (!is_absolute_path(apk_path_)) return false;
2258 if (!is_valid_instruction_set(instruction_set_)) return false;
2259
2260 std::string::size_type end = apk_path_.rfind('.');
2261 std::string::size_type start = apk_path_.rfind('/', end);
2262 if (end == std::string::npos || start == std::string::npos) {
2263 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2264 return false;
2265 }
2266
2267 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2268 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2269 const char* res = res_.c_str();
2270 if (strlen(res) >= PKG_PATH_MAX) {
2271 LOG(ERROR) << "Result too large";
2272 return false;
2273 } else {
2274 strlcpy(path, res, PKG_PATH_MAX);
2275 return true;
2276 }
2277}
2278
2279bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2280 const char *instruction_set) {
2281 std::string apk_path_ = apk_path;
2282 std::string instruction_set_ = instruction_set;
2283
2284 if (!is_absolute_path(apk_path_)) return false;
2285 if (!is_valid_instruction_set(instruction_set_)) return false;
2286
2287 std::string::size_type end = apk_path_.rfind('.');
2288 std::string::size_type start = apk_path_.rfind('/', end);
2289 if (end == std::string::npos || start == std::string::npos) {
2290 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2291 return false;
2292 }
2293
2294 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2295 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2296}
2297
2298bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2299 const char *instruction_set) {
2300 std::string src_ = src;
2301 std::string instruction_set_ = instruction_set;
2302
2303 if (!is_absolute_path(src_)) return false;
2304 if (!is_valid_instruction_set(instruction_set_)) return false;
2305
2306 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2307 if (*it == '/') {
2308 *it = '@';
2309 }
2310 }
2311
2312 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2313 + DALVIK_CACHE_POSTFIX;
2314 const char* res = res_.c_str();
2315 if (strlen(res) >= PKG_PATH_MAX) {
2316 LOG(ERROR) << "Result too large";
2317 return false;
2318 } else {
2319 strlcpy(path, res, PKG_PATH_MAX);
2320 return true;
2321 }
2322}
2323
Calin Juravlec3596c32017-12-05 12:29:15 -08002324bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
Calin Juravle29591732017-11-20 17:46:19 -08002325 const std::string& code_path) {
2326 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2327
2328 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, code_path);
2329 if (snapshot_fd < 0) {
2330 return false;
2331 }
2332
2333 std::vector<unique_fd> profiles_fd;
2334 unique_fd reference_profile_fd;
2335 open_profile_files(app_shared_gid, package_name, /*is_secondary_dex*/ false, &profiles_fd,
2336 &reference_profile_fd);
2337 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2338 return false;
2339 }
2340
2341 profiles_fd.push_back(std::move(reference_profile_fd));
2342
2343 pid_t pid = fork();
2344 if (pid == 0) {
2345 /* child -- drop privileges before continuing */
2346 drop_capabilities(app_shared_gid);
2347 run_profman_merge(profiles_fd, snapshot_fd);
2348 exit(42); /* only get here on exec failure */
2349 }
2350
2351 /* parent */
2352 int return_code = wait_child(pid);
2353 if (!WIFEXITED(return_code)) {
2354 LOG(WARNING) << "profman failed for " << package_name << ":" << code_path;
2355 return false;
2356 }
2357
2358 return true;
2359}
2360
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002361} // namespace installd
2362} // namespace android