blob: 9dfbfd3bd089b434fbbb4453f41e908edc9e1c3e [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 */
Alan Stokescb27c342018-04-20 17:09:25 +010016#define LOG_TAG "installd"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
Alan Stokesa25d90c2017-10-16 10:56:00 +010018#include <array>
Jeff Sharkey90aff262016-12-12 14:28:24 -070019#include <fcntl.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070020#include <stdlib.h>
21#include <string.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070022#include <sys/capability.h>
23#include <sys/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070024#include <sys/stat.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070025#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/resource.h>
28#include <sys/wait.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070029#include <unistd.h>
30
Andreas Gampe023b2242018-02-28 16:03:25 -080031#include <iomanip>
32
Alan Stokesa25d90c2017-10-16 10:56:00 +010033#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070035#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070036#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070037#include <android-base/strings.h>
38#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080039#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070040#include <cutils/properties.h>
41#include <cutils/sched_policy.h>
Andreas Gampefa2dadd2018-02-28 19:52:47 -080042#include <dex2oat_return_codes.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070043#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010044#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <private/android_filesystem_config.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070046#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070047#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070048
49#include "dexopt.h"
Andreas Gampefa2dadd2018-02-28 19:52:47 -080050#include "dexopt_return_codes.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060051#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070052#include "installd_deps.h"
53#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070054#include "utils.h"
55
Jeff Sharkey90aff262016-12-12 14:28:24 -070056using android::base::EndsWith;
Alan Stokesa25d90c2017-10-16 10:56:00 +010057using android::base::ReadFully;
58using android::base::StringPrintf;
59using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080060using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070061
62namespace android {
63namespace installd {
64
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070065// Should minidebug info be included in compiled artifacts? Even if this value is
66// "true," usage might still be conditional to other constraints, e.g., system
67// property overrides.
68static constexpr bool kEnableMinidebugInfo = true;
69
70static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
71static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
72static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080073static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070074
Andreas Gampefa2dadd2018-02-28 19:52:47 -080075
Calin Juravle114f0812017-03-08 19:05:07 -080076// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
77struct FreeDelete {
78 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
79 void operator()(const void* ptr) const {
80 free(const_cast<void*>(ptr));
81 }
82};
83
84// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
85template <typename T>
86using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
87
Calin Juravle1a0af3b2017-03-09 14:33:33 -080088static unique_fd invalid_unique_fd() {
89 return unique_fd(-1);
90}
91
Andreas Gampe6a9cf722017-07-24 16:49:10 -070092static bool is_debug_runtime() {
93 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
94}
95
David Sehra3b5ab62017-10-25 14:27:29 -070096static bool is_debuggable_build() {
97 return android::base::GetBoolProperty("ro.debuggable", false);
98}
99
Jeff Sharkey90aff262016-12-12 14:28:24 -0700100static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800101 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700102 if (ufd.get() < 0) {
103 if (errno != ENOENT) {
104 PLOG(WARNING) << "Could not open profile " << profile;
105 return false;
106 } else {
107 // Nothing to clear. That's ok.
108 return true;
109 }
110 }
111
112 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
113 if (errno != EWOULDBLOCK) {
114 PLOG(WARNING) << "Error locking profile " << profile;
115 }
116 // This implies that the app owning this profile is running
117 // (and has acquired the lock).
118 //
119 // If we can't acquire the lock bail out since clearing is useless anyway
120 // (the app will write again to the profile).
121 //
122 // Note:
123 // This does not impact the this is not an issue for the profiling correctness.
124 // In case this is needed because of an app upgrade, profiles will still be
125 // eventually cleared by the app itself due to checksum mismatch.
126 // If this is needed because profman advised, then keeping the data around
127 // until the next run is again not an issue.
128 //
129 // If the app attempts to acquire a lock while we've held one here,
130 // it will simply skip the current write cycle.
131 return false;
132 }
133
134 bool truncated = ftruncate(ufd.get(), 0) == 0;
135 if (!truncated) {
136 PLOG(WARNING) << "Could not truncate " << profile;
137 }
138 if (flock(ufd.get(), LOCK_UN) != 0) {
139 PLOG(WARNING) << "Error unlocking profile " << profile;
140 }
141 return truncated;
142}
143
Calin Juravle114f0812017-03-08 19:05:07 -0800144// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800145// The location is the profile name for primary apks or the dex path for secondary dex files.
146static bool clear_reference_profile(const std::string& package_name, const std::string& location,
147 bool is_secondary_dex) {
148 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700149}
150
Calin Juravle114f0812017-03-08 19:05:07 -0800151// Clear the reference profile for the given location.
Calin Juravle824a64d2018-01-18 20:23:17 -0800152// The location is the profile name for primary apks or the dex path for secondary dex files.
153static bool clear_current_profile(const std::string& package_name, const std::string& location,
154 userid_t user, bool is_secondary_dex) {
155 return clear_profile(create_current_profile_path(user, package_name, location,
156 is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700157}
158
Calin Juravle114f0812017-03-08 19:05:07 -0800159// Clear the reference profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800160// The location is the profile name for primary apks or the dex path for secondary dex files.
161bool clear_primary_reference_profile(const std::string& package_name,
162 const std::string& location) {
163 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800164}
165
166// Clear all current profile for the primary apk of the given package.
Calin Juravle824a64d2018-01-18 20:23:17 -0800167// The location is the profile name for primary apks or the dex path for secondary dex files.
168bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700169 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800170 // 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 -0700171 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
172 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800173 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700174 }
175 return success;
176}
177
Calin Juravle114f0812017-03-08 19:05:07 -0800178// Clear the current profile for the primary apk of the given package and user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800179bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
180 userid_t user) {
181 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800182}
183
Jeff Sharkey90aff262016-12-12 14:28:24 -0700184static int split_count(const char *str)
185{
186 char *ctx;
187 int count = 0;
188 char buf[kPropertyValueMax];
189
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600190 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700191 char *pBuf = buf;
192
193 while(strtok_r(pBuf, " ", &ctx) != NULL) {
194 count++;
195 pBuf = NULL;
196 }
197
198 return count;
199}
200
201static int split(char *buf, const char **argv)
202{
203 char *ctx;
204 int count = 0;
205 char *tok;
206 char *pBuf = buf;
207
208 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
209 argv[count++] = tok;
210 pBuf = NULL;
211 }
212
213 return count;
214}
215
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700216static const char* get_location_from_path(const char* path) {
217 static constexpr char kLocationSeparator = '/';
218 const char *location = strrchr(path, kLocationSeparator);
219 if (location == NULL) {
220 return path;
221 } else {
222 // Skip the separator character.
223 return location + 1;
224 }
225}
226
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800227[[ noreturn ]]
Jeff Sharkey90aff262016-12-12 14:28:24 -0700228static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
229 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100230 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700231 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
Calin Juravle62c5a372018-02-01 17:03:23 +0000232 const char* class_loader_context, int target_sdk_version, bool enable_hidden_api_checks,
Mathieu Chartierf69c2f72018-03-06 13:55:58 -0800233 bool generate_compact_dex, int dex_metadata_fd, const char* compilation_reason) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700234 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
235
236 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800237 LOG(ERROR) << "Instruction set '" << instruction_set << "' longer than max length of "
238 << MAX_INSTRUCTION_SET_LEN;
239 exit(DexoptReturnCodes::kInstructionSetLength);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700240 }
241
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700242 // Get the relative path to the input file.
243 const char* relative_input_file_name = get_location_from_path(input_file_name);
244
Jeff Sharkey90aff262016-12-12 14:28:24 -0700245 char dex2oat_Xms_flag[kPropertyValueMax];
246 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
247
248 char dex2oat_Xmx_flag[kPropertyValueMax];
249 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
250
251 char dex2oat_threads_buf[kPropertyValueMax];
252 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
253 ? "dalvik.vm.dex2oat-threads"
254 : "dalvik.vm.boot-dex2oat-threads",
255 dex2oat_threads_buf,
256 NULL) > 0;
257 char dex2oat_threads_arg[kPropertyValueMax + 2];
258 if (have_dex2oat_threads_flag) {
259 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
260 }
261
262 char dex2oat_isa_features_key[kPropertyKeyMax];
263 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
264 char dex2oat_isa_features[kPropertyValueMax];
265 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
266 dex2oat_isa_features, NULL) > 0;
267
268 char dex2oat_isa_variant_key[kPropertyKeyMax];
269 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
270 char dex2oat_isa_variant[kPropertyValueMax];
271 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
272 dex2oat_isa_variant, NULL) > 0;
273
274 const char *dex2oat_norelocation = "-Xnorelocate";
275 bool have_dex2oat_relocation_skip_flag = false;
276
277 char dex2oat_flags[kPropertyValueMax];
278 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
279 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
280 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
281
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100282 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700283 char vold_decrypt[kPropertyValueMax];
284 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
285 bool skip_compilation = (have_vold_decrypt &&
286 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
287 (strcmp(vold_decrypt, "1") == 0)));
288
289 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
290
291 char app_image_format[kPropertyValueMax];
292 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
293 bool have_app_image_format =
294 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
295 if (have_app_image_format) {
296 sprintf(image_format_arg, "--image-format=%s", app_image_format);
297 }
298
299 char dex2oat_large_app_threshold[kPropertyValueMax];
300 bool have_dex2oat_large_app_threshold =
301 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
302 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
303 if (have_dex2oat_large_app_threshold) {
304 sprintf(dex2oat_large_app_threshold_arg,
305 "--very-large-app-threshold=%s",
306 dex2oat_large_app_threshold);
307 }
308
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700309 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700310 const char* dex2oat_bin = "/system/bin/dex2oat";
Andreas Gampee87fe0a2018-03-01 23:55:53 -0800311 constexpr const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700312 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
Andreas Gampee87fe0a2018-03-01 23:55:53 -0800313 if (access(kDex2oatDebugPath, X_OK) == 0) {
314 dex2oat_bin = kDex2oatDebugPath;
315 }
David Sehra3b5ab62017-10-25 14:27:29 -0700316 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700317
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700318 bool generate_minidebug_info = kEnableMinidebugInfo &&
319 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
320 kMinidebugInfoSystemPropertyDefault);
321
Jeff Sharkey90aff262016-12-12 14:28:24 -0700322 static const char* RUNTIME_ARG = "--runtime-arg";
323
324 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
325
George Burgess IV36cebe772017-01-25 11:52:01 -0800326 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
327 // use arraysize instead.
328 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
329 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
330 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
331 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
332 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
333 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
334 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
335 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
336 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
337 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
338 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
339 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800341 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800343 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700344 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
David Brazdil570d3982018-01-16 20:15:43 +0000345 char target_sdk_version_arg[arraysize("-Xtarget-sdk-version:") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700346 char class_loader_context_arg[class_loader_context_size];
347 if (class_loader_context != nullptr) {
348 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
349 class_loader_context);
350 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700351
352 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700353 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700354 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
355 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
356 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
357 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
358 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
359 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
360 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
361 if (swap_fd >= 0) {
362 have_dex2oat_swap_fd = true;
363 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
364 }
365 if (image_fd >= 0) {
366 have_dex2oat_image_fd = true;
367 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
368 }
369
370 if (have_dex2oat_Xms_flag) {
371 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
372 }
373 if (have_dex2oat_Xmx_flag) {
374 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
375 }
David Brazdil570d3982018-01-16 20:15:43 +0000376 sprintf(target_sdk_version_arg, "-Xtarget-sdk-version:%d", target_sdk_version);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700377
378 // Compute compiler filter.
379
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100380 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700381 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600382 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
383 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700384 have_dex2oat_compiler_filter_flag = true;
385 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100386 } else if (compiler_filter != nullptr) {
387 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700388 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100389 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
390 have_dex2oat_compiler_filter_flag = true;
391 } else {
392 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
393 compiler_filter,
394 kPropertyValueMax);
395 }
396 }
397
398 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700399 char dex2oat_compiler_filter_flag[kPropertyValueMax];
400 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
401 dex2oat_compiler_filter_flag, NULL) > 0;
402 if (have_dex2oat_compiler_filter_flag) {
403 sprintf(dex2oat_compiler_filter_arg,
404 "--compiler-filter=%s",
405 dex2oat_compiler_filter_flag);
406 }
407 }
408
409 // Check whether all apps should be compiled debuggable.
410 if (!debuggable) {
411 char prop_buf[kPropertyValueMax];
412 debuggable =
413 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
414 (prop_buf[0] == '1');
415 }
416 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
417 if (profile_fd != -1) {
418 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
419 }
420
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700421 // Get the directory of the apk to pass as a base classpath directory.
422 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
423 std::string apk_dir(input_file_name);
424 unsigned long dir_index = apk_dir.rfind('/');
425 bool has_base_dir = dir_index != std::string::npos;
426 if (has_base_dir) {
427 apk_dir = apk_dir.substr(0, dir_index);
428 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
429 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700430
Calin Juravle62c5a372018-02-01 17:03:23 +0000431 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700432
Calin Juravle2efc4022018-02-13 18:31:32 -0800433 std::string compilation_reason_arg = compilation_reason == nullptr
434 ? ""
435 : std::string("--compilation-reason=") + compilation_reason;
436
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700437 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700438
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800439 // Disable cdex if update input vdex is true since this combination of options is not
440 // supported.
Mathieu Chartierf69c2f72018-03-06 13:55:58 -0800441 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800442
Jeff Sharkey90aff262016-12-12 14:28:24 -0700443 const char* argv[9 // program name, mandatory arguments and the final NULL
444 + (have_dex2oat_isa_variant ? 1 : 0)
445 + (have_dex2oat_isa_features ? 1 : 0)
446 + (have_dex2oat_Xms_flag ? 2 : 0)
447 + (have_dex2oat_Xmx_flag ? 2 : 0)
448 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
449 + (have_dex2oat_threads_flag ? 1 : 0)
450 + (have_dex2oat_swap_fd ? 1 : 0)
451 + (have_dex2oat_image_fd ? 1 : 0)
452 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
453 + (generate_debug_info ? 1 : 0)
454 + (debuggable ? 1 : 0)
455 + (have_app_image_format ? 1 : 0)
456 + dex2oat_flags_count
457 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700458 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700459 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700460 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800461 + (disable_cdex ? 1 : 0)
David Brazdil570d3982018-01-16 20:15:43 +0000462 + (generate_minidebug_info ? 1 : 0)
David Brazdil7fcbb812018-01-17 17:05:40 +0000463 + (target_sdk_version != 0 ? 2 : 0)
Calin Juravle62c5a372018-02-01 17:03:23 +0000464 + (enable_hidden_api_checks ? 2 : 0)
Calin Juravle2efc4022018-02-13 18:31:32 -0800465 + (dex_metadata_fd > -1 ? 1 : 0)
466 + (compilation_reason != nullptr ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700467 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700468 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700469 argv[i++] = zip_fd_arg;
470 argv[i++] = zip_location_arg;
471 argv[i++] = input_vdex_fd_arg;
472 argv[i++] = output_vdex_fd_arg;
473 argv[i++] = oat_fd_arg;
474 argv[i++] = oat_location_arg;
475 argv[i++] = instruction_set_arg;
476 if (have_dex2oat_isa_variant) {
477 argv[i++] = instruction_set_variant_arg;
478 }
479 if (have_dex2oat_isa_features) {
480 argv[i++] = instruction_set_features_arg;
481 }
482 if (have_dex2oat_Xms_flag) {
483 argv[i++] = RUNTIME_ARG;
484 argv[i++] = dex2oat_Xms_arg;
485 }
486 if (have_dex2oat_Xmx_flag) {
487 argv[i++] = RUNTIME_ARG;
488 argv[i++] = dex2oat_Xmx_arg;
489 }
490 if (have_dex2oat_compiler_filter_flag) {
491 argv[i++] = dex2oat_compiler_filter_arg;
492 }
493 if (have_dex2oat_threads_flag) {
494 argv[i++] = dex2oat_threads_arg;
495 }
496 if (have_dex2oat_swap_fd) {
497 argv[i++] = dex2oat_swap_fd;
498 }
499 if (have_dex2oat_image_fd) {
500 argv[i++] = dex2oat_image_fd;
501 }
502 if (generate_debug_info) {
503 argv[i++] = "--generate-debug-info";
504 }
505 if (debuggable) {
506 argv[i++] = "--debuggable";
507 }
508 if (have_app_image_format) {
509 argv[i++] = image_format_arg;
510 }
511 if (have_dex2oat_large_app_threshold) {
512 argv[i++] = dex2oat_large_app_threshold_arg;
513 }
514 if (dex2oat_flags_count) {
515 i += split(dex2oat_flags, argv + i);
516 }
517 if (have_dex2oat_relocation_skip_flag) {
518 argv[i++] = RUNTIME_ARG;
519 argv[i++] = dex2oat_norelocation;
520 }
521 if (profile_fd != -1) {
522 argv[i++] = profile_arg;
523 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700524 if (has_base_dir) {
525 argv[i++] = base_dir;
526 }
Calin Juravle52c45822017-07-13 22:50:21 -0700527 if (class_loader_context != nullptr) {
528 argv[i++] = class_loader_context_arg;
529 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700530 if (generate_minidebug_info) {
531 argv[i++] = kMinidebugDex2oatFlag;
532 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800533 if (disable_cdex) {
534 argv[i++] = kDisableCompactDexFlag;
535 }
David Brazdil570d3982018-01-16 20:15:43 +0000536 if (target_sdk_version != 0) {
537 argv[i++] = RUNTIME_ARG;
538 argv[i++] = target_sdk_version_arg;
539 }
David Brazdil52249162018-02-12 18:04:59 -0800540 if (enable_hidden_api_checks) {
David Brazdil7fcbb812018-01-17 17:05:40 +0000541 argv[i++] = RUNTIME_ARG;
David Brazdil52249162018-02-12 18:04:59 -0800542 argv[i++] = "-Xhidden-api-checks";
David Brazdil7fcbb812018-01-17 17:05:40 +0000543 }
Calin Juravle52c45822017-07-13 22:50:21 -0700544
Calin Juravle62c5a372018-02-01 17:03:23 +0000545 if (dex_metadata_fd > -1) {
546 argv[i++] = dex_metadata_fd_arg.c_str();
547 }
Calin Juravle2efc4022018-02-13 18:31:32 -0800548
549 if(compilation_reason != nullptr) {
550 argv[i++] = compilation_reason_arg.c_str();
551 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700552 // Do not add after dex2oat_flags, they should override others for debugging.
553 argv[i] = NULL;
554
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700555 execv(dex2oat_bin, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800556 PLOG(ERROR) << "execv(" << dex2oat_bin << ") failed";
557 exit(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700558}
559
560/*
561 * Whether dexopt should use a swap file when compiling an APK.
562 *
563 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
564 * itself, anyways).
565 *
566 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
567 *
568 * Otherwise, return true if this is a low-mem device.
569 *
570 * Otherwise, return default value.
571 */
572static bool kAlwaysProvideSwapFile = false;
573static bool kDefaultProvideSwapFile = true;
574
575static bool ShouldUseSwapFileForDexopt() {
576 if (kAlwaysProvideSwapFile) {
577 return true;
578 }
579
580 // Check the "override" property. If it exists, return value == "true".
581 char dex2oat_prop_buf[kPropertyValueMax];
582 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
583 if (strcmp(dex2oat_prop_buf, "true") == 0) {
584 return true;
585 } else {
586 return false;
587 }
588 }
589
590 // Shortcut for default value. This is an implementation optimization for the process sketched
591 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
592 // as low-mem is never returning false. The compiler will optimize this away if it can.
593 if (kDefaultProvideSwapFile) {
594 return true;
595 }
596
597 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
598 if (is_low_mem) {
599 return true;
600 }
601
602 // Default value must be false here.
603 return kDefaultProvideSwapFile;
604}
605
Richard Uhler76cc0272016-12-08 10:46:35 +0000606static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700607 if (set_to_bg) {
608 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800609 PLOG(ERROR) << "set_sched_policy failed";
610 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700611 }
612 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800613 PLOG(ERROR) << "setpriority failed";
614 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700615 }
616 }
617}
618
Calin Juravle29591732017-11-20 17:46:19 -0800619static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
620 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800621 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800622 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800623 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800624 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800625 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700626 }
Calin Juravle114f0812017-03-08 19:05:07 -0800627 // Profiles should belong to the app; make sure of that by giving ownership to
628 // the app uid. If we cannot do that, there's no point in returning the fd
629 // since dex2oat/profman will fail with SElinux denials.
630 if (fchown(fd.get(), uid, uid) < 0) {
631 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800632 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800633 }
Calin Juravle29591732017-11-20 17:46:19 -0800634 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800635}
636
Calin Juravle29591732017-11-20 17:46:19 -0800637static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800638 // Do not follow symlinks when opening a profile:
639 // - primary profiles should not contain symlinks in their paths
640 // - secondary dex paths should have been already resolved and validated
641 flags |= O_NOFOLLOW;
642
Calin Juravle29591732017-11-20 17:46:19 -0800643 // Check if we need to create the profile
644 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
645 unique_fd fd;
646 if ((flags & O_CREAT) != 0) {
647 fd = create_profile(uid, profile, flags);
648 } else {
649 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
650 }
651
Calin Juravle114f0812017-03-08 19:05:07 -0800652 if (fd.get() < 0) {
653 if (errno != ENOENT) {
654 // Profiles might be missing for various reasons. For example, in a
655 // multi-user environment, the profile directory for one user can be created
656 // after we start a merge. In this case the current profile for that user
657 // will not be found.
658 // Also, the secondary dex profiles might be deleted by the app at any time,
659 // so we can't we need to prepare if they are missing.
660 PLOG(ERROR) << "Failed to open profile " << profile;
661 }
662 return invalid_unique_fd();
663 }
664
Jeff Sharkey90aff262016-12-12 14:28:24 -0700665 return fd;
666}
667
Calin Juravle824a64d2018-01-18 20:23:17 -0800668static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
669 const std::string& location, bool is_secondary_dex) {
670 std::string profile = create_current_profile_path(user, package_name, location,
671 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800672 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800673}
674
Calin Juravle824a64d2018-01-18 20:23:17 -0800675static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
676 const std::string& location, bool read_write, bool is_secondary_dex) {
677 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800678 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
679}
680
681static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800682 const std::string& location) {
683 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800684 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800685}
686
Calin Juravle824a64d2018-01-18 20:23:17 -0800687static void open_profile_files(uid_t uid, const std::string& package_name,
688 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800689 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800691 *reference_profile_fd = open_reference_profile(uid, package_name, location,
692 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700693
Calin Juravle114f0812017-03-08 19:05:07 -0800694 // For secondary dex files, we don't really need the user but we use it for sanity checks.
695 // Note: the user owning the dex file should be the current user.
696 std::vector<userid_t> users;
697 if (is_secondary_dex){
698 users.push_back(multiuser_get_user_id(uid));
699 } else {
700 users = get_known_users(/*volume_uuid*/ nullptr);
701 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700702 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800703 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
704 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700705 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800706 if (profile_fd.get() >= 0) {
707 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700708 }
709 }
710}
711
712static void drop_capabilities(uid_t uid) {
713 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800714 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
715 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700716 }
717 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800718 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
719 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700720 }
721 // drop capabilities
722 struct __user_cap_header_struct capheader;
723 struct __user_cap_data_struct capdata[2];
724 memset(&capheader, 0, sizeof(capheader));
725 memset(&capdata, 0, sizeof(capdata));
726 capheader.version = _LINUX_CAPABILITY_VERSION_3;
727 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800728 PLOG(ERROR) << "capset failed";
729 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700730 }
731}
732
733static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
734static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
735static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
736static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
737static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
738
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800739[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000740static void run_profman(const std::vector<unique_fd>& profile_fds,
741 const unique_fd& reference_profile_fd,
742 const std::vector<unique_fd>* apk_fds,
Calin Juravle3bbaed22018-04-27 17:50:23 -0700743 const std::vector<std::string>* dex_locations,
Calin Juravlef63d4792018-01-30 17:43:34 +0000744 bool copy_and_update) {
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700745 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700746
Calin Juravlef63d4792018-01-30 17:43:34 +0000747 if (copy_and_update) {
748 CHECK_EQ(1u, profile_fds.size());
749 CHECK(apk_fds != nullptr);
750 CHECK_EQ(1u, apk_fds->size());
751 }
752 std::vector<std::string> profile_args(profile_fds.size());
753 for (size_t k = 0; k < profile_fds.size(); k++) {
754 profile_args[k] = "--profile-file-fd=" + std::to_string(profile_fds[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700755 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800756 std::string reference_profile_arg = "--reference-profile-file-fd="
757 + std::to_string(reference_profile_fd.get());
758
759 std::vector<std::string> apk_args;
760 if (apk_fds != nullptr) {
761 for (size_t k = 0; k < apk_fds->size(); k++) {
762 apk_args.push_back("--apk-fd=" + std::to_string((*apk_fds)[k].get()));
763 }
764 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700765
Calin Juravle3bbaed22018-04-27 17:50:23 -0700766 std::vector<std::string> dex_location_args;
767 if (dex_locations != nullptr) {
768 for (size_t k = 0; k < dex_locations->size(); k++) {
769 dex_location_args.push_back("--dex-location=" + (*dex_locations)[k]);
770 }
771 }
772
Jeff Sharkey90aff262016-12-12 14:28:24 -0700773 // program name, reference profile fd, the final NULL and the profile fds
Calin Juravlea30265a2018-06-11 13:28:15 -0700774 const char* argv[3 + profile_args.size() + apk_args.size()
775 + dex_location_args.size() + (copy_and_update ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700776 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700777 argv[i++] = profman_bin;
Calin Juravle0d0a4922018-01-23 19:54:11 -0800778 argv[i++] = reference_profile_arg.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700779 for (size_t k = 0; k < profile_args.size(); k++) {
780 argv[i++] = profile_args[k].c_str();
781 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800782 for (size_t k = 0; k < apk_args.size(); k++) {
783 argv[i++] = apk_args[k].c_str();
784 }
Calin Juravle3bbaed22018-04-27 17:50:23 -0700785 for (size_t k = 0; k < dex_location_args.size(); k++) {
786 argv[i++] = dex_location_args[k].c_str();
787 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000788 if (copy_and_update) {
789 argv[i++] = "--copy-and-update-profile-key";
790 }
Calin Juravle3bbaed22018-04-27 17:50:23 -0700791
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792 // Do not add after dex2oat_flags, they should override others for debugging.
793 argv[i] = NULL;
794
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700795 execv(profman_bin, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800796 PLOG(ERROR) << "execv(" << profman_bin << ") failed";
797 exit(DexoptReturnCodes::kProfmanExec); /* only get here on exec failure */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700798}
799
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800800[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000801static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
802 const unique_fd& reference_profile_fd,
Calin Juravle3bbaed22018-04-27 17:50:23 -0700803 const std::vector<unique_fd>* apk_fds = nullptr,
804 const std::vector<std::string>* dex_locations = nullptr) {
805 run_profman(profiles_fd, reference_profile_fd, apk_fds, dex_locations,
806 /*copy_and_update*/false);
Calin Juravlef63d4792018-01-30 17:43:34 +0000807}
808
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800809[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000810static void run_profman_copy_and_update(unique_fd&& profile_fd,
811 unique_fd&& reference_profile_fd,
Calin Juravle3bbaed22018-04-27 17:50:23 -0700812 unique_fd&& apk_fd,
813 const std::string& dex_location) {
Calin Juravlef63d4792018-01-30 17:43:34 +0000814 std::vector<unique_fd> profiles_fd;
815 profiles_fd.push_back(std::move(profile_fd));
816 std::vector<unique_fd> apk_fds;
817 apk_fds.push_back(std::move(apk_fd));
Calin Juravle3bbaed22018-04-27 17:50:23 -0700818 std::vector<std::string> dex_locations;
819 dex_locations.push_back(dex_location);
Calin Juravlef63d4792018-01-30 17:43:34 +0000820
Calin Juravle3bbaed22018-04-27 17:50:23 -0700821 run_profman(profiles_fd, reference_profile_fd, &apk_fds, &dex_locations,
822 /*copy_and_update*/true);
Calin Juravlef63d4792018-01-30 17:43:34 +0000823}
824
Jeff Sharkey90aff262016-12-12 14:28:24 -0700825// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800826// The location is the package name for primary apks or the dex path for secondary dex files.
827// Returns true if there is enough information in the current profiles that makes it
828// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700829// If the return value is true all the current profiles would have been merged into
830// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800831static bool analyze_profiles(uid_t uid, const std::string& package_name,
832 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800833 std::vector<unique_fd> profiles_fd;
834 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800835 open_profile_files(uid, package_name, location, is_secondary_dex,
836 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800837 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700838 // Skip profile guided compilation because no profiles were found.
839 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700840 return false;
841 }
842
Jeff Sharkey90aff262016-12-12 14:28:24 -0700843 pid_t pid = fork();
844 if (pid == 0) {
845 /* child -- drop privileges before continuing */
846 drop_capabilities(uid);
847 run_profman_merge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700848 }
849 /* parent */
850 int return_code = wait_child(pid);
851 bool need_to_compile = false;
852 bool should_clear_current_profiles = false;
853 bool should_clear_reference_profile = false;
854 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800855 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856 } else {
857 return_code = WEXITSTATUS(return_code);
858 switch (return_code) {
859 case PROFMAN_BIN_RETURN_CODE_COMPILE:
860 need_to_compile = true;
861 should_clear_current_profiles = true;
862 should_clear_reference_profile = false;
863 break;
864 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
865 need_to_compile = false;
866 should_clear_current_profiles = false;
867 should_clear_reference_profile = false;
868 break;
869 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800870 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 need_to_compile = false;
872 should_clear_current_profiles = true;
873 should_clear_reference_profile = true;
874 break;
875 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
876 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
877 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800878 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879 need_to_compile = false;
880 should_clear_current_profiles = false;
881 should_clear_reference_profile = false;
882 break;
883 default:
884 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800885 LOG(WARNING) << "Unknown error code while processing profiles for location "
886 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700887 need_to_compile = false;
888 should_clear_current_profiles = true;
889 should_clear_reference_profile = true;
890 break;
891 }
892 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800893
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800895 if (is_secondary_dex) {
896 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800897 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
898 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800899 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800900 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800901 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700902 }
903 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800904 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700905 }
906 return need_to_compile;
907}
908
Calin Juravle114f0812017-03-08 19:05:07 -0800909// Decides if profile guided compilation is needed or not based on existing profiles.
910// The analysis is done for the primary apks of the given package.
911// Returns true if there is enough information in the current profiles that makes it
912// worth to recompile the package.
913// If the return value is true all the current profiles would have been merged into
914// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800915bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
916 const std::string& profile_name) {
917 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800918}
919
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800920[[ noreturn ]]
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800921static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
922 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700923 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800924 const std::vector<unique_fd>& apk_fds,
925 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700926 std::vector<std::string> profman_args;
927 static const char* PROFMAN_BIN = "/system/bin/profman";
928 profman_args.push_back(PROFMAN_BIN);
929 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800930 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700931 if (reference_profile_fd != -1) {
932 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800933 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700934 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800935 for (size_t i = 0; i < profile_fds.size(); i++) {
936 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700937 }
938 for (const std::string& dex_location : dex_locations) {
939 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
940 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800941 for (size_t i = 0; i < apk_fds.size(); i++) {
942 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700943 }
944 const char **argv = new const char*[profman_args.size() + 1];
945 size_t i = 0;
946 for (const std::string& profman_arg : profman_args) {
947 argv[i++] = profman_arg.c_str();
948 }
949 argv[i] = NULL;
950
951 execv(PROFMAN_BIN, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800952 PLOG(ERROR) << "execv(" << PROFMAN_BIN << ") failed";
953 exit(DexoptReturnCodes::kProfmanExec); /* only get here on exec failure */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700954}
955
Calin Juravle408cd4a2018-01-20 23:34:18 -0800956bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
957 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800958 std::vector<unique_fd> profile_fds;
959 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800960 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
961 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700962
Calin Juravle408cd4a2018-01-20 23:34:18 -0800963 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800964 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700965
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800966 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967 const bool has_profiles = !profile_fds.empty();
968
969 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800970 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700971 return false;
972 }
973
Calin Juravle114f0812017-03-08 19:05:07 -0800974 unique_fd output_fd(open(out_file_name.c_str(),
975 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700976 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800977 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700978 return false;
979 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800980
Jeff Sharkey90aff262016-12-12 14:28:24 -0700981 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800982 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800983 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
984 if (apk_fd == -1) {
985 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
986 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700987 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800988 dex_locations.push_back(get_location_from_path(code_path.c_str()));
989 apk_fds.push_back(std::move(apk_fd));
990
Jeff Sharkey90aff262016-12-12 14:28:24 -0700991
992 pid_t pid = fork();
993 if (pid == 0) {
994 /* child -- drop privileges before continuing */
995 drop_capabilities(uid);
996 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
997 apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700998 }
999 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001000 int return_code = wait_child(pid);
1001 if (!WIFEXITED(return_code)) {
1002 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1003 << return_code;
1004 return false;
1005 }
1006 return true;
1007}
1008
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001009bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001010 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001011 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1012 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001013 package_name,
1014 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001015 /*read_write*/ true,
1016 /*secondary*/ false));
1017 if (in_fd.get() < 0) {
1018 PLOG(WARNING) << "Could not open profile " << system_profile;
1019 return false;
1020 }
1021 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001022 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001023 return false;
1024 }
1025
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001026 // As a security measure we want to write the profile information with the reduced capabilities
1027 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001028 pid_t pid = fork();
1029 if (pid == 0) {
1030 /* child -- drop privileges before continuing */
1031 drop_capabilities(packageUid);
1032
1033 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1034 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001035 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001036 }
1037 // This implies that the app owning this profile is running
1038 // (and has acquired the lock).
1039 //
1040 // The app never acquires the lock for the reference profiles of primary apks.
1041 // Only dex2oat from installd will do that. Since installd is single threaded
1042 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001043 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001044 return false;
1045 }
1046
1047 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1048 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001049 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001050 }
1051
1052 // Copy over data.
1053 static constexpr size_t kBufferSize = 4 * 1024;
1054 char buffer[kBufferSize];
1055 while (true) {
1056 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1057 if (bytes == 0) {
1058 break;
1059 }
1060 write(out_fd.get(), buffer, bytes);
1061 }
1062 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001063 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001064 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001065 // Use _exit since we don't want to run the global destructors in the child.
1066 // b/62597429
1067 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001068 }
1069 /* parent */
1070 int return_code = wait_child(pid);
1071 return return_code == 0;
1072}
1073
Jeff Sharkey90aff262016-12-12 14:28:24 -07001074static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1075 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1076 if (EndsWith(oat_path, ".dex")) {
1077 std::string new_path = oat_path;
1078 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001079 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001080 return new_path;
1081 }
1082
1083 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1084 // case (where the base name will have an extension for the B artifact).
1085 size_t odex_pos = oat_path.rfind(".odex");
1086 if (odex_pos != std::string::npos) {
1087 std::string new_path = oat_path;
1088 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1089 CHECK_NE(new_path.find(new_ext), std::string::npos);
1090 return new_path;
1091 }
1092
1093 // Don't know how to handle this.
1094 return "";
1095}
1096
1097// Translate the given oat path to an art (app image) path. An empty string
1098// denotes an error.
1099static std::string create_image_filename(const std::string& oat_path) {
1100 return replace_file_extension(oat_path, ".art");
1101}
1102
1103// Translate the given oat path to a vdex path. An empty string denotes an error.
1104static std::string create_vdex_filename(const std::string& oat_path) {
1105 return replace_file_extension(oat_path, ".vdex");
1106}
1107
Jeff Sharkey90aff262016-12-12 14:28:24 -07001108static int open_output_file(const char* file_name, bool recreate, int permissions) {
1109 int flags = O_RDWR | O_CREAT;
1110 if (recreate) {
1111 if (unlink(file_name) < 0) {
1112 if (errno != ENOENT) {
1113 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1114 }
1115 }
1116 flags |= O_EXCL;
1117 }
1118 return open(file_name, flags, permissions);
1119}
1120
Calin Juravle2289c0a2017-02-15 12:44:14 -08001121static bool set_permissions_and_ownership(
1122 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1123 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1124 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001125 if (fchmod(fd,
1126 S_IRUSR|S_IWUSR|S_IRGRP |
1127 (is_public ? S_IROTH : 0)) < 0) {
1128 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1129 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001130 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001131 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1132 return false;
1133 }
1134 return true;
1135}
1136
1137static bool IsOutputDalvikCache(const char* oat_dir) {
1138 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1139 // into '!'. Play it safe by handling it both.
1140 // TODO: ensure we never get null.
1141 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1142 return oat_dir == nullptr || oat_dir[0] == '!';
1143}
1144
Calin Juravled23dee72017-07-06 16:29:11 -07001145// Best-effort check whether we can fit the the path into our buffers.
1146// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1147// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1148// extension to the cache path (5 bytes).
1149// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1150static bool validate_dex_path_size(const std::string& dex_path) {
1151 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1152 LOG(ERROR) << "dex_path too long: " << dex_path;
1153 return false;
1154 }
1155 return true;
1156}
1157
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001159 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001160 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001161 return false;
1162 }
1163
1164 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001165 // Oat dirs for secondary dex files are already validated.
1166 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001167 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1168 return false;
1169 }
1170 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1171 return false;
1172 }
1173 } else {
1174 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1175 return false;
1176 }
1177 }
1178 return true;
1179}
1180
1181// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1182// on destruction. It will also run the given cleanup (unless told not to) after closing.
1183//
1184// Usage example:
1185//
Calin Juravle7a570e82017-01-14 16:23:30 -08001186// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001187// [name]() {
1188// unlink(name.c_str());
1189// });
1190// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1191// wrapper if captured as a reference.
1192//
1193// if (file.get() == -1) {
1194// // Error opening...
1195// }
1196//
1197// ...
1198// if (error) {
1199// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1200// // and delete the file (after the fd is closed).
1201// return -1;
1202// }
1203//
1204// (Success case)
1205// file.SetCleanup(false);
1206// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1207// // (leaving the file around; after the fd is closed).
1208//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001209class Dex2oatFileWrapper {
1210 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001211 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001212 }
1213
Calin Juravle7a570e82017-01-14 16:23:30 -08001214 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1215 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1216
1217 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1218 value_ = other.value_;
1219 cleanup_ = other.cleanup_;
1220 do_cleanup_ = other.do_cleanup_;
1221 auto_close_ = other.auto_close_;
1222 other.release();
1223 }
1224
1225 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1226 value_ = other.value_;
1227 cleanup_ = other.cleanup_;
1228 do_cleanup_ = other.do_cleanup_;
1229 auto_close_ = other.auto_close_;
1230 other.release();
1231 return *this;
1232 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001233
1234 ~Dex2oatFileWrapper() {
1235 reset(-1);
1236 }
1237
1238 int get() {
1239 return value_;
1240 }
1241
1242 void SetCleanup(bool cleanup) {
1243 do_cleanup_ = cleanup;
1244 }
1245
1246 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001247 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001248 close(value_);
1249 }
1250 if (do_cleanup_ && cleanup_ != nullptr) {
1251 cleanup_();
1252 }
1253
1254 value_ = new_value;
1255 }
1256
Calin Juravle7a570e82017-01-14 16:23:30 -08001257 void reset(int new_value, std::function<void ()> new_cleanup) {
1258 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001259 close(value_);
1260 }
1261 if (do_cleanup_ && cleanup_ != nullptr) {
1262 cleanup_();
1263 }
1264
1265 value_ = new_value;
1266 cleanup_ = new_cleanup;
1267 }
1268
Calin Juravle7a570e82017-01-14 16:23:30 -08001269 void DisableAutoClose() {
1270 auto_close_ = false;
1271 }
1272
Jeff Sharkey90aff262016-12-12 14:28:24 -07001273 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001274 void release() {
1275 value_ = -1;
1276 do_cleanup_ = false;
1277 cleanup_ = nullptr;
1278 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001279 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001280 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001281 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001282 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001283};
1284
Calin Juravle7a570e82017-01-14 16:23:30 -08001285// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001286Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1287 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001288
1289 // We don't create an image for secondary dex files.
1290 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001291 return Dex2oatFileWrapper();
1292 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001293
Calin Juravle7a570e82017-01-14 16:23:30 -08001294 const std::string image_path = create_image_filename(out_oat_path);
1295 if (image_path.empty()) {
1296 // Happens when the out_oat_path has an unknown extension.
1297 return Dex2oatFileWrapper();
1298 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001299
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001300 // In case there is a stale image, remove it now. Ignore any error.
1301 unlink(image_path.c_str());
1302
1303 // Not enabled, exit.
1304 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001305 return Dex2oatFileWrapper();
1306 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001307 char app_image_format[kPropertyValueMax];
1308 bool have_app_image_format =
1309 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1310 if (!have_app_image_format) {
1311 return Dex2oatFileWrapper();
1312 }
1313 // Recreate is true since we do not want to modify a mapped image. If the app is
1314 // already running and we modify the image file, it can cause crashes (b/27493510).
1315 Dex2oatFileWrapper wrapper_fd(
1316 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1317 [image_path]() { unlink(image_path.c_str()); });
1318 if (wrapper_fd.get() < 0) {
1319 // Could not create application image file. Go on since we can compile without it.
1320 LOG(ERROR) << "installd could not create '" << image_path
1321 << "' for image file during dexopt";
1322 // If we have a valid image file path but no image fd, explicitly erase the image file.
1323 if (unlink(image_path.c_str()) < 0) {
1324 if (errno != ENOENT) {
1325 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1326 }
1327 }
1328 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001329 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001330 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1331 wrapper_fd.reset(-1);
1332 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001333
Calin Juravle7a570e82017-01-14 16:23:30 -08001334 return wrapper_fd;
1335}
1336
1337// Creates the dexopt swap file if necessary and return its fd.
1338// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001339unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001340 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001341 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001342 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001343 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001344 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001345 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001346 if (swap_fd.get() < 0) {
1347 // Could not create swap file. Optimistically go on and hope that we can compile
1348 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001349 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001350 } else {
1351 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001352 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001353 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1354 }
1355 }
1356 return swap_fd;
1357}
1358
1359// Opens the reference profiles if needed.
1360// 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 -08001361Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001362 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001363 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001364 // If we are not profile guided compilation, or we are compiling system server
1365 // do not bother to open the profiles; we won't be using them.
1366 if (!profile_guided || (pkgname[0] == '*')) {
1367 return Dex2oatFileWrapper();
1368 }
1369
1370 // If this is a secondary dex path which is public do not open the profile.
1371 // We cannot compile public secondary dex paths with profiles. That's because
1372 // it will expose how the dex files are used by their owner.
1373 //
1374 // Note that the PackageManager is responsible to set the is_public flag for
1375 // primary apks and we do not check it here. In some cases, e.g. when
1376 // compiling with a public profile from the .dm file the PackageManager will
1377 // set is_public toghether with the profile guided compilation.
1378 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001379 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001380 }
Calin Juravle114f0812017-03-08 19:05:07 -08001381
1382 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001383 std::string location;
1384 if (is_secondary_dex) {
1385 location = dex_path;
1386 } else {
1387 if (profile_name == nullptr) {
1388 // This path is taken for system server re-compilation lunched from ZygoteInit.
1389 return Dex2oatFileWrapper();
1390 } else {
1391 location = profile_name;
1392 }
1393 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001394 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1395 is_secondary_dex);
1396 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1397 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001398 };
1399 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001400}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001401
Calin Juravle7a570e82017-01-14 16:23:30 -08001402// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1403// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001404bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001405 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001406 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001407 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1408 CHECK(in_vdex_wrapper_fd != nullptr);
1409 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001410 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1411 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001412 char in_odex_path[PKG_PATH_MAX];
1413 int dexopt_action = abs(dexopt_needed);
1414 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001415 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001416
1417 // Infer the name of the output VDEX.
1418 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1419 if (out_vdex_path_str.empty()) {
1420 return false;
1421 }
1422
1423 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001424 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001425 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1426 const char* path = nullptr;
1427 if (is_odex_location) {
1428 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1429 path = in_odex_path;
1430 } else {
1431 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001432 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001433 }
1434 } else {
1435 path = out_oat_path;
1436 }
1437 in_vdex_path_str = create_vdex_filename(path);
1438 if (in_vdex_path_str.empty()) {
1439 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001440 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001441 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001442 // We can update in place when all these conditions are met:
1443 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1444 // on /system typically cannot be updated in place).
1445 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1446 // cannot be currently used by a running process.
1447 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1448 // different vdex files to operate.
1449 update_vdex_in_place =
1450 (in_vdex_path_str == out_vdex_path_str) &&
1451 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1452 !profile_guided;
1453 if (update_vdex_in_place) {
1454 // Open the file read-write to be able to update it.
1455 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1456 if (in_vdex_wrapper_fd->get() == -1) {
1457 // If we failed to open the file, we cannot update it in place.
1458 update_vdex_in_place = false;
1459 }
1460 } else {
1461 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1462 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001463 }
1464
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001465 // If we are updating the vdex in place, we do not need to recreate a vdex,
1466 // and can use the same existing one.
1467 if (update_vdex_in_place) {
1468 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1469 // have bogus stale vdex files.
1470 out_vdex_wrapper_fd->reset(
1471 in_vdex_wrapper_fd->get(),
1472 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1473 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1474 // wrapper).
1475 in_vdex_wrapper_fd->DisableAutoClose();
1476 } else {
1477 out_vdex_wrapper_fd->reset(
1478 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1479 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1480 if (out_vdex_wrapper_fd->get() < 0) {
1481 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1482 return false;
1483 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001484 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001485 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001486 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001487 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1488 return false;
1489 }
1490
1491 // If we got here we successfully opened the vdex files.
1492 return true;
1493}
1494
1495// Opens the output oat file for the given apk.
1496// If successful it stores the output path into out_oat_path and returns true.
1497Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001498 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1499 char* out_oat_path) {
1500 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001501 return Dex2oatFileWrapper();
1502 }
1503 const std::string out_oat_path_str(out_oat_path);
1504 Dex2oatFileWrapper wrapper_fd(
1505 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1506 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1507 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001508 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001509 } else if (!set_permissions_and_ownership(
1510 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001511 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1512 wrapper_fd.reset(-1);
1513 }
1514 return wrapper_fd;
1515}
1516
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001517// Creates RDONLY fds for oat and vdex files, if exist.
1518// Returns false if it fails to create oat out path for the given apk path.
1519// Note that the method returns true even if the files could not be opened.
1520bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1521 const std::string& oat_dir,
1522 const std::string& instruction_set,
1523 bool is_secondary_dex,
1524 unique_fd* oat_file_fd,
1525 unique_fd* vdex_file_fd) {
1526 char oat_path[PKG_PATH_MAX];
1527 if (!create_oat_out_path(apk_path.c_str(),
1528 instruction_set.c_str(),
1529 oat_dir.c_str(),
1530 is_secondary_dex,
1531 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001532 LOG(ERROR) << "Could not create oat out path for "
1533 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001534 return false;
1535 }
1536 oat_file_fd->reset(open(oat_path, O_RDONLY));
1537 if (oat_file_fd->get() < 0) {
1538 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1539 }
1540
1541 std::string vdex_filename = create_vdex_filename(oat_path);
1542 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1543 if (vdex_file_fd->get() < 0) {
1544 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1545 }
1546
1547 return true;
1548}
1549
Calin Juravle7a570e82017-01-14 16:23:30 -08001550// Updates the access times of out_oat_path based on those from apk_path.
1551void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1552 struct stat input_stat;
1553 memset(&input_stat, 0, sizeof(input_stat));
1554 if (stat(apk_path, &input_stat) != 0) {
1555 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1556 return;
1557 }
1558
1559 struct utimbuf ut;
1560 ut.actime = input_stat.st_atime;
1561 ut.modtime = input_stat.st_mtime;
1562 if (utime(out_oat_path, &ut) != 0) {
1563 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1564 }
1565}
1566
Calin Juravle80a21252017-01-17 14:43:25 -08001567// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001568// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1569// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1570// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001571static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1572 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1573 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001574 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001575 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001576 const char* dexoptanalyzer_bin =
1577 is_debug_runtime()
1578 ? "/system/bin/dexoptanalyzerd"
1579 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001580 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1581
Calin Juravled23dee72017-07-06 16:29:11 -07001582 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1583 LOG(ERROR) << "Instruction set " << instruction_set
1584 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001585 return;
1586 }
1587
Calin Juravled23dee72017-07-06 16:29:11 -07001588 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001589 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1590 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1591 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001592 std::string isa_arg = "--isa=" + instruction_set;
1593 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001594 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001595 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001596 std::string class_loader_context_arg = "--class-loader-context=";
1597 if (class_loader_context != nullptr) {
1598 class_loader_context_arg += class_loader_context;
1599 }
Calin Juravle80a21252017-01-17 14:43:25 -08001600
Calin Juravle80a21252017-01-17 14:43:25 -08001601 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001602 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001603 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001604 (vdex_fd >= 0 ? 1 : 0) +
1605 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001606 (downgrade ? 1 : 0) +
1607 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001608 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001609 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001610 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001611 argv[i++] = dex_file_arg.c_str();
1612 argv[i++] = isa_arg.c_str();
1613 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001614 if (oat_fd >= 0) {
1615 argv[i++] = oat_fd_arg.c_str();
1616 }
1617 if (vdex_fd >= 0) {
1618 argv[i++] = vdex_fd_arg.c_str();
1619 }
1620 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001621 if (profile_was_updated) {
1622 argv[i++] = assume_profile_changed;
1623 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001624 if (downgrade) {
1625 argv[i++] = downgrade_flag;
1626 }
Calin Juravle58cab072017-09-12 01:02:26 -07001627 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001628 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001629 }
Calin Juravle80a21252017-01-17 14:43:25 -08001630 argv[i] = NULL;
1631
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001632 execv(dexoptanalyzer_bin, (char * const *)argv);
1633 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001634}
1635
1636// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001637static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001638 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001639 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001640 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001641 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001642 return false;
1643 }
Calin Juravle114f0812017-03-08 19:05:07 -08001644 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001645
Calin Juravle80a21252017-01-17 14:43:25 -08001646 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001647 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1648 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001649 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001650 return false;
1651 }
1652
1653 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001654 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001655
Calin Juravle7d765462017-09-04 15:57:10 -07001656 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001657 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001658 return false;
1659 }
1660
1661 return true;
1662}
1663
Calin Juravle7d765462017-09-04 15:57:10 -07001664// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1665// secondary dex files. This return codes are returned by the child process created for
1666// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001667
Andreas Gampe194fe422018-02-28 20:16:19 -08001668enum DexoptAnalyzerSkipCodes {
1669 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001670 // Specific errors are encoded in the name.
1671 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1672 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1673 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1674 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1675 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001676 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001677 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001678};
Calin Juravle7d765462017-09-04 15:57:10 -07001679
1680// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001681// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1682// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001683// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1684// of dexoptanalyzer.
1685static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001686 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001687 // The result values are defined in dexoptanalyzer.
1688 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001689 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001690 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001691 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001692 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001693 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001694 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001695 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001696 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001697 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001698 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001699 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1700 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1701 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Andreas Gampe194fe422018-02-28 20:16:19 -08001702 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1703 " Expected odex file status for secondary dex %s"
1704 " : dexoptanalyzer result=%d",
1705 dex_path.c_str(),
1706 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001707 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001708 }
1709
1710 // Use a second switch for enum switch-case analysis.
1711 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001712 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001713 // If the file does not exist there's no need for dexopt.
1714 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1715 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001716
1717 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1718 *error_msg = "Dexoptanalyzer path validation failed";
1719 return false;
1720 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1721 *error_msg = "Dexoptanalyzer open zip failed";
1722 return false;
1723 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1724 *error_msg = "Dexoptanalyzer dir preparation failed";
1725 return false;
1726 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1727 *error_msg = "Dexoptanalyzer open output failed";
1728 return false;
1729 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1730 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001731 return false;
1732 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001733
1734 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1735 dex_path.c_str(),
1736 result);
1737 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001738}
1739
Calin Juravle7d765462017-09-04 15:57:10 -07001740enum SecondaryDexAccess {
1741 kSecondaryDexAccessReadOk = 0,
1742 kSecondaryDexAccessDoesNotExist = 1,
1743 kSecondaryDexAccessPermissionError = 2,
1744 kSecondaryDexAccessIOError = 3
1745};
1746
1747static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1748 // Check if the path exists and can be read. If not, there's nothing to do.
1749 if (access(dex_path.c_str(), R_OK) == 0) {
1750 return kSecondaryDexAccessReadOk;
1751 } else {
1752 if (errno == ENOENT) {
1753 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1754 return kSecondaryDexAccessDoesNotExist;
1755 } else {
1756 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1757 return errno == EACCES
1758 ? kSecondaryDexAccessPermissionError
1759 : kSecondaryDexAccessIOError;
1760 }
1761 }
1762}
1763
1764static bool is_file_public(const std::string& filename) {
1765 struct stat file_stat;
1766 if (stat(filename.c_str(), &file_stat) == 0) {
1767 return (file_stat.st_mode & S_IROTH) != 0;
1768 }
1769 return false;
1770}
1771
1772// Create the oat file structure for the secondary dex 'dex_path' and assign
1773// the individual path component to the 'out_' parameters.
1774static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001775 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001776 size_t dirIndex = dex_path.rfind('/');
1777 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001778 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001779 return false;
1780 }
1781 // TODO(calin): we have similar computations in at lest 3 other places
1782 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1783 // using string append.
1784 std::string apk_dir = dex_path.substr(0, dirIndex);
1785 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1786 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1787
1788 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1789 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001790 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001791 return false;
1792 }
1793 return true;
1794}
1795
1796// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1797// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001798static bool validate_dexopt_storage_flags(int dexopt_flags,
1799 int* out_storage_flag,
1800 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001801 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1802 *out_storage_flag = FLAG_STORAGE_CE;
1803 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001804 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001805 return false;
1806 }
1807 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1808 *out_storage_flag = FLAG_STORAGE_DE;
1809 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001810 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001811 return false;
1812 }
1813 return true;
1814}
1815
Calin Juravlec9eab382017-01-25 01:17:17 -08001816// 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 -08001817// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1818// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001819// When returning true, the output parameters will be:
1820// - is_public_out: whether or not the oat file should not be made public
1821// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1822// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001823static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001824 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001825 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001826 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1827 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001828 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001829 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001830 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1831 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001832 return false;
1833 }
Calin Juravle7d765462017-09-04 15:57:10 -07001834 // Compute the oat dir as it's not easy to extract it from the child computation.
1835 char oat_path[PKG_PATH_MAX];
1836 char oat_dir[PKG_PATH_MAX];
1837 char oat_isa_dir[PKG_PATH_MAX];
1838 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001839 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1840 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001841 return false;
1842 }
Calin Juravle7d765462017-09-04 15:57:10 -07001843 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001844
Calin Juravle80a21252017-01-17 14:43:25 -08001845 pid_t pid = fork();
1846 if (pid == 0) {
1847 // child -- drop privileges before continuing.
1848 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001849
1850 // Validate the path structure.
1851 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1852 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001853 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001854 }
1855
1856 // Open the dex file.
1857 unique_fd zip_fd;
1858 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1859 if (zip_fd.get() < 0) {
1860 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001861 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001862 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001863 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001864 }
1865 }
1866
1867 // Prepare the oat directories.
1868 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001869 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001870 }
1871
1872 // Open the vdex/oat files if any.
1873 unique_fd oat_file_fd;
1874 unique_fd vdex_file_fd;
1875 if (!maybe_open_oat_and_vdex_file(dex_path,
1876 *oat_dir_out,
1877 instruction_set,
1878 true /* is_secondary_dex */,
1879 &oat_file_fd,
1880 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001881 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001882 }
1883
1884 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001885 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1886 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001887
1888 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001889 exec_dexoptanalyzer(dex_path,
1890 vdex_file_fd.get(),
1891 oat_file_fd.get(),
1892 zip_fd.get(),
1893 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001894 compiler_filter, profile_was_updated,
1895 downgrade,
1896 class_loader_context);
1897 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001898 _exit(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001899 }
1900
1901 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001902 int result = wait_child(pid);
1903 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001904 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1905 dex_path.c_str(),
1906 result);
1907 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001908 return false;
1909 }
1910 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001911 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001912 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1913 result,
1914 dexopt_needed_out,
1915 error_msg);
1916 if (!success) {
1917 LOG(ERROR) << *error_msg;
1918 }
Calin Juravle7d765462017-09-04 15:57:10 -07001919
1920 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1921
Calin Juravle80a21252017-01-17 14:43:25 -08001922 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001923 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1924 // makes the code simpler; force compilation is only needed during tests).
1925 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001926 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001927 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001928 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1929 }
1930
Calin Juravle7d765462017-09-04 15:57:10 -07001931 // Check if we should make the oat file public.
1932 // Note that if the dex file is not public the compiled code cannot be made public.
1933 // It is ok to check this flag outside in the parent process.
1934 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1935
Calin Juravle80a21252017-01-17 14:43:25 -08001936 return success;
1937}
1938
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001939static std::string format_dexopt_error(int status, const char* dex_path) {
1940 if (WIFEXITED(status)) {
1941 int int_code = WEXITSTATUS(status);
1942 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1943 if (code_name != nullptr) {
1944 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1945 }
1946 }
1947 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001948}
1949
Calin Juravlec9eab382017-01-25 01:17:17 -08001950int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001951 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001952 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001953 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001954 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001955 CHECK(pkgname != nullptr);
1956 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001957 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001958 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1959 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001960
Calin Juravled23dee72017-07-06 16:29:11 -07001961 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001962 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001963 return -1;
1964 }
1965
1966 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001967 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1968 class_loader_context);
1969 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001970 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001971 }
1972
Calin Juravleebc8a792017-04-04 20:21:05 -07001973 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001974 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1975 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1976 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001977 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001978 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001979 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001980 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001981 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001982
1983 // Check if we're dealing with a secondary dex file and if we need to compile it.
1984 std::string oat_dir_str;
1985 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001986 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001987 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001988 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001989 oat_dir = oat_dir_str.c_str();
1990 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1991 return 0; // Nothing to do, report success.
1992 }
1993 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001994 if (error_msg->empty()) { // TODO: Make this a CHECK.
1995 *error_msg = "Failed processing secondary.";
1996 }
Calin Juravle80a21252017-01-17 14:43:25 -08001997 return -1; // We had an error, logged in the process method.
1998 }
1999 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08002000 // Currently these flags are only use for secondary dex files.
2001 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002002 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2003 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2004 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002005
2006 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002007 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002008 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002009 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2010 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002011 return -1;
2012 }
2013
2014 // Create the output OAT file.
2015 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002016 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002017 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002018 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002019 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002020 return -1;
2021 }
2022
2023 // Open vdex files.
2024 Dex2oatFileWrapper in_vdex_fd;
2025 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002026 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2027 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002028 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002029 return -1;
2030 }
2031
Calin Juravlecb556e32017-04-04 20:22:50 -07002032 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2033 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2034 // fully inherit their parent context).
2035 // Note that for primary apk the oat files are created before, in a separate installd
2036 // call which also does the restorecon. TODO(calin): unify the paths.
2037 if (is_secondary_dex) {
2038 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2039 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002040 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2041 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002042 return -1;
2043 }
2044 }
2045
Jeff Sharkey90aff262016-12-12 14:28:24 -07002046 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002047 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002048
Calin Juravle7a570e82017-01-14 16:23:30 -08002049 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002050 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2051 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002052
Calin Juravle7a570e82017-01-14 16:23:30 -08002053 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002054 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002055 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002056
Calin Juravle62c5a372018-02-01 17:03:23 +00002057 unique_fd dex_metadata_fd;
2058 if (dex_metadata_path != nullptr) {
2059 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2060 if (dex_metadata_fd.get() < 0) {
2061 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2062 }
2063 }
2064
Andreas Gampe023b2242018-02-28 16:03:25 -08002065 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002066
2067 pid_t pid = fork();
2068 if (pid == 0) {
2069 /* child -- drop privileges before continuing */
2070 drop_capabilities(uid);
2071
Richard Uhler76cc0272016-12-08 10:46:35 +00002072 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002073 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002074 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002075 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002076 }
2077
Richard Uhler76cc0272016-12-08 10:46:35 +00002078 run_dex2oat(input_fd.get(),
2079 out_oat_fd.get(),
2080 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08002081 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00002082 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07002083 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00002084 out_oat_path,
2085 swap_fd.get(),
2086 instruction_set,
2087 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00002088 debuggable,
2089 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002090 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00002091 reference_profile_fd.get(),
David Brazdil570d3982018-01-16 20:15:43 +00002092 class_loader_context,
David Brazdil7fcbb812018-01-17 17:05:40 +00002093 target_sdk_version,
Calin Juravle62c5a372018-02-01 17:03:23 +00002094 enable_hidden_api_checks,
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002095 generate_compact_dex,
Calin Juravle2efc4022018-02-13 18:31:32 -08002096 dex_metadata_fd.get(),
2097 compilation_reason);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002098 } else {
2099 int res = wait_child(pid);
2100 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002101 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002102 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002103 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2104 << std::hex << std::setw(4) << res << ", process failed";
2105 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002106 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002107 }
2108 }
2109
Calin Juravlec9eab382017-01-25 01:17:17 -08002110 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002111
2112 // We've been successful, don't delete output.
2113 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002114 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002115 image_fd.SetCleanup(false);
2116 reference_profile_fd.SetCleanup(false);
2117
2118 return 0;
2119}
2120
Calin Juravlec9eab382017-01-25 01:17:17 -08002121// Try to remove the given directory. Log an error if the directory exists
2122// and is empty but could not be removed.
2123static bool rmdir_if_empty(const char* dir) {
2124 if (rmdir(dir) == 0) {
2125 return true;
2126 }
2127 if (errno == ENOENT || errno == ENOTEMPTY) {
2128 return true;
2129 }
2130 PLOG(ERROR) << "Failed to remove dir: " << dir;
2131 return false;
2132}
2133
2134// Try to unlink the given file. Log an error if the file exists and could not
2135// be unlinked.
2136static bool unlink_if_exists(const std::string& file) {
2137 if (unlink(file.c_str()) == 0) {
2138 return true;
2139 }
2140 if (errno == ENOENT) {
2141 return true;
2142
2143 }
2144 PLOG(ERROR) << "Could not unlink: " << file;
2145 return false;
2146}
2147
Calin Juravle7d765462017-09-04 15:57:10 -07002148enum ReconcileSecondaryDexResult {
2149 kReconcileSecondaryDexExists = 0,
2150 kReconcileSecondaryDexCleanedUp = 1,
2151 kReconcileSecondaryDexValidationError = 2,
2152 kReconcileSecondaryDexCleanUpError = 3,
2153 kReconcileSecondaryDexAccessIOError = 4,
2154};
Calin Juravlec9eab382017-01-25 01:17:17 -08002155
2156// Reconcile the secondary dex 'dex_path' and its generated oat files.
2157// Return true if all the parameters are valid and the secondary dex file was
2158// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2159// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2160// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2161// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2162// Return false if there were errors during processing. In this case
2163// out_secondary_dex_exists will be set to false.
2164bool reconcile_secondary_dex_file(const std::string& dex_path,
2165 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2166 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2167 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002168 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002169 if (isas.size() == 0) {
2170 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2171 return false;
2172 }
2173
Calin Juravle7d765462017-09-04 15:57:10 -07002174 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2175 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2176 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002177 return false;
2178 }
2179
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002180 // As a security measure we want to unlink art artifacts with the reduced capabilities
2181 // of the package user id. So we fork and drop capabilities in the child.
2182 pid_t pid = fork();
2183 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002184 /* child -- drop privileges before continuing */
2185 drop_capabilities(uid);
2186
2187 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2188 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2189 uid, storage_flag)) {
2190 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2191 _exit(kReconcileSecondaryDexValidationError);
2192 }
2193
2194 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2195 switch (access_check) {
2196 case kSecondaryDexAccessDoesNotExist:
2197 // File does not exist. Proceed with cleaning.
2198 break;
2199 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2200 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2201 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2202 default:
2203 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2204 _exit(kReconcileSecondaryDexValidationError);
2205 }
2206
2207 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002208 char oat_path[PKG_PATH_MAX];
2209 char oat_dir[PKG_PATH_MAX];
2210 char oat_isa_dir[PKG_PATH_MAX];
2211 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002212 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002213 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002214 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002215 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2216 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002217 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002218 }
Calin Juravle51314092017-05-18 15:33:05 -07002219
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002220 // Delete oat/vdex/art files.
2221 result = unlink_if_exists(oat_path) && result;
2222 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2223 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002224
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002225 // Delete profiles.
2226 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002227 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002228 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002229 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002230 result = unlink_if_exists(current_profile) && result;
2231 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002232
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002233 // We upgraded once the location of current profile for secondary dex files.
2234 // Check for any previous left-overs and remove them as well.
2235 std::string old_current_profile = dex_path + ".prof";
2236 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002237
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002238 // Try removing the directories as well, they might be empty.
2239 result = rmdir_if_empty(oat_isa_dir) && result;
2240 result = rmdir_if_empty(oat_dir) && result;
2241 }
Calin Juravle7d765462017-09-04 15:57:10 -07002242 if (!result) {
2243 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2244 }
2245 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002246 }
2247
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002248 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002249 if (!WIFEXITED(return_code)) {
2250 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2251 } else {
2252 return_code = WEXITSTATUS(return_code);
2253 }
2254
2255 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2256
2257 switch (return_code) {
2258 case kReconcileSecondaryDexCleanedUp:
2259 case kReconcileSecondaryDexValidationError:
2260 // If we couldn't validate assume the dex file does not exist.
2261 // This will purge the entry from the PM records.
2262 *out_secondary_dex_exists = false;
2263 return true;
2264 case kReconcileSecondaryDexExists:
2265 *out_secondary_dex_exists = true;
2266 return true;
2267 case kReconcileSecondaryDexAccessIOError:
2268 // We had an access IO error.
2269 // Return false so that we can try again.
2270 // The value of out_secondary_dex_exists does not matter in this case and by convention
2271 // is set to false.
2272 *out_secondary_dex_exists = false;
2273 return false;
2274 default:
2275 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2276 *out_secondary_dex_exists = false;
2277 return false;
2278 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002279}
2280
Alan Stokesa25d90c2017-10-16 10:56:00 +01002281// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2282// Returns true if all parameters are valid and the hash successfully computed and stored in
2283// out_secondary_dex_hash.
2284// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2285// the app.
2286// For any other errors (e.g. if any of the parameters are invalid) returns false.
2287bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2288 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2289 std::vector<uint8_t>* out_secondary_dex_hash) {
2290 out_secondary_dex_hash->clear();
2291
2292 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2293
2294 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2295 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2296 << storage_flag;
2297 return false;
2298 }
2299
2300 // Pipe to get the hash result back from our child process.
2301 unique_fd pipe_read, pipe_write;
2302 if (!Pipe(&pipe_read, &pipe_write)) {
2303 PLOG(ERROR) << "Failed to create pipe";
2304 return false;
2305 }
2306
2307 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2308 // access data the app itself can access.
2309 pid_t pid = fork();
2310 if (pid == 0) {
2311 // child -- drop privileges before continuing
2312 drop_capabilities(uid);
2313 pipe_read.reset();
2314
2315 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2316 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002317 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002318 }
2319
2320 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2321 if (fd == -1) {
2322 if (errno == EACCES || errno == ENOENT) {
2323 // Not treated as an error.
2324 _exit(0);
2325 }
2326 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002327 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002328 }
2329
2330 SHA256_CTX ctx;
2331 SHA256_Init(&ctx);
2332
2333 std::vector<uint8_t> buffer(65536);
2334 while (true) {
2335 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2336 if (bytes_read == 0) {
2337 break;
2338 } else if (bytes_read == -1) {
2339 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002340 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002341 }
2342
2343 SHA256_Update(&ctx, buffer.data(), bytes_read);
2344 }
2345
2346 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2347 SHA256_Final(hash.data(), &ctx);
2348 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002349 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002350 }
2351
2352 _exit(0);
2353 }
2354
2355 // parent
2356 pipe_write.reset();
2357
2358 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2359 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2360 out_secondary_dex_hash->clear();
2361 }
2362 return wait_child(pid) == 0;
2363}
2364
Jeff Sharkey90aff262016-12-12 14:28:24 -07002365// Helper for move_ab, so that we can have common failure-case cleanup.
2366static bool unlink_and_rename(const char* from, const char* to) {
2367 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2368 // return a failure.
2369 struct stat s;
2370 if (stat(to, &s) == 0) {
2371 if (!S_ISREG(s.st_mode)) {
2372 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2373 return false;
2374 }
2375 if (unlink(to) != 0) {
2376 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2377 return false;
2378 }
2379 } else {
2380 // This may be a permission problem. We could investigate the error code, but we'll just
2381 // let the rename failure do the work for us.
2382 }
2383
2384 // Try to rename "to" to "from."
2385 if (rename(from, to) != 0) {
2386 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2387 return false;
2388 }
2389 return true;
2390}
2391
2392// Move/rename a B artifact (from) to an A artifact (to).
2393static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2394 // Check whether B exists.
2395 {
2396 struct stat s;
2397 if (stat(b_path.c_str(), &s) != 0) {
2398 // Silently ignore for now. The service calling this isn't smart enough to understand
2399 // lack of artifacts at the moment.
2400 return false;
2401 }
2402 if (!S_ISREG(s.st_mode)) {
2403 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2404 // Try to unlink, but swallow errors.
2405 unlink(b_path.c_str());
2406 return false;
2407 }
2408 }
2409
2410 // Rename B to A.
2411 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2412 // Delete the b_path so we don't try again (or fail earlier).
2413 if (unlink(b_path.c_str()) != 0) {
2414 PLOG(ERROR) << "Could not unlink " << b_path;
2415 }
2416
2417 return false;
2418 }
2419
2420 return true;
2421}
2422
2423bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2424 // Get the current slot suffix. No suffix, no A/B.
2425 std::string slot_suffix;
2426 {
2427 char buf[kPropertyValueMax];
2428 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2429 return false;
2430 }
2431 slot_suffix = buf;
2432
2433 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2434 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2435 return false;
2436 }
2437 }
2438
2439 // Validate other inputs.
2440 if (validate_apk_path(apk_path) != 0) {
2441 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2442 return false;
2443 }
2444 if (validate_apk_path(oat_dir) != 0) {
2445 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2446 return false;
2447 }
2448
2449 char a_path[PKG_PATH_MAX];
2450 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2451 return false;
2452 }
2453 const std::string a_vdex_path = create_vdex_filename(a_path);
2454 const std::string a_image_path = create_image_filename(a_path);
2455
2456 // B path = A path + slot suffix.
2457 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2458 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2459 const std::string b_image_path = StringPrintf("%s.%s",
2460 a_image_path.c_str(),
2461 slot_suffix.c_str());
2462
2463 bool success = true;
2464 if (move_ab_path(b_path, a_path)) {
2465 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2466 // Note: we can live without an app image. As such, ignore failure to move the image file.
2467 // If we decide to require the app image, or the app image being moved correctly,
2468 // then change accordingly.
2469 constexpr bool kIgnoreAppImageFailure = true;
2470
2471 if (!a_image_path.empty()) {
2472 if (!move_ab_path(b_image_path, a_image_path)) {
2473 unlink(a_image_path.c_str());
2474 if (!kIgnoreAppImageFailure) {
2475 success = false;
2476 }
2477 }
2478 }
2479 } else {
2480 // Cleanup: delete B image, ignore errors.
2481 unlink(b_image_path.c_str());
2482 success = false;
2483 }
2484 } else {
2485 // Cleanup: delete B image, ignore errors.
2486 unlink(b_vdex_path.c_str());
2487 unlink(b_image_path.c_str());
2488 success = false;
2489 }
2490 return success;
2491}
2492
2493bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2494 // Delete the oat/odex file.
2495 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002496 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002497 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002498 return false;
2499 }
2500
2501 // In case of a permission failure report the issue. Otherwise just print a warning.
2502 auto unlink_and_check = [](const char* path) -> bool {
2503 int result = unlink(path);
2504 if (result != 0) {
2505 if (errno == EACCES || errno == EPERM) {
2506 PLOG(ERROR) << "Could not unlink " << path;
2507 return false;
2508 }
2509 PLOG(WARNING) << "Could not unlink " << path;
2510 }
2511 return true;
2512 };
2513
2514 // Delete the oat/odex file.
2515 bool return_value_oat = unlink_and_check(out_path);
2516
2517 // Derive and delete the app image.
2518 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2519
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002520 // Derive and delete the vdex file.
2521 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2522
Jeff Sharkey90aff262016-12-12 14:28:24 -07002523 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002524 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002525}
2526
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002527static bool is_absolute_path(const std::string& path) {
2528 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2529 LOG(ERROR) << "Invalid absolute path " << path;
2530 return false;
2531 } else {
2532 return true;
2533 }
2534}
2535
2536static bool is_valid_instruction_set(const std::string& instruction_set) {
2537 // TODO: add explicit whitelisting of instruction sets
2538 if (instruction_set.find('/') != std::string::npos) {
2539 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2540 return false;
2541 } else {
2542 return true;
2543 }
2544}
2545
2546bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2547 const char *apk_path, const char *instruction_set) {
2548 std::string oat_dir_ = oat_dir;
2549 std::string apk_path_ = apk_path;
2550 std::string instruction_set_ = instruction_set;
2551
2552 if (!is_absolute_path(oat_dir_)) return false;
2553 if (!is_absolute_path(apk_path_)) return false;
2554 if (!is_valid_instruction_set(instruction_set_)) return false;
2555
2556 std::string::size_type end = apk_path_.rfind('.');
2557 std::string::size_type start = apk_path_.rfind('/', end);
2558 if (end == std::string::npos || start == std::string::npos) {
2559 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2560 return false;
2561 }
2562
2563 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2564 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2565 const char* res = res_.c_str();
2566 if (strlen(res) >= PKG_PATH_MAX) {
2567 LOG(ERROR) << "Result too large";
2568 return false;
2569 } else {
2570 strlcpy(path, res, PKG_PATH_MAX);
2571 return true;
2572 }
2573}
2574
2575bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2576 const char *instruction_set) {
2577 std::string apk_path_ = apk_path;
2578 std::string instruction_set_ = instruction_set;
2579
2580 if (!is_absolute_path(apk_path_)) return false;
2581 if (!is_valid_instruction_set(instruction_set_)) return false;
2582
2583 std::string::size_type end = apk_path_.rfind('.');
2584 std::string::size_type start = apk_path_.rfind('/', end);
2585 if (end == std::string::npos || start == std::string::npos) {
2586 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2587 return false;
2588 }
2589
2590 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2591 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2592}
2593
2594bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2595 const char *instruction_set) {
2596 std::string src_ = src;
2597 std::string instruction_set_ = instruction_set;
2598
2599 if (!is_absolute_path(src_)) return false;
2600 if (!is_valid_instruction_set(instruction_set_)) return false;
2601
2602 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2603 if (*it == '/') {
2604 *it = '@';
2605 }
2606 }
2607
2608 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2609 + DALVIK_CACHE_POSTFIX;
2610 const char* res = res_.c_str();
2611 if (strlen(res) >= PKG_PATH_MAX) {
2612 LOG(ERROR) << "Result too large";
2613 return false;
2614 } else {
2615 strlcpy(path, res, PKG_PATH_MAX);
2616 return true;
2617 }
2618}
2619
Calin Juravle3bbaed22018-04-27 17:50:23 -07002620bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2621 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002622 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2623 for (const std::string& elem : classpaths_elems) {
2624 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2625 if (fd < 0) {
2626 PLOG(ERROR) << "Could not open classpath elem " << elem;
2627 return false;
2628 } else {
2629 apk_fds->push_back(std::move(fd));
Calin Juravle3bbaed22018-04-27 17:50:23 -07002630 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002631 }
2632 }
2633 return true;
2634}
2635
2636static bool create_app_profile_snapshot(int32_t app_id,
2637 const std::string& package_name,
2638 const std::string& profile_name,
2639 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002640 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2641
Calin Juravle824a64d2018-01-18 20:23:17 -08002642 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002643 if (snapshot_fd < 0) {
2644 return false;
2645 }
2646
2647 std::vector<unique_fd> profiles_fd;
2648 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002649 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2650 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002651 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2652 return false;
2653 }
2654
2655 profiles_fd.push_back(std::move(reference_profile_fd));
2656
Calin Juravle0d0a4922018-01-23 19:54:11 -08002657 // Open the class paths elements. These will be used to filter out profile data that does
2658 // not belong to the classpath during merge.
2659 std::vector<unique_fd> apk_fds;
Calin Juravle3bbaed22018-04-27 17:50:23 -07002660 std::vector<std::string> dex_locations;
2661 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002662 return false;
2663 }
2664
Calin Juravle29591732017-11-20 17:46:19 -08002665 pid_t pid = fork();
2666 if (pid == 0) {
2667 /* child -- drop privileges before continuing */
2668 drop_capabilities(app_shared_gid);
Calin Juravle3bbaed22018-04-27 17:50:23 -07002669 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds, &dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002670 }
2671
2672 /* parent */
2673 int return_code = wait_child(pid);
2674 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002675 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002676 return false;
2677 }
2678
2679 return true;
2680}
2681
Calin Juravle0d0a4922018-01-23 19:54:11 -08002682static bool create_boot_image_profile_snapshot(const std::string& package_name,
2683 const std::string& profile_name,
2684 const std::string& classpath) {
2685 // The reference profile directory for the android package might not be prepared. Do it now.
2686 const std::string ref_profile_dir =
2687 create_primary_reference_profile_package_dir_path(package_name);
2688 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2689 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2690 return false;
2691 }
2692
2693 // Open and create the snapshot profile.
2694 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2695
2696 // Collect all non empty profiles.
2697 // The collection will traverse all applications profiles and find the non empty files.
2698 // This has the potential of inspecting a large number of files and directories (depending
2699 // on the number of applications and users). So there is a slight increase in the chance
2700 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2701 // fail the snapshot and aggregate whatever profile we could open.
2702 //
2703 // The profile snapshot is a best effort based on available data it's ok if some data
2704 // from some apps is missing. It will be counter productive for the snapshot to fail
2705 // because we could not open or read some of the files.
2706 std::vector<std::string> profiles;
2707 if (!collect_profiles(&profiles)) {
2708 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2709 }
2710
2711 // If we have no profiles return early.
2712 if (profiles.empty()) {
2713 return true;
2714 }
2715
2716 // Open the classpath elements. These will be used to filter out profile data that does
2717 // not belong to the classpath during merge.
2718 std::vector<unique_fd> apk_fds;
Calin Juravle3bbaed22018-04-27 17:50:23 -07002719 std::vector<std::string> dex_locations;
2720 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002721 return false;
2722 }
2723
2724 // If we could not open any files from the classpath return an error.
2725 if (apk_fds.empty()) {
2726 LOG(ERROR) << "Could not open any of the classpath elements.";
2727 return false;
2728 }
2729
2730 // Aggregate the profiles in batches of kAggregationBatchSize.
2731 // We do this to avoid opening a huge a amount of files.
2732 static constexpr size_t kAggregationBatchSize = 10;
2733
2734 std::vector<unique_fd> profiles_fd;
2735 for (size_t i = 0; i < profiles.size(); ) {
2736 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2737 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2738 if (fd.get() >= 0) {
2739 profiles_fd.push_back(std::move(fd));
2740 }
2741 }
2742 pid_t pid = fork();
2743 if (pid == 0) {
2744 /* child -- drop privileges before continuing */
2745 drop_capabilities(AID_SYSTEM);
2746
Calin Juravle3bbaed22018-04-27 17:50:23 -07002747 // The introduction of new access flags into boot jars causes them to
2748 // fail dex file verification.
2749 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds, &dex_locations);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002750 }
2751
2752 /* parent */
2753 int return_code = wait_child(pid);
2754 if (!WIFEXITED(return_code)) {
2755 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2756 return false;
2757 }
2758 return true;
2759 }
2760 return true;
2761}
2762
2763bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2764 const std::string& profile_name, const std::string& classpath) {
2765 if (app_id == -1) {
2766 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2767 } else {
2768 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2769 }
2770}
2771
Calin Juravlec3b049e2018-01-18 22:32:58 -08002772bool prepare_app_profile(const std::string& package_name,
2773 userid_t user_id,
2774 appid_t app_id,
2775 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002776 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002777 const std::unique_ptr<std::string>& dex_metadata) {
2778 // Prepare the current profile.
2779 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2780 /*is_secondary_dex*/ false);
2781 uid_t uid = multiuser_get_uid(user_id, app_id);
2782 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2783 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2784 return false;
2785 }
2786
2787 // Check if we need to install the profile from the dex metadata.
2788 if (dex_metadata == nullptr) {
2789 return true;
2790 }
2791
2792 // We have a dex metdata. Merge the profile into the reference profile.
2793 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2794 /*read_write*/ true, /*is_secondary_dex*/ false);
2795 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2796 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002797 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2798 if (apk_fd < 0) {
2799 PLOG(ERROR) << "Could not open code path " << code_path;
2800 return false;
2801 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002802
2803 pid_t pid = fork();
2804 if (pid == 0) {
2805 /* child -- drop privileges before continuing */
2806 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2807 drop_capabilities(app_shared_gid);
2808
Calin Juravlef63d4792018-01-30 17:43:34 +00002809 // The copy and update takes ownership over the fds.
2810 run_profman_copy_and_update(std::move(dex_metadata_fd),
2811 std::move(ref_profile_fd),
Calin Juravle3bbaed22018-04-27 17:50:23 -07002812 std::move(apk_fd),
2813 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002814 }
2815
2816 /* parent */
2817 int return_code = wait_child(pid);
2818 if (!WIFEXITED(return_code)) {
2819 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2820 return false;
2821 }
2822 return true;
2823}
2824
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002825} // namespace installd
2826} // namespace android