blob: 8917684f77839cabd69b17c86746230dc58e1314 [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";
64
Calin Juravle114f0812017-03-08 19:05:07 -080065// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
66struct FreeDelete {
67 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
68 void operator()(const void* ptr) const {
69 free(const_cast<void*>(ptr));
70 }
71};
72
73// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
74template <typename T>
75using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
76
Calin Juravle1a0af3b2017-03-09 14:33:33 -080077static unique_fd invalid_unique_fd() {
78 return unique_fd(-1);
79}
80
Andreas Gampe6a9cf722017-07-24 16:49:10 -070081static bool is_debug_runtime() {
82 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
83}
84
David Sehra3b5ab62017-10-25 14:27:29 -070085static bool is_debuggable_build() {
86 return android::base::GetBoolProperty("ro.debuggable", false);
87}
88
Jeff Sharkey90aff262016-12-12 14:28:24 -070089static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080090 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070091 if (ufd.get() < 0) {
92 if (errno != ENOENT) {
93 PLOG(WARNING) << "Could not open profile " << profile;
94 return false;
95 } else {
96 // Nothing to clear. That's ok.
97 return true;
98 }
99 }
100
101 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
102 if (errno != EWOULDBLOCK) {
103 PLOG(WARNING) << "Error locking profile " << profile;
104 }
105 // This implies that the app owning this profile is running
106 // (and has acquired the lock).
107 //
108 // If we can't acquire the lock bail out since clearing is useless anyway
109 // (the app will write again to the profile).
110 //
111 // Note:
112 // This does not impact the this is not an issue for the profiling correctness.
113 // In case this is needed because of an app upgrade, profiles will still be
114 // eventually cleared by the app itself due to checksum mismatch.
115 // If this is needed because profman advised, then keeping the data around
116 // until the next run is again not an issue.
117 //
118 // If the app attempts to acquire a lock while we've held one here,
119 // it will simply skip the current write cycle.
120 return false;
121 }
122
123 bool truncated = ftruncate(ufd.get(), 0) == 0;
124 if (!truncated) {
125 PLOG(WARNING) << "Could not truncate " << profile;
126 }
127 if (flock(ufd.get(), LOCK_UN) != 0) {
128 PLOG(WARNING) << "Error unlocking profile " << profile;
129 }
130 return truncated;
131}
132
Calin Juravle114f0812017-03-08 19:05:07 -0800133// Clear the reference profile for the given location.
134// The location is the package name for primary apks or the dex path for secondary dex files.
135static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
136 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700137}
138
Calin Juravle114f0812017-03-08 19:05:07 -0800139// Clear the reference profile for the given location.
140// The location is the package name for primary apks or the dex path for secondary dex files.
141static bool clear_current_profile(const std::string& pkgname, userid_t user,
142 bool is_secondary_dex) {
143 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700144}
145
Calin Juravle114f0812017-03-08 19:05:07 -0800146// Clear the reference profile for the primary apk of the given package.
147bool clear_primary_reference_profile(const std::string& pkgname) {
148 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
149}
150
151// Clear all current profile for the primary apk of the given package.
152bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700153 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800154 // 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 -0700155 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
156 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800157 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700158 }
159 return success;
160}
161
Calin Juravle114f0812017-03-08 19:05:07 -0800162// Clear the current profile for the primary apk of the given package and user.
163bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
164 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
165}
166
Jeff Sharkey90aff262016-12-12 14:28:24 -0700167static int split_count(const char *str)
168{
169 char *ctx;
170 int count = 0;
171 char buf[kPropertyValueMax];
172
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600173 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 char *pBuf = buf;
175
176 while(strtok_r(pBuf, " ", &ctx) != NULL) {
177 count++;
178 pBuf = NULL;
179 }
180
181 return count;
182}
183
184static int split(char *buf, const char **argv)
185{
186 char *ctx;
187 int count = 0;
188 char *tok;
189 char *pBuf = buf;
190
191 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
192 argv[count++] = tok;
193 pBuf = NULL;
194 }
195
196 return count;
197}
198
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700199static const char* get_location_from_path(const char* path) {
200 static constexpr char kLocationSeparator = '/';
201 const char *location = strrchr(path, kLocationSeparator);
202 if (location == NULL) {
203 return path;
204 } else {
205 // Skip the separator character.
206 return location + 1;
207 }
208}
209
Jeff Sharkey90aff262016-12-12 14:28:24 -0700210static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
211 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100212 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700213 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
David Sehra3b5ab62017-10-25 14:27:29 -0700214 const char* class_loader_context) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700215 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
216
217 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
218 ALOGE("Instruction set %s longer than max length of %d",
219 instruction_set, MAX_INSTRUCTION_SET_LEN);
220 return;
221 }
222
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700223 // Get the relative path to the input file.
224 const char* relative_input_file_name = get_location_from_path(input_file_name);
225
Jeff Sharkey90aff262016-12-12 14:28:24 -0700226 char dex2oat_Xms_flag[kPropertyValueMax];
227 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
228
229 char dex2oat_Xmx_flag[kPropertyValueMax];
230 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
231
232 char dex2oat_threads_buf[kPropertyValueMax];
233 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
234 ? "dalvik.vm.dex2oat-threads"
235 : "dalvik.vm.boot-dex2oat-threads",
236 dex2oat_threads_buf,
237 NULL) > 0;
238 char dex2oat_threads_arg[kPropertyValueMax + 2];
239 if (have_dex2oat_threads_flag) {
240 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
241 }
242
243 char dex2oat_isa_features_key[kPropertyKeyMax];
244 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
245 char dex2oat_isa_features[kPropertyValueMax];
246 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
247 dex2oat_isa_features, NULL) > 0;
248
249 char dex2oat_isa_variant_key[kPropertyKeyMax];
250 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
251 char dex2oat_isa_variant[kPropertyValueMax];
252 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
253 dex2oat_isa_variant, NULL) > 0;
254
255 const char *dex2oat_norelocation = "-Xnorelocate";
256 bool have_dex2oat_relocation_skip_flag = false;
257
258 char dex2oat_flags[kPropertyValueMax];
259 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
260 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
261 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
262
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100263 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700264 char vold_decrypt[kPropertyValueMax];
265 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
266 bool skip_compilation = (have_vold_decrypt &&
267 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
268 (strcmp(vold_decrypt, "1") == 0)));
269
270 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
271
272 char app_image_format[kPropertyValueMax];
273 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
274 bool have_app_image_format =
275 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
276 if (have_app_image_format) {
277 sprintf(image_format_arg, "--image-format=%s", app_image_format);
278 }
279
280 char dex2oat_large_app_threshold[kPropertyValueMax];
281 bool have_dex2oat_large_app_threshold =
282 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
283 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
284 if (have_dex2oat_large_app_threshold) {
285 sprintf(dex2oat_large_app_threshold_arg,
286 "--very-large-app-threshold=%s",
287 dex2oat_large_app_threshold);
288 }
289
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700290 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700291 const char* dex2oat_bin = "/system/bin/dex2oat";
292 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700293 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700294 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
295 dex2oat_bin = kDex2oatDebugPath;
296 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700297
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700298 bool generate_minidebug_info = kEnableMinidebugInfo &&
299 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
300 kMinidebugInfoSystemPropertyDefault);
301
Jeff Sharkey90aff262016-12-12 14:28:24 -0700302 static const char* RUNTIME_ARG = "--runtime-arg";
303
304 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
305
George Burgess IV36cebe772017-01-25 11:52:01 -0800306 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
307 // use arraysize instead.
308 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
309 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
310 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
311 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
312 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
313 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
314 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
315 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
316 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
317 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
318 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
319 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700320 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800321 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700322 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800323 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700324 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
325 char class_loader_context_arg[class_loader_context_size];
326 if (class_loader_context != nullptr) {
327 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
328 class_loader_context);
329 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700330
331 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700332 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700333 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
334 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
335 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
336 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
337 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
338 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
339 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
340 if (swap_fd >= 0) {
341 have_dex2oat_swap_fd = true;
342 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
343 }
344 if (image_fd >= 0) {
345 have_dex2oat_image_fd = true;
346 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
347 }
348
349 if (have_dex2oat_Xms_flag) {
350 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
351 }
352 if (have_dex2oat_Xmx_flag) {
353 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
354 }
355
356 // Compute compiler filter.
357
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100358 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700359 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600360 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
361 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700362 have_dex2oat_compiler_filter_flag = true;
363 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100364 } else if (compiler_filter != nullptr) {
365 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700366 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100367 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
368 have_dex2oat_compiler_filter_flag = true;
369 } else {
370 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
371 compiler_filter,
372 kPropertyValueMax);
373 }
374 }
375
376 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700377 char dex2oat_compiler_filter_flag[kPropertyValueMax];
378 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
379 dex2oat_compiler_filter_flag, NULL) > 0;
380 if (have_dex2oat_compiler_filter_flag) {
381 sprintf(dex2oat_compiler_filter_arg,
382 "--compiler-filter=%s",
383 dex2oat_compiler_filter_flag);
384 }
385 }
386
387 // Check whether all apps should be compiled debuggable.
388 if (!debuggable) {
389 char prop_buf[kPropertyValueMax];
390 debuggable =
391 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
392 (prop_buf[0] == '1');
393 }
394 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
395 if (profile_fd != -1) {
396 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
397 }
398
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700399 // Get the directory of the apk to pass as a base classpath directory.
400 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
401 std::string apk_dir(input_file_name);
402 unsigned long dir_index = apk_dir.rfind('/');
403 bool has_base_dir = dir_index != std::string::npos;
404 if (has_base_dir) {
405 apk_dir = apk_dir.substr(0, dir_index);
406 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
407 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700408
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700409
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700410 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700411
412 const char* argv[9 // program name, mandatory arguments and the final NULL
413 + (have_dex2oat_isa_variant ? 1 : 0)
414 + (have_dex2oat_isa_features ? 1 : 0)
415 + (have_dex2oat_Xms_flag ? 2 : 0)
416 + (have_dex2oat_Xmx_flag ? 2 : 0)
417 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
418 + (have_dex2oat_threads_flag ? 1 : 0)
419 + (have_dex2oat_swap_fd ? 1 : 0)
420 + (have_dex2oat_image_fd ? 1 : 0)
421 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
422 + (generate_debug_info ? 1 : 0)
423 + (debuggable ? 1 : 0)
424 + (have_app_image_format ? 1 : 0)
425 + dex2oat_flags_count
426 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700427 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700428 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700429 + (have_dex2oat_large_app_threshold ? 1 : 0)
430 + (generate_minidebug_info ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700431 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700432 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700433 argv[i++] = zip_fd_arg;
434 argv[i++] = zip_location_arg;
435 argv[i++] = input_vdex_fd_arg;
436 argv[i++] = output_vdex_fd_arg;
437 argv[i++] = oat_fd_arg;
438 argv[i++] = oat_location_arg;
439 argv[i++] = instruction_set_arg;
440 if (have_dex2oat_isa_variant) {
441 argv[i++] = instruction_set_variant_arg;
442 }
443 if (have_dex2oat_isa_features) {
444 argv[i++] = instruction_set_features_arg;
445 }
446 if (have_dex2oat_Xms_flag) {
447 argv[i++] = RUNTIME_ARG;
448 argv[i++] = dex2oat_Xms_arg;
449 }
450 if (have_dex2oat_Xmx_flag) {
451 argv[i++] = RUNTIME_ARG;
452 argv[i++] = dex2oat_Xmx_arg;
453 }
454 if (have_dex2oat_compiler_filter_flag) {
455 argv[i++] = dex2oat_compiler_filter_arg;
456 }
457 if (have_dex2oat_threads_flag) {
458 argv[i++] = dex2oat_threads_arg;
459 }
460 if (have_dex2oat_swap_fd) {
461 argv[i++] = dex2oat_swap_fd;
462 }
463 if (have_dex2oat_image_fd) {
464 argv[i++] = dex2oat_image_fd;
465 }
466 if (generate_debug_info) {
467 argv[i++] = "--generate-debug-info";
468 }
469 if (debuggable) {
470 argv[i++] = "--debuggable";
471 }
472 if (have_app_image_format) {
473 argv[i++] = image_format_arg;
474 }
475 if (have_dex2oat_large_app_threshold) {
476 argv[i++] = dex2oat_large_app_threshold_arg;
477 }
478 if (dex2oat_flags_count) {
479 i += split(dex2oat_flags, argv + i);
480 }
481 if (have_dex2oat_relocation_skip_flag) {
482 argv[i++] = RUNTIME_ARG;
483 argv[i++] = dex2oat_norelocation;
484 }
485 if (profile_fd != -1) {
486 argv[i++] = profile_arg;
487 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700488 if (has_base_dir) {
489 argv[i++] = base_dir;
490 }
Calin Juravle52c45822017-07-13 22:50:21 -0700491 if (class_loader_context != nullptr) {
492 argv[i++] = class_loader_context_arg;
493 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700494 if (generate_minidebug_info) {
495 argv[i++] = kMinidebugDex2oatFlag;
496 }
Calin Juravle52c45822017-07-13 22:50:21 -0700497
Jeff Sharkey90aff262016-12-12 14:28:24 -0700498 // Do not add after dex2oat_flags, they should override others for debugging.
499 argv[i] = NULL;
500
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700501 execv(dex2oat_bin, (char * const *)argv);
502 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700503}
504
505/*
506 * Whether dexopt should use a swap file when compiling an APK.
507 *
508 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
509 * itself, anyways).
510 *
511 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
512 *
513 * Otherwise, return true if this is a low-mem device.
514 *
515 * Otherwise, return default value.
516 */
517static bool kAlwaysProvideSwapFile = false;
518static bool kDefaultProvideSwapFile = true;
519
520static bool ShouldUseSwapFileForDexopt() {
521 if (kAlwaysProvideSwapFile) {
522 return true;
523 }
524
525 // Check the "override" property. If it exists, return value == "true".
526 char dex2oat_prop_buf[kPropertyValueMax];
527 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
528 if (strcmp(dex2oat_prop_buf, "true") == 0) {
529 return true;
530 } else {
531 return false;
532 }
533 }
534
535 // Shortcut for default value. This is an implementation optimization for the process sketched
536 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
537 // as low-mem is never returning false. The compiler will optimize this away if it can.
538 if (kDefaultProvideSwapFile) {
539 return true;
540 }
541
542 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
543 if (is_low_mem) {
544 return true;
545 }
546
547 // Default value must be false here.
548 return kDefaultProvideSwapFile;
549}
550
Richard Uhler76cc0272016-12-08 10:46:35 +0000551static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552 if (set_to_bg) {
553 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
554 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
555 exit(70);
556 }
557 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
558 ALOGE("setpriority failed: %s\n", strerror(errno));
559 exit(71);
560 }
561 }
562}
563
Calin Juravle29591732017-11-20 17:46:19 -0800564static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
565 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800566 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800567 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800568 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800569 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800570 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700571 }
Calin Juravle114f0812017-03-08 19:05:07 -0800572 // Profiles should belong to the app; make sure of that by giving ownership to
573 // the app uid. If we cannot do that, there's no point in returning the fd
574 // since dex2oat/profman will fail with SElinux denials.
575 if (fchown(fd.get(), uid, uid) < 0) {
576 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800577 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800578 }
Calin Juravle29591732017-11-20 17:46:19 -0800579 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800580}
581
Calin Juravle29591732017-11-20 17:46:19 -0800582static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800583 // Do not follow symlinks when opening a profile:
584 // - primary profiles should not contain symlinks in their paths
585 // - secondary dex paths should have been already resolved and validated
586 flags |= O_NOFOLLOW;
587
Calin Juravle29591732017-11-20 17:46:19 -0800588 // Check if we need to create the profile
589 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
590 unique_fd fd;
591 if ((flags & O_CREAT) != 0) {
592 fd = create_profile(uid, profile, flags);
593 } else {
594 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
595 }
596
Calin Juravle114f0812017-03-08 19:05:07 -0800597 if (fd.get() < 0) {
598 if (errno != ENOENT) {
599 // Profiles might be missing for various reasons. For example, in a
600 // multi-user environment, the profile directory for one user can be created
601 // after we start a merge. In this case the current profile for that user
602 // will not be found.
603 // Also, the secondary dex profiles might be deleted by the app at any time,
604 // so we can't we need to prepare if they are missing.
605 PLOG(ERROR) << "Failed to open profile " << profile;
606 }
607 return invalid_unique_fd();
608 }
609
Jeff Sharkey90aff262016-12-12 14:28:24 -0700610 return fd;
611}
612
Calin Juravle114f0812017-03-08 19:05:07 -0800613static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
614 bool is_secondary_dex) {
615 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800616 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800617}
618
619static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
620 bool is_secondary_dex) {
621 std::string profile = create_reference_profile_path(location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800622 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
623}
624
625static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
626 const std::string& code_path) {
627 std::string profile = create_snapshot_profile_path(package_name, code_path);
628 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800629}
630
631static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800632 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700633 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800634 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
635 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700636
Calin Juravle114f0812017-03-08 19:05:07 -0800637 // For secondary dex files, we don't really need the user but we use it for sanity checks.
638 // Note: the user owning the dex file should be the current user.
639 std::vector<userid_t> users;
640 if (is_secondary_dex){
641 users.push_back(multiuser_get_user_id(uid));
642 } else {
643 users = get_known_users(/*volume_uuid*/ nullptr);
644 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700645 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800646 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700647 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800648 if (profile_fd.get() >= 0) {
649 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700650 }
651 }
652}
653
654static void drop_capabilities(uid_t uid) {
655 if (setgid(uid) != 0) {
656 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
657 exit(64);
658 }
659 if (setuid(uid) != 0) {
660 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
661 exit(65);
662 }
663 // drop capabilities
664 struct __user_cap_header_struct capheader;
665 struct __user_cap_data_struct capdata[2];
666 memset(&capheader, 0, sizeof(capheader));
667 memset(&capdata, 0, sizeof(capdata));
668 capheader.version = _LINUX_CAPABILITY_VERSION_3;
669 if (capset(&capheader, &capdata[0]) < 0) {
670 ALOGE("capset failed: %s\n", strerror(errno));
671 exit(66);
672 }
673}
674
675static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
676static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
677static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
678static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
679static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
680
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800681static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
682 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700683 static const size_t MAX_INT_LEN = 32;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700684 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700685
686 std::vector<std::string> profile_args(profiles_fd.size());
687 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
688 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800689 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 profile_args[k].assign(profile_buf);
691 }
692 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800693 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700694
695 // program name, reference profile fd, the final NULL and the profile fds
696 const char* argv[3 + profiles_fd.size()];
697 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700698 argv[i++] = profman_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700699 argv[i++] = reference_profile_arg;
700 for (size_t k = 0; k < profile_args.size(); k++) {
701 argv[i++] = profile_args[k].c_str();
702 }
703 // Do not add after dex2oat_flags, they should override others for debugging.
704 argv[i] = NULL;
705
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700706 execv(profman_bin, (char * const *)argv);
707 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700708 exit(68); /* only get here on exec failure */
709}
710
711// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800712// The location is the package name for primary apks or the dex path for secondary dex files.
713// Returns true if there is enough information in the current profiles that makes it
714// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700715// If the return value is true all the current profiles would have been merged into
716// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800717static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800718 std::vector<unique_fd> profiles_fd;
719 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800720 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800721 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700722 // Skip profile guided compilation because no profiles were found.
723 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700724 return false;
725 }
726
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727 pid_t pid = fork();
728 if (pid == 0) {
729 /* child -- drop privileges before continuing */
730 drop_capabilities(uid);
731 run_profman_merge(profiles_fd, reference_profile_fd);
732 exit(68); /* only get here on exec failure */
733 }
734 /* parent */
735 int return_code = wait_child(pid);
736 bool need_to_compile = false;
737 bool should_clear_current_profiles = false;
738 bool should_clear_reference_profile = false;
739 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800740 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700741 } else {
742 return_code = WEXITSTATUS(return_code);
743 switch (return_code) {
744 case PROFMAN_BIN_RETURN_CODE_COMPILE:
745 need_to_compile = true;
746 should_clear_current_profiles = true;
747 should_clear_reference_profile = false;
748 break;
749 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
750 need_to_compile = false;
751 should_clear_current_profiles = false;
752 should_clear_reference_profile = false;
753 break;
754 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800755 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700756 need_to_compile = false;
757 should_clear_current_profiles = true;
758 should_clear_reference_profile = true;
759 break;
760 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
761 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
762 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800763 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700764 need_to_compile = false;
765 should_clear_current_profiles = false;
766 should_clear_reference_profile = false;
767 break;
768 default:
769 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800770 LOG(WARNING) << "Unknown error code while processing profiles for location "
771 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700772 need_to_compile = false;
773 should_clear_current_profiles = true;
774 should_clear_reference_profile = true;
775 break;
776 }
777 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800778
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800780 if (is_secondary_dex) {
781 // For secondary dex files, the owning user is the current user.
782 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
783 } else {
784 clear_primary_current_profiles(location);
785 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700786 }
787 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800788 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700789 }
790 return need_to_compile;
791}
792
Calin Juravle114f0812017-03-08 19:05:07 -0800793// Decides if profile guided compilation is needed or not based on existing profiles.
794// The analysis is done for the primary apks of the given package.
795// Returns true if there is enough information in the current profiles that makes it
796// worth to recompile the package.
797// If the return value is true all the current profiles would have been merged into
798// the reference profiles accessible with open_reference_profile().
799bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
800 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
801}
802
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800803static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
804 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700805 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800806 const std::vector<unique_fd>& apk_fds,
807 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700808 std::vector<std::string> profman_args;
809 static const char* PROFMAN_BIN = "/system/bin/profman";
810 profman_args.push_back(PROFMAN_BIN);
811 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800812 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700813 if (reference_profile_fd != -1) {
814 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800815 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700816 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800817 for (size_t i = 0; i < profile_fds.size(); i++) {
818 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700819 }
820 for (const std::string& dex_location : dex_locations) {
821 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
822 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800823 for (size_t i = 0; i < apk_fds.size(); i++) {
824 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825 }
826 const char **argv = new const char*[profman_args.size() + 1];
827 size_t i = 0;
828 for (const std::string& profman_arg : profman_args) {
829 argv[i++] = profman_arg.c_str();
830 }
831 argv[i] = NULL;
832
833 execv(PROFMAN_BIN, (char * const *)argv);
834 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
835 exit(68); /* only get here on exec failure */
836}
837
Calin Juravle76268c52017-03-09 13:19:42 -0800838bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800839 std::vector<unique_fd> profile_fds;
840 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800841 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842
Calin Juravle114f0812017-03-08 19:05:07 -0800843 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
844 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700845
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800846 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 const bool has_profiles = !profile_fds.empty();
848
849 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800850 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700851 return false;
852 }
853
Calin Juravle114f0812017-03-08 19:05:07 -0800854 unique_fd output_fd(open(out_file_name.c_str(),
855 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
857 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
858 return false;
859 }
860 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
861 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800862 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700863 for (const std::string& code_full_path : code_full_paths) {
864 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800865 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700866 if (apk_fd == -1) {
867 ALOGE("installd cannot open '%s'\n", full_path);
868 return false;
869 }
870 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800871 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700872 }
873
874 pid_t pid = fork();
875 if (pid == 0) {
876 /* child -- drop privileges before continuing */
877 drop_capabilities(uid);
878 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
879 apk_fds, output_fd);
880 exit(68); /* only get here on exec failure */
881 }
882 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700883 int return_code = wait_child(pid);
884 if (!WIFEXITED(return_code)) {
885 LOG(WARNING) << "profman failed for package " << pkgname << ": "
886 << return_code;
887 return false;
888 }
889 return true;
890}
891
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700892bool copy_system_profile(const std::string& system_profile,
893 uid_t packageUid, const std::string& data_profile_location) {
894 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
895 unique_fd out_fd(open_reference_profile(packageUid,
896 data_profile_location,
897 /*read_write*/ true,
898 /*secondary*/ false));
899 if (in_fd.get() < 0) {
900 PLOG(WARNING) << "Could not open profile " << system_profile;
901 return false;
902 }
903 if (out_fd.get() < 0) {
904 PLOG(WARNING) << "Could not open profile " << data_profile_location;
905 return false;
906 }
907
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700908 // As a security measure we want to write the profile information with the reduced capabilities
909 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700910 pid_t pid = fork();
911 if (pid == 0) {
912 /* child -- drop privileges before continuing */
913 drop_capabilities(packageUid);
914
915 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
916 if (errno != EWOULDBLOCK) {
917 PLOG(WARNING) << "Error locking profile " << data_profile_location;
918 }
919 // This implies that the app owning this profile is running
920 // (and has acquired the lock).
921 //
922 // The app never acquires the lock for the reference profiles of primary apks.
923 // Only dex2oat from installd will do that. Since installd is single threaded
924 // we should not see this case. Nevertheless be prepared for it.
925 PLOG(WARNING) << "Failed to flock " << data_profile_location;
926 return false;
927 }
928
929 bool truncated = ftruncate(out_fd.get(), 0) == 0;
930 if (!truncated) {
931 PLOG(WARNING) << "Could not truncate " << data_profile_location;
932 }
933
934 // Copy over data.
935 static constexpr size_t kBufferSize = 4 * 1024;
936 char buffer[kBufferSize];
937 while (true) {
938 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
939 if (bytes == 0) {
940 break;
941 }
942 write(out_fd.get(), buffer, bytes);
943 }
944 if (flock(out_fd.get(), LOCK_UN) != 0) {
945 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
946 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700947 // Use _exit since we don't want to run the global destructors in the child.
948 // b/62597429
949 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700950 }
951 /* parent */
952 int return_code = wait_child(pid);
953 return return_code == 0;
954}
955
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
957 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
958 if (EndsWith(oat_path, ".dex")) {
959 std::string new_path = oat_path;
960 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
961 CHECK(EndsWith(new_path, new_ext.c_str()));
962 return new_path;
963 }
964
965 // An odex entry. Not that this may not be an extension, e.g., in the OTA
966 // case (where the base name will have an extension for the B artifact).
967 size_t odex_pos = oat_path.rfind(".odex");
968 if (odex_pos != std::string::npos) {
969 std::string new_path = oat_path;
970 new_path.replace(odex_pos, strlen(".odex"), new_ext);
971 CHECK_NE(new_path.find(new_ext), std::string::npos);
972 return new_path;
973 }
974
975 // Don't know how to handle this.
976 return "";
977}
978
979// Translate the given oat path to an art (app image) path. An empty string
980// denotes an error.
981static std::string create_image_filename(const std::string& oat_path) {
982 return replace_file_extension(oat_path, ".art");
983}
984
985// Translate the given oat path to a vdex path. An empty string denotes an error.
986static std::string create_vdex_filename(const std::string& oat_path) {
987 return replace_file_extension(oat_path, ".vdex");
988}
989
Jeff Sharkey90aff262016-12-12 14:28:24 -0700990static int open_output_file(const char* file_name, bool recreate, int permissions) {
991 int flags = O_RDWR | O_CREAT;
992 if (recreate) {
993 if (unlink(file_name) < 0) {
994 if (errno != ENOENT) {
995 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
996 }
997 }
998 flags |= O_EXCL;
999 }
1000 return open(file_name, flags, permissions);
1001}
1002
Calin Juravle2289c0a2017-02-15 12:44:14 -08001003static bool set_permissions_and_ownership(
1004 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1005 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1006 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001007 if (fchmod(fd,
1008 S_IRUSR|S_IWUSR|S_IRGRP |
1009 (is_public ? S_IROTH : 0)) < 0) {
1010 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1011 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001012 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001013 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1014 return false;
1015 }
1016 return true;
1017}
1018
1019static bool IsOutputDalvikCache(const char* oat_dir) {
1020 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1021 // into '!'. Play it safe by handling it both.
1022 // TODO: ensure we never get null.
1023 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1024 return oat_dir == nullptr || oat_dir[0] == '!';
1025}
1026
Calin Juravled23dee72017-07-06 16:29:11 -07001027// Best-effort check whether we can fit the the path into our buffers.
1028// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1029// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1030// extension to the cache path (5 bytes).
1031// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1032static bool validate_dex_path_size(const std::string& dex_path) {
1033 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1034 LOG(ERROR) << "dex_path too long: " << dex_path;
1035 return false;
1036 }
1037 return true;
1038}
1039
Jeff Sharkey90aff262016-12-12 14:28:24 -07001040static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001041 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001042 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001043 return false;
1044 }
1045
1046 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001047 // Oat dirs for secondary dex files are already validated.
1048 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001049 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1050 return false;
1051 }
1052 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1053 return false;
1054 }
1055 } else {
1056 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1057 return false;
1058 }
1059 }
1060 return true;
1061}
1062
1063// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1064// on destruction. It will also run the given cleanup (unless told not to) after closing.
1065//
1066// Usage example:
1067//
Calin Juravle7a570e82017-01-14 16:23:30 -08001068// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001069// [name]() {
1070// unlink(name.c_str());
1071// });
1072// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1073// wrapper if captured as a reference.
1074//
1075// if (file.get() == -1) {
1076// // Error opening...
1077// }
1078//
1079// ...
1080// if (error) {
1081// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1082// // and delete the file (after the fd is closed).
1083// return -1;
1084// }
1085//
1086// (Success case)
1087// file.SetCleanup(false);
1088// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1089// // (leaving the file around; after the fd is closed).
1090//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001091class Dex2oatFileWrapper {
1092 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001093 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001094 }
1095
Calin Juravle7a570e82017-01-14 16:23:30 -08001096 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1097 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1098
1099 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1100 value_ = other.value_;
1101 cleanup_ = other.cleanup_;
1102 do_cleanup_ = other.do_cleanup_;
1103 auto_close_ = other.auto_close_;
1104 other.release();
1105 }
1106
1107 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1108 value_ = other.value_;
1109 cleanup_ = other.cleanup_;
1110 do_cleanup_ = other.do_cleanup_;
1111 auto_close_ = other.auto_close_;
1112 other.release();
1113 return *this;
1114 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001115
1116 ~Dex2oatFileWrapper() {
1117 reset(-1);
1118 }
1119
1120 int get() {
1121 return value_;
1122 }
1123
1124 void SetCleanup(bool cleanup) {
1125 do_cleanup_ = cleanup;
1126 }
1127
1128 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001129 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001130 close(value_);
1131 }
1132 if (do_cleanup_ && cleanup_ != nullptr) {
1133 cleanup_();
1134 }
1135
1136 value_ = new_value;
1137 }
1138
Calin Juravle7a570e82017-01-14 16:23:30 -08001139 void reset(int new_value, std::function<void ()> new_cleanup) {
1140 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 cleanup_ = new_cleanup;
1149 }
1150
Calin Juravle7a570e82017-01-14 16:23:30 -08001151 void DisableAutoClose() {
1152 auto_close_ = false;
1153 }
1154
Jeff Sharkey90aff262016-12-12 14:28:24 -07001155 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 void release() {
1157 value_ = -1;
1158 do_cleanup_ = false;
1159 cleanup_ = nullptr;
1160 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001161 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001162 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001163 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001164 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001165};
1166
Calin Juravle7a570e82017-01-14 16:23:30 -08001167// (re)Creates the app image if needed.
1168Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001169 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001170
1171 // We don't create an image for secondary dex files.
1172 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001173 return Dex2oatFileWrapper();
1174 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001175
Calin Juravle7a570e82017-01-14 16:23:30 -08001176 const std::string image_path = create_image_filename(out_oat_path);
1177 if (image_path.empty()) {
1178 // Happens when the out_oat_path has an unknown extension.
1179 return Dex2oatFileWrapper();
1180 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001181
1182 // Use app images only if it is enabled (by a set image format) and we are compiling
1183 // profile-guided (so the app image doesn't conservatively contain all classes).
1184 if (!profile_guided) {
1185 // In case there is a stale image, remove it now. Ignore any error.
1186 unlink(image_path.c_str());
1187 return Dex2oatFileWrapper();
1188 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001189 char app_image_format[kPropertyValueMax];
1190 bool have_app_image_format =
1191 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1192 if (!have_app_image_format) {
1193 return Dex2oatFileWrapper();
1194 }
1195 // Recreate is true since we do not want to modify a mapped image. If the app is
1196 // already running and we modify the image file, it can cause crashes (b/27493510).
1197 Dex2oatFileWrapper wrapper_fd(
1198 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1199 [image_path]() { unlink(image_path.c_str()); });
1200 if (wrapper_fd.get() < 0) {
1201 // Could not create application image file. Go on since we can compile without it.
1202 LOG(ERROR) << "installd could not create '" << image_path
1203 << "' for image file during dexopt";
1204 // If we have a valid image file path but no image fd, explicitly erase the image file.
1205 if (unlink(image_path.c_str()) < 0) {
1206 if (errno != ENOENT) {
1207 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1208 }
1209 }
1210 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001211 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001212 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1213 wrapper_fd.reset(-1);
1214 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001215
Calin Juravle7a570e82017-01-14 16:23:30 -08001216 return wrapper_fd;
1217}
1218
1219// Creates the dexopt swap file if necessary and return its fd.
1220// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001221unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001222 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001223 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001224 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001225 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001226 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001227 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001228 if (swap_fd.get() < 0) {
1229 // Could not create swap file. Optimistically go on and hope that we can compile
1230 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001231 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001232 } else {
1233 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001234 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001235 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1236 }
1237 }
1238 return swap_fd;
1239}
1240
1241// Opens the reference profiles if needed.
1242// 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 -08001243Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1244 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1245 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001246 // Public apps should not be compiled with profile information ever. Same goes for the special
1247 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001248 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001250 }
Calin Juravle114f0812017-03-08 19:05:07 -08001251
1252 // Open reference profile in read only mode as dex2oat does not get write permissions.
1253 const std::string location = is_secondary_dex ? dex_path : pkgname;
1254 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1255 const auto& cleanup = [location, is_secondary_dex]() {
1256 clear_reference_profile(location.c_str(), is_secondary_dex);
1257 };
1258 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001259}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001260
Calin Juravle7a570e82017-01-14 16:23:30 -08001261// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1262// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001263bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001264 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001265 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001266 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1267 CHECK(in_vdex_wrapper_fd != nullptr);
1268 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001269 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1270 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001271 char in_odex_path[PKG_PATH_MAX];
1272 int dexopt_action = abs(dexopt_needed);
1273 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001274 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001275
1276 // Infer the name of the output VDEX.
1277 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1278 if (out_vdex_path_str.empty()) {
1279 return false;
1280 }
1281
1282 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001283 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001284 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1285 const char* path = nullptr;
1286 if (is_odex_location) {
1287 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1288 path = in_odex_path;
1289 } else {
1290 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001292 }
1293 } else {
1294 path = out_oat_path;
1295 }
1296 in_vdex_path_str = create_vdex_filename(path);
1297 if (in_vdex_path_str.empty()) {
1298 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001299 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001300 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001301 // We can update in place when all these conditions are met:
1302 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1303 // on /system typically cannot be updated in place).
1304 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1305 // cannot be currently used by a running process.
1306 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1307 // different vdex files to operate.
1308 update_vdex_in_place =
1309 (in_vdex_path_str == out_vdex_path_str) &&
1310 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1311 !profile_guided;
1312 if (update_vdex_in_place) {
1313 // Open the file read-write to be able to update it.
1314 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1315 if (in_vdex_wrapper_fd->get() == -1) {
1316 // If we failed to open the file, we cannot update it in place.
1317 update_vdex_in_place = false;
1318 }
1319 } else {
1320 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1321 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001322 }
1323
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001324 // If we are updating the vdex in place, we do not need to recreate a vdex,
1325 // and can use the same existing one.
1326 if (update_vdex_in_place) {
1327 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1328 // have bogus stale vdex files.
1329 out_vdex_wrapper_fd->reset(
1330 in_vdex_wrapper_fd->get(),
1331 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1332 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1333 // wrapper).
1334 in_vdex_wrapper_fd->DisableAutoClose();
1335 } else {
1336 out_vdex_wrapper_fd->reset(
1337 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1338 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1339 if (out_vdex_wrapper_fd->get() < 0) {
1340 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1341 return false;
1342 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001343 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001344 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001345 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001346 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1347 return false;
1348 }
1349
1350 // If we got here we successfully opened the vdex files.
1351 return true;
1352}
1353
1354// Opens the output oat file for the given apk.
1355// If successful it stores the output path into out_oat_path and returns true.
1356Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001357 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1358 char* out_oat_path) {
1359 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001360 return Dex2oatFileWrapper();
1361 }
1362 const std::string out_oat_path_str(out_oat_path);
1363 Dex2oatFileWrapper wrapper_fd(
1364 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1365 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1366 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001367 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001368 } else if (!set_permissions_and_ownership(
1369 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001370 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1371 wrapper_fd.reset(-1);
1372 }
1373 return wrapper_fd;
1374}
1375
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001376// Creates RDONLY fds for oat and vdex files, if exist.
1377// Returns false if it fails to create oat out path for the given apk path.
1378// Note that the method returns true even if the files could not be opened.
1379bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1380 const std::string& oat_dir,
1381 const std::string& instruction_set,
1382 bool is_secondary_dex,
1383 unique_fd* oat_file_fd,
1384 unique_fd* vdex_file_fd) {
1385 char oat_path[PKG_PATH_MAX];
1386 if (!create_oat_out_path(apk_path.c_str(),
1387 instruction_set.c_str(),
1388 oat_dir.c_str(),
1389 is_secondary_dex,
1390 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001391 LOG(ERROR) << "Could not create oat out path for "
1392 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001393 return false;
1394 }
1395 oat_file_fd->reset(open(oat_path, O_RDONLY));
1396 if (oat_file_fd->get() < 0) {
1397 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1398 }
1399
1400 std::string vdex_filename = create_vdex_filename(oat_path);
1401 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1402 if (vdex_file_fd->get() < 0) {
1403 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1404 }
1405
1406 return true;
1407}
1408
Calin Juravle7a570e82017-01-14 16:23:30 -08001409// Updates the access times of out_oat_path based on those from apk_path.
1410void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1411 struct stat input_stat;
1412 memset(&input_stat, 0, sizeof(input_stat));
1413 if (stat(apk_path, &input_stat) != 0) {
1414 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1415 return;
1416 }
1417
1418 struct utimbuf ut;
1419 ut.actime = input_stat.st_atime;
1420 ut.modtime = input_stat.st_mtime;
1421 if (utime(out_oat_path, &ut) != 0) {
1422 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1423 }
1424}
1425
Calin Juravle80a21252017-01-17 14:43:25 -08001426// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001427// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1428// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1429// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001430static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1431 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1432 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001433 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001434 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001435 const char* dexoptanalyzer_bin =
1436 is_debug_runtime()
1437 ? "/system/bin/dexoptanalyzerd"
1438 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001439 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1440
Calin Juravled23dee72017-07-06 16:29:11 -07001441 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1442 LOG(ERROR) << "Instruction set " << instruction_set
1443 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001444 return;
1445 }
1446
Calin Juravled23dee72017-07-06 16:29:11 -07001447 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001448 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1449 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1450 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001451 std::string isa_arg = "--isa=" + instruction_set;
1452 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001453 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001454 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001455 std::string class_loader_context_arg = "--class-loader-context=";
1456 if (class_loader_context != nullptr) {
1457 class_loader_context_arg += class_loader_context;
1458 }
Calin Juravle80a21252017-01-17 14:43:25 -08001459
Calin Juravle80a21252017-01-17 14:43:25 -08001460 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001461 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001462 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001463 (vdex_fd >= 0 ? 1 : 0) +
1464 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001465 (downgrade ? 1 : 0) +
1466 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001467 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001468 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001469 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001470 argv[i++] = dex_file_arg.c_str();
1471 argv[i++] = isa_arg.c_str();
1472 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001473 if (oat_fd >= 0) {
1474 argv[i++] = oat_fd_arg.c_str();
1475 }
1476 if (vdex_fd >= 0) {
1477 argv[i++] = vdex_fd_arg.c_str();
1478 }
1479 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001480 if (profile_was_updated) {
1481 argv[i++] = assume_profile_changed;
1482 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001483 if (downgrade) {
1484 argv[i++] = downgrade_flag;
1485 }
Calin Juravle58cab072017-09-12 01:02:26 -07001486 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001487 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001488 }
Calin Juravle80a21252017-01-17 14:43:25 -08001489 argv[i] = NULL;
1490
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001491 execv(dexoptanalyzer_bin, (char * const *)argv);
1492 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001493}
1494
1495// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001496static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001497 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001498 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001499 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001500 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001501 return false;
1502 }
Calin Juravle114f0812017-03-08 19:05:07 -08001503 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001504
Calin Juravle80a21252017-01-17 14:43:25 -08001505 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001506 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1507 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001508 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001509 return false;
1510 }
1511
1512 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001513 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001514
Calin Juravle7d765462017-09-04 15:57:10 -07001515 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001516 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001517 return false;
1518 }
1519
1520 return true;
1521}
1522
Calin Juravle7d765462017-09-04 15:57:10 -07001523// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1524// secondary dex files. This return codes are returned by the child process created for
1525// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001526
Calin Juravle7d765462017-09-04 15:57:10 -07001527// The dexoptanalyzer was not invoked because of validation or IO errors.
1528static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1529// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1530static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1531
1532// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001533// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1534// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001535// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1536// of dexoptanalyzer.
1537static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001538 int* dexopt_needed_out) {
1539 // The result values are defined in dexoptanalyzer.
1540 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001541 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001542 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001543 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001544 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001545 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001546 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001547 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001548 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001549 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001550 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001551 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1552 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1553 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001554 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1555 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001556 << " : dexoptanalyzer result=" << result;
1557 return false;
Calin Juravle7d765462017-09-04 15:57:10 -07001558 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1559 // If the file does not exist there's no need for dexopt.
1560 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1561 return true;
1562 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1563 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001564 default:
Calin Juravle7d765462017-09-04 15:57:10 -07001565 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1566 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001567 return false;
1568 }
1569}
1570
Calin Juravle7d765462017-09-04 15:57:10 -07001571enum SecondaryDexAccess {
1572 kSecondaryDexAccessReadOk = 0,
1573 kSecondaryDexAccessDoesNotExist = 1,
1574 kSecondaryDexAccessPermissionError = 2,
1575 kSecondaryDexAccessIOError = 3
1576};
1577
1578static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1579 // Check if the path exists and can be read. If not, there's nothing to do.
1580 if (access(dex_path.c_str(), R_OK) == 0) {
1581 return kSecondaryDexAccessReadOk;
1582 } else {
1583 if (errno == ENOENT) {
1584 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1585 return kSecondaryDexAccessDoesNotExist;
1586 } else {
1587 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1588 return errno == EACCES
1589 ? kSecondaryDexAccessPermissionError
1590 : kSecondaryDexAccessIOError;
1591 }
1592 }
1593}
1594
1595static bool is_file_public(const std::string& filename) {
1596 struct stat file_stat;
1597 if (stat(filename.c_str(), &file_stat) == 0) {
1598 return (file_stat.st_mode & S_IROTH) != 0;
1599 }
1600 return false;
1601}
1602
1603// Create the oat file structure for the secondary dex 'dex_path' and assign
1604// the individual path component to the 'out_' parameters.
1605static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1606 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1607 size_t dirIndex = dex_path.rfind('/');
1608 if (dirIndex == std::string::npos) {
1609 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1610 return false;
1611 }
1612 // TODO(calin): we have similar computations in at lest 3 other places
1613 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1614 // using string append.
1615 std::string apk_dir = dex_path.substr(0, dirIndex);
1616 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1617 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1618
1619 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1620 /*is_secondary_dex*/true, out_oat_path)) {
1621 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1622 return false;
1623 }
1624 return true;
1625}
1626
1627// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1628// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1629static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1630 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1631 *out_storage_flag = FLAG_STORAGE_CE;
1632 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1633 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1634 return false;
1635 }
1636 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1637 *out_storage_flag = FLAG_STORAGE_DE;
1638 } else {
1639 LOG(ERROR) << "Secondary dex storage flag must be set";
1640 return false;
1641 }
1642 return true;
1643}
1644
Calin Juravlec9eab382017-01-25 01:17:17 -08001645// 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 -08001646// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1647// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001648// When returning true, the output parameters will be:
1649// - is_public_out: whether or not the oat file should not be made public
1650// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1651// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001652static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001653 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001654 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle7d765462017-09-04 15:57:10 -07001655 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1656 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001657 int storage_flag;
Calin Juravle7d765462017-09-04 15:57:10 -07001658 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001659 return false;
1660 }
Calin Juravle7d765462017-09-04 15:57:10 -07001661 // Compute the oat dir as it's not easy to extract it from the child computation.
1662 char oat_path[PKG_PATH_MAX];
1663 char oat_dir[PKG_PATH_MAX];
1664 char oat_isa_dir[PKG_PATH_MAX];
1665 if (!create_secondary_dex_oat_layout(
1666 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1667 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001668 return false;
1669 }
Calin Juravle7d765462017-09-04 15:57:10 -07001670 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001671
Calin Juravle80a21252017-01-17 14:43:25 -08001672 pid_t pid = fork();
1673 if (pid == 0) {
1674 // child -- drop privileges before continuing.
1675 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001676
1677 // Validate the path structure.
1678 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1679 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1680 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1681 }
1682
1683 // Open the dex file.
1684 unique_fd zip_fd;
1685 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1686 if (zip_fd.get() < 0) {
1687 if (errno == ENOENT) {
1688 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1689 } else {
1690 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1691 }
1692 }
1693
1694 // Prepare the oat directories.
1695 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1696 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1697 }
1698
1699 // Open the vdex/oat files if any.
1700 unique_fd oat_file_fd;
1701 unique_fd vdex_file_fd;
1702 if (!maybe_open_oat_and_vdex_file(dex_path,
1703 *oat_dir_out,
1704 instruction_set,
1705 true /* is_secondary_dex */,
1706 &oat_file_fd,
1707 &vdex_file_fd)) {
1708 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1709 }
1710
1711 // Analyze profiles.
1712 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1713
1714 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001715 exec_dexoptanalyzer(dex_path,
1716 vdex_file_fd.get(),
1717 oat_file_fd.get(),
1718 zip_fd.get(),
1719 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001720 compiler_filter, profile_was_updated,
1721 downgrade,
1722 class_loader_context);
1723 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1724 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001725 }
1726
1727 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001728 int result = wait_child(pid);
1729 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001730 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001731 return false;
1732 }
1733 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001734 // Check that we successfully executed dexoptanalyzer.
1735 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1736
1737 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1738
Calin Juravle80a21252017-01-17 14:43:25 -08001739 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001740 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1741 // makes the code simpler; force compilation is only needed during tests).
1742 if (success &&
1743 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1744 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001745 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1746 }
1747
Calin Juravle7d765462017-09-04 15:57:10 -07001748 // Check if we should make the oat file public.
1749 // Note that if the dex file is not public the compiled code cannot be made public.
1750 // It is ok to check this flag outside in the parent process.
1751 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1752
Calin Juravle80a21252017-01-17 14:43:25 -08001753 return success;
1754}
1755
Calin Juravlec9eab382017-01-25 01:17:17 -08001756int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001757 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001758 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001759 bool downgrade) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001760 CHECK(pkgname != nullptr);
1761 CHECK(pkgname[0] != 0);
1762 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1763 LOG_FATAL("dexopt flags contains unknown fields\n");
1764 }
1765
Calin Juravled23dee72017-07-06 16:29:11 -07001766 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001767 return -1;
1768 }
1769
1770 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1771 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1772 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001773 }
1774
Calin Juravleebc8a792017-04-04 20:21:05 -07001775 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001776 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1777 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1778 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001779 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001780 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001781
1782 // Check if we're dealing with a secondary dex file and if we need to compile it.
1783 std::string oat_dir_str;
1784 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001785 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001786 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle7d765462017-09-04 15:57:10 -07001787 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001788 oat_dir = oat_dir_str.c_str();
1789 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1790 return 0; // Nothing to do, report success.
1791 }
1792 } else {
1793 return -1; // We had an error, logged in the process method.
1794 }
1795 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001796 // Currently these flags are only use for secondary dex files.
1797 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001798 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1799 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1800 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001801
1802 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001803 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001804 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001805 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001806 return -1;
1807 }
1808
1809 // Create the output OAT file.
1810 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001811 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001812 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001813 if (out_oat_fd.get() < 0) {
1814 return -1;
1815 }
1816
1817 // Open vdex files.
1818 Dex2oatFileWrapper in_vdex_fd;
1819 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001820 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1821 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001822 return -1;
1823 }
1824
Calin Juravlecb556e32017-04-04 20:22:50 -07001825 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1826 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1827 // fully inherit their parent context).
1828 // Note that for primary apk the oat files are created before, in a separate installd
1829 // call which also does the restorecon. TODO(calin): unify the paths.
1830 if (is_secondary_dex) {
1831 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1832 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1833 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1834 return -1;
1835 }
1836 }
1837
Jeff Sharkey90aff262016-12-12 14:28:24 -07001838 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001839 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001840
Calin Juravle7a570e82017-01-14 16:23:30 -08001841 // Create the app image file if needed.
1842 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001843 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001844
Calin Juravle7a570e82017-01-14 16:23:30 -08001845 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001846 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1847 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001848
Calin Juravlec9eab382017-01-25 01:17:17 -08001849 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001850
1851 pid_t pid = fork();
1852 if (pid == 0) {
1853 /* child -- drop privileges before continuing */
1854 drop_capabilities(uid);
1855
Richard Uhler76cc0272016-12-08 10:46:35 +00001856 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001857 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1858 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1859 _exit(67);
1860 }
1861
Richard Uhler76cc0272016-12-08 10:46:35 +00001862 run_dex2oat(input_fd.get(),
1863 out_oat_fd.get(),
1864 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001865 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001866 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001867 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001868 out_oat_path,
1869 swap_fd.get(),
1870 instruction_set,
1871 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001872 debuggable,
1873 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001874 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00001875 reference_profile_fd.get(),
Calin Juravle52c45822017-07-13 22:50:21 -07001876 class_loader_context);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001877 _exit(68); /* only get here on exec failure */
1878 } else {
1879 int res = wait_child(pid);
1880 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001881 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001882 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001883 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001884 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001885 }
1886 }
1887
Calin Juravlec9eab382017-01-25 01:17:17 -08001888 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001889
1890 // We've been successful, don't delete output.
1891 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001892 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001893 image_fd.SetCleanup(false);
1894 reference_profile_fd.SetCleanup(false);
1895
1896 return 0;
1897}
1898
Calin Juravlec9eab382017-01-25 01:17:17 -08001899// Try to remove the given directory. Log an error if the directory exists
1900// and is empty but could not be removed.
1901static bool rmdir_if_empty(const char* dir) {
1902 if (rmdir(dir) == 0) {
1903 return true;
1904 }
1905 if (errno == ENOENT || errno == ENOTEMPTY) {
1906 return true;
1907 }
1908 PLOG(ERROR) << "Failed to remove dir: " << dir;
1909 return false;
1910}
1911
1912// Try to unlink the given file. Log an error if the file exists and could not
1913// be unlinked.
1914static bool unlink_if_exists(const std::string& file) {
1915 if (unlink(file.c_str()) == 0) {
1916 return true;
1917 }
1918 if (errno == ENOENT) {
1919 return true;
1920
1921 }
1922 PLOG(ERROR) << "Could not unlink: " << file;
1923 return false;
1924}
1925
Calin Juravle7d765462017-09-04 15:57:10 -07001926enum ReconcileSecondaryDexResult {
1927 kReconcileSecondaryDexExists = 0,
1928 kReconcileSecondaryDexCleanedUp = 1,
1929 kReconcileSecondaryDexValidationError = 2,
1930 kReconcileSecondaryDexCleanUpError = 3,
1931 kReconcileSecondaryDexAccessIOError = 4,
1932};
Calin Juravlec9eab382017-01-25 01:17:17 -08001933
1934// Reconcile the secondary dex 'dex_path' and its generated oat files.
1935// Return true if all the parameters are valid and the secondary dex file was
1936// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1937// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1938// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1939// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1940// Return false if there were errors during processing. In this case
1941// out_secondary_dex_exists will be set to false.
1942bool reconcile_secondary_dex_file(const std::string& dex_path,
1943 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1944 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1945 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001946 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001947 if (isas.size() == 0) {
1948 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1949 return false;
1950 }
1951
Calin Juravle7d765462017-09-04 15:57:10 -07001952 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1953 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1954 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001955 return false;
1956 }
1957
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001958 // As a security measure we want to unlink art artifacts with the reduced capabilities
1959 // of the package user id. So we fork and drop capabilities in the child.
1960 pid_t pid = fork();
1961 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001962 /* child -- drop privileges before continuing */
1963 drop_capabilities(uid);
1964
1965 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1966 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1967 uid, storage_flag)) {
1968 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1969 _exit(kReconcileSecondaryDexValidationError);
1970 }
1971
1972 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1973 switch (access_check) {
1974 case kSecondaryDexAccessDoesNotExist:
1975 // File does not exist. Proceed with cleaning.
1976 break;
1977 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1978 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1979 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1980 default:
1981 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
1982 _exit(kReconcileSecondaryDexValidationError);
1983 }
1984
1985 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001986 char oat_path[PKG_PATH_MAX];
1987 char oat_dir[PKG_PATH_MAX];
1988 char oat_isa_dir[PKG_PATH_MAX];
1989 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001990 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle7d765462017-09-04 15:57:10 -07001991 if (!create_secondary_dex_oat_layout(
1992 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
1993 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1994 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001995 }
Calin Juravle51314092017-05-18 15:33:05 -07001996
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001997 // Delete oat/vdex/art files.
1998 result = unlink_if_exists(oat_path) && result;
1999 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2000 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002001
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002002 // Delete profiles.
2003 std::string current_profile = create_current_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002004 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002005 std::string reference_profile = create_reference_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002006 dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002007 result = unlink_if_exists(current_profile) && result;
2008 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002009
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002010 // We upgraded once the location of current profile for secondary dex files.
2011 // Check for any previous left-overs and remove them as well.
2012 std::string old_current_profile = dex_path + ".prof";
2013 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002014
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002015 // Try removing the directories as well, they might be empty.
2016 result = rmdir_if_empty(oat_isa_dir) && result;
2017 result = rmdir_if_empty(oat_dir) && result;
2018 }
Calin Juravle7d765462017-09-04 15:57:10 -07002019 if (!result) {
2020 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2021 }
2022 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002023 }
2024
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002025 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002026 if (!WIFEXITED(return_code)) {
2027 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2028 } else {
2029 return_code = WEXITSTATUS(return_code);
2030 }
2031
2032 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2033
2034 switch (return_code) {
2035 case kReconcileSecondaryDexCleanedUp:
2036 case kReconcileSecondaryDexValidationError:
2037 // If we couldn't validate assume the dex file does not exist.
2038 // This will purge the entry from the PM records.
2039 *out_secondary_dex_exists = false;
2040 return true;
2041 case kReconcileSecondaryDexExists:
2042 *out_secondary_dex_exists = true;
2043 return true;
2044 case kReconcileSecondaryDexAccessIOError:
2045 // We had an access IO error.
2046 // Return false so that we can try again.
2047 // The value of out_secondary_dex_exists does not matter in this case and by convention
2048 // is set to false.
2049 *out_secondary_dex_exists = false;
2050 return false;
2051 default:
2052 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2053 *out_secondary_dex_exists = false;
2054 return false;
2055 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002056}
2057
Jeff Sharkey90aff262016-12-12 14:28:24 -07002058// Helper for move_ab, so that we can have common failure-case cleanup.
2059static bool unlink_and_rename(const char* from, const char* to) {
2060 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2061 // return a failure.
2062 struct stat s;
2063 if (stat(to, &s) == 0) {
2064 if (!S_ISREG(s.st_mode)) {
2065 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2066 return false;
2067 }
2068 if (unlink(to) != 0) {
2069 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2070 return false;
2071 }
2072 } else {
2073 // This may be a permission problem. We could investigate the error code, but we'll just
2074 // let the rename failure do the work for us.
2075 }
2076
2077 // Try to rename "to" to "from."
2078 if (rename(from, to) != 0) {
2079 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2080 return false;
2081 }
2082 return true;
2083}
2084
2085// Move/rename a B artifact (from) to an A artifact (to).
2086static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2087 // Check whether B exists.
2088 {
2089 struct stat s;
2090 if (stat(b_path.c_str(), &s) != 0) {
2091 // Silently ignore for now. The service calling this isn't smart enough to understand
2092 // lack of artifacts at the moment.
2093 return false;
2094 }
2095 if (!S_ISREG(s.st_mode)) {
2096 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2097 // Try to unlink, but swallow errors.
2098 unlink(b_path.c_str());
2099 return false;
2100 }
2101 }
2102
2103 // Rename B to A.
2104 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2105 // Delete the b_path so we don't try again (or fail earlier).
2106 if (unlink(b_path.c_str()) != 0) {
2107 PLOG(ERROR) << "Could not unlink " << b_path;
2108 }
2109
2110 return false;
2111 }
2112
2113 return true;
2114}
2115
2116bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2117 // Get the current slot suffix. No suffix, no A/B.
2118 std::string slot_suffix;
2119 {
2120 char buf[kPropertyValueMax];
2121 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2122 return false;
2123 }
2124 slot_suffix = buf;
2125
2126 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2127 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2128 return false;
2129 }
2130 }
2131
2132 // Validate other inputs.
2133 if (validate_apk_path(apk_path) != 0) {
2134 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2135 return false;
2136 }
2137 if (validate_apk_path(oat_dir) != 0) {
2138 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2139 return false;
2140 }
2141
2142 char a_path[PKG_PATH_MAX];
2143 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2144 return false;
2145 }
2146 const std::string a_vdex_path = create_vdex_filename(a_path);
2147 const std::string a_image_path = create_image_filename(a_path);
2148
2149 // B path = A path + slot suffix.
2150 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2151 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2152 const std::string b_image_path = StringPrintf("%s.%s",
2153 a_image_path.c_str(),
2154 slot_suffix.c_str());
2155
2156 bool success = true;
2157 if (move_ab_path(b_path, a_path)) {
2158 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2159 // Note: we can live without an app image. As such, ignore failure to move the image file.
2160 // If we decide to require the app image, or the app image being moved correctly,
2161 // then change accordingly.
2162 constexpr bool kIgnoreAppImageFailure = true;
2163
2164 if (!a_image_path.empty()) {
2165 if (!move_ab_path(b_image_path, a_image_path)) {
2166 unlink(a_image_path.c_str());
2167 if (!kIgnoreAppImageFailure) {
2168 success = false;
2169 }
2170 }
2171 }
2172 } else {
2173 // Cleanup: delete B image, ignore errors.
2174 unlink(b_image_path.c_str());
2175 success = false;
2176 }
2177 } else {
2178 // Cleanup: delete B image, ignore errors.
2179 unlink(b_vdex_path.c_str());
2180 unlink(b_image_path.c_str());
2181 success = false;
2182 }
2183 return success;
2184}
2185
2186bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2187 // Delete the oat/odex file.
2188 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002189 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002190 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002191 return false;
2192 }
2193
2194 // In case of a permission failure report the issue. Otherwise just print a warning.
2195 auto unlink_and_check = [](const char* path) -> bool {
2196 int result = unlink(path);
2197 if (result != 0) {
2198 if (errno == EACCES || errno == EPERM) {
2199 PLOG(ERROR) << "Could not unlink " << path;
2200 return false;
2201 }
2202 PLOG(WARNING) << "Could not unlink " << path;
2203 }
2204 return true;
2205 };
2206
2207 // Delete the oat/odex file.
2208 bool return_value_oat = unlink_and_check(out_path);
2209
2210 // Derive and delete the app image.
2211 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2212
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002213 // Derive and delete the vdex file.
2214 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2215
Jeff Sharkey90aff262016-12-12 14:28:24 -07002216 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002217 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002218}
2219
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002220static bool is_absolute_path(const std::string& path) {
2221 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2222 LOG(ERROR) << "Invalid absolute path " << path;
2223 return false;
2224 } else {
2225 return true;
2226 }
2227}
2228
2229static bool is_valid_instruction_set(const std::string& instruction_set) {
2230 // TODO: add explicit whitelisting of instruction sets
2231 if (instruction_set.find('/') != std::string::npos) {
2232 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2233 return false;
2234 } else {
2235 return true;
2236 }
2237}
2238
2239bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2240 const char *apk_path, const char *instruction_set) {
2241 std::string oat_dir_ = oat_dir;
2242 std::string apk_path_ = apk_path;
2243 std::string instruction_set_ = instruction_set;
2244
2245 if (!is_absolute_path(oat_dir_)) return false;
2246 if (!is_absolute_path(apk_path_)) return false;
2247 if (!is_valid_instruction_set(instruction_set_)) return false;
2248
2249 std::string::size_type end = apk_path_.rfind('.');
2250 std::string::size_type start = apk_path_.rfind('/', end);
2251 if (end == std::string::npos || start == std::string::npos) {
2252 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2253 return false;
2254 }
2255
2256 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2257 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2258 const char* res = res_.c_str();
2259 if (strlen(res) >= PKG_PATH_MAX) {
2260 LOG(ERROR) << "Result too large";
2261 return false;
2262 } else {
2263 strlcpy(path, res, PKG_PATH_MAX);
2264 return true;
2265 }
2266}
2267
2268bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2269 const char *instruction_set) {
2270 std::string apk_path_ = apk_path;
2271 std::string instruction_set_ = instruction_set;
2272
2273 if (!is_absolute_path(apk_path_)) return false;
2274 if (!is_valid_instruction_set(instruction_set_)) return false;
2275
2276 std::string::size_type end = apk_path_.rfind('.');
2277 std::string::size_type start = apk_path_.rfind('/', end);
2278 if (end == std::string::npos || start == std::string::npos) {
2279 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2280 return false;
2281 }
2282
2283 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2284 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2285}
2286
2287bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2288 const char *instruction_set) {
2289 std::string src_ = src;
2290 std::string instruction_set_ = instruction_set;
2291
2292 if (!is_absolute_path(src_)) return false;
2293 if (!is_valid_instruction_set(instruction_set_)) return false;
2294
2295 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2296 if (*it == '/') {
2297 *it = '@';
2298 }
2299 }
2300
2301 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2302 + DALVIK_CACHE_POSTFIX;
2303 const char* res = res_.c_str();
2304 if (strlen(res) >= PKG_PATH_MAX) {
2305 LOG(ERROR) << "Result too large";
2306 return false;
2307 } else {
2308 strlcpy(path, res, PKG_PATH_MAX);
2309 return true;
2310 }
2311}
2312
Calin Juravle29591732017-11-20 17:46:19 -08002313bool snapshot_profile(int32_t app_id, const std::string& package_name,
2314 const std::string& code_path) {
2315 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2316
2317 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, code_path);
2318 if (snapshot_fd < 0) {
2319 return false;
2320 }
2321
2322 std::vector<unique_fd> profiles_fd;
2323 unique_fd reference_profile_fd;
2324 open_profile_files(app_shared_gid, package_name, /*is_secondary_dex*/ false, &profiles_fd,
2325 &reference_profile_fd);
2326 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2327 return false;
2328 }
2329
2330 profiles_fd.push_back(std::move(reference_profile_fd));
2331
2332 pid_t pid = fork();
2333 if (pid == 0) {
2334 /* child -- drop privileges before continuing */
2335 drop_capabilities(app_shared_gid);
2336 run_profman_merge(profiles_fd, snapshot_fd);
2337 exit(42); /* only get here on exec failure */
2338 }
2339
2340 /* parent */
2341 int return_code = wait_child(pid);
2342 if (!WIFEXITED(return_code)) {
2343 LOG(WARNING) << "profman failed for " << package_name << ":" << code_path;
2344 return false;
2345 }
2346
2347 return true;
2348}
2349
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002350} // namespace installd
2351} // namespace android