blob: 66dece740a13d861ab5947f2aba57c7be5dd5e34 [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
Yi Kong954cf642018-07-17 16:16:24 -0700193 while(strtok_r(pBuf, " ", &ctx) != nullptr) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700194 count++;
Yi Kong954cf642018-07-17 16:16:24 -0700195 pBuf = nullptr;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700196 }
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
Yi Kong954cf642018-07-17 16:16:24 -0700208 while((tok = strtok_r(pBuf, " ", &ctx)) != nullptr) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700209 argv[count++] = tok;
Yi Kong954cf642018-07-17 16:16:24 -0700210 pBuf = nullptr;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700211 }
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);
Yi Kong954cf642018-07-17 16:16:24 -0700219 if (location == nullptr) {
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700220 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];
Yi Kong954cf642018-07-17 16:16:24 -0700246 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700247
248 char dex2oat_Xmx_flag[kPropertyValueMax];
Yi Kong954cf642018-07-17 16:16:24 -0700249 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700250
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,
Yi Kong954cf642018-07-17 16:16:24 -0700256 nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700257 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,
Yi Kong954cf642018-07-17 16:16:24 -0700266 dex2oat_isa_features, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700267
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,
Yi Kong954cf642018-07-17 16:16:24 -0700272 dex2oat_isa_variant, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700273
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",
Yi Kong954cf642018-07-17 16:16:24 -0700279 dex2oat_flags, nullptr) <= 0 ? 0 : split_count(dex2oat_flags);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700280 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 =
Yi Kong954cf642018-07-17 16:16:24 -0700294 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700295 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 =
Yi Kong954cf642018-07-17 16:16:24 -0700301 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700302 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";
David Sehr31419e72018-05-24 15:00:09 -0700312 // Do not use dex2oatd for release candidates (give dex2oat more soak time).
313 bool is_release = android::base::GetProperty("ro.build.version.codename", "") == "REL";
314 if (is_debug_runtime() || (background_job_compile && is_debuggable_build() && !is_release)) {
Andreas Gampee87fe0a2018-03-01 23:55:53 -0800315 if (access(kDex2oatDebugPath, X_OK) == 0) {
316 dex2oat_bin = kDex2oatDebugPath;
317 }
David Sehra3b5ab62017-10-25 14:27:29 -0700318 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700319
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700320 bool generate_minidebug_info = kEnableMinidebugInfo &&
321 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
322 kMinidebugInfoSystemPropertyDefault);
323
Jeff Sharkey90aff262016-12-12 14:28:24 -0700324 static const char* RUNTIME_ARG = "--runtime-arg";
325
326 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
327
George Burgess IV36cebe772017-01-25 11:52:01 -0800328 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
329 // use arraysize instead.
330 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
331 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
332 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
333 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
334 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
335 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
336 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
337 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
338 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
339 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
340 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
341 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800343 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700344 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800345 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700346 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
David Brazdil570d3982018-01-16 20:15:43 +0000347 char target_sdk_version_arg[arraysize("-Xtarget-sdk-version:") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700348 char class_loader_context_arg[class_loader_context_size];
349 if (class_loader_context != nullptr) {
350 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
351 class_loader_context);
352 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700353
354 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700355 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700356 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
357 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
358 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
359 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
360 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
361 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
362 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
363 if (swap_fd >= 0) {
364 have_dex2oat_swap_fd = true;
365 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
366 }
367 if (image_fd >= 0) {
368 have_dex2oat_image_fd = true;
369 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
370 }
371
372 if (have_dex2oat_Xms_flag) {
373 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
374 }
375 if (have_dex2oat_Xmx_flag) {
376 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
377 }
David Brazdil570d3982018-01-16 20:15:43 +0000378 sprintf(target_sdk_version_arg, "-Xtarget-sdk-version:%d", target_sdk_version);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700379
380 // Compute compiler filter.
381
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100382 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700383 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600384 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
385 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700386 have_dex2oat_compiler_filter_flag = true;
387 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100388 } else if (compiler_filter != nullptr) {
389 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700390 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100391 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
392 have_dex2oat_compiler_filter_flag = true;
393 } else {
394 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
395 compiler_filter,
396 kPropertyValueMax);
397 }
398 }
399
400 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700401 char dex2oat_compiler_filter_flag[kPropertyValueMax];
402 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
Yi Kong954cf642018-07-17 16:16:24 -0700403 dex2oat_compiler_filter_flag, nullptr) > 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700404 if (have_dex2oat_compiler_filter_flag) {
405 sprintf(dex2oat_compiler_filter_arg,
406 "--compiler-filter=%s",
407 dex2oat_compiler_filter_flag);
408 }
409 }
410
411 // Check whether all apps should be compiled debuggable.
412 if (!debuggable) {
413 char prop_buf[kPropertyValueMax];
414 debuggable =
415 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
416 (prop_buf[0] == '1');
417 }
418 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
419 if (profile_fd != -1) {
420 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
421 }
422
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700423 // Get the directory of the apk to pass as a base classpath directory.
424 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
425 std::string apk_dir(input_file_name);
426 unsigned long dir_index = apk_dir.rfind('/');
427 bool has_base_dir = dir_index != std::string::npos;
428 if (has_base_dir) {
429 apk_dir = apk_dir.substr(0, dir_index);
430 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
431 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700432
Calin Juravle62c5a372018-02-01 17:03:23 +0000433 std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700434
Calin Juravle2efc4022018-02-13 18:31:32 -0800435 std::string compilation_reason_arg = compilation_reason == nullptr
436 ? ""
437 : std::string("--compilation-reason=") + compilation_reason;
438
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700439 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700440
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800441 // Disable cdex if update input vdex is true since this combination of options is not
442 // supported.
Mathieu Chartierf69c2f72018-03-06 13:55:58 -0800443 const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800444
Jeff Sharkey90aff262016-12-12 14:28:24 -0700445 const char* argv[9 // program name, mandatory arguments and the final NULL
446 + (have_dex2oat_isa_variant ? 1 : 0)
447 + (have_dex2oat_isa_features ? 1 : 0)
448 + (have_dex2oat_Xms_flag ? 2 : 0)
449 + (have_dex2oat_Xmx_flag ? 2 : 0)
450 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
451 + (have_dex2oat_threads_flag ? 1 : 0)
452 + (have_dex2oat_swap_fd ? 1 : 0)
453 + (have_dex2oat_image_fd ? 1 : 0)
454 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
455 + (generate_debug_info ? 1 : 0)
456 + (debuggable ? 1 : 0)
457 + (have_app_image_format ? 1 : 0)
458 + dex2oat_flags_count
459 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700460 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700461 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700462 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800463 + (disable_cdex ? 1 : 0)
David Brazdil570d3982018-01-16 20:15:43 +0000464 + (generate_minidebug_info ? 1 : 0)
David Brazdil7fcbb812018-01-17 17:05:40 +0000465 + (target_sdk_version != 0 ? 2 : 0)
Calin Juravle62c5a372018-02-01 17:03:23 +0000466 + (enable_hidden_api_checks ? 2 : 0)
Calin Juravle2efc4022018-02-13 18:31:32 -0800467 + (dex_metadata_fd > -1 ? 1 : 0)
468 + (compilation_reason != nullptr ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700469 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700470 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700471 argv[i++] = zip_fd_arg;
472 argv[i++] = zip_location_arg;
473 argv[i++] = input_vdex_fd_arg;
474 argv[i++] = output_vdex_fd_arg;
475 argv[i++] = oat_fd_arg;
476 argv[i++] = oat_location_arg;
477 argv[i++] = instruction_set_arg;
478 if (have_dex2oat_isa_variant) {
479 argv[i++] = instruction_set_variant_arg;
480 }
481 if (have_dex2oat_isa_features) {
482 argv[i++] = instruction_set_features_arg;
483 }
484 if (have_dex2oat_Xms_flag) {
485 argv[i++] = RUNTIME_ARG;
486 argv[i++] = dex2oat_Xms_arg;
487 }
488 if (have_dex2oat_Xmx_flag) {
489 argv[i++] = RUNTIME_ARG;
490 argv[i++] = dex2oat_Xmx_arg;
491 }
492 if (have_dex2oat_compiler_filter_flag) {
493 argv[i++] = dex2oat_compiler_filter_arg;
494 }
495 if (have_dex2oat_threads_flag) {
496 argv[i++] = dex2oat_threads_arg;
497 }
498 if (have_dex2oat_swap_fd) {
499 argv[i++] = dex2oat_swap_fd;
500 }
501 if (have_dex2oat_image_fd) {
502 argv[i++] = dex2oat_image_fd;
503 }
504 if (generate_debug_info) {
505 argv[i++] = "--generate-debug-info";
506 }
507 if (debuggable) {
508 argv[i++] = "--debuggable";
509 }
510 if (have_app_image_format) {
511 argv[i++] = image_format_arg;
512 }
513 if (have_dex2oat_large_app_threshold) {
514 argv[i++] = dex2oat_large_app_threshold_arg;
515 }
516 if (dex2oat_flags_count) {
517 i += split(dex2oat_flags, argv + i);
518 }
519 if (have_dex2oat_relocation_skip_flag) {
520 argv[i++] = RUNTIME_ARG;
521 argv[i++] = dex2oat_norelocation;
522 }
523 if (profile_fd != -1) {
524 argv[i++] = profile_arg;
525 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700526 if (has_base_dir) {
527 argv[i++] = base_dir;
528 }
Calin Juravle52c45822017-07-13 22:50:21 -0700529 if (class_loader_context != nullptr) {
530 argv[i++] = class_loader_context_arg;
531 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700532 if (generate_minidebug_info) {
533 argv[i++] = kMinidebugDex2oatFlag;
534 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800535 if (disable_cdex) {
536 argv[i++] = kDisableCompactDexFlag;
537 }
David Brazdil570d3982018-01-16 20:15:43 +0000538 if (target_sdk_version != 0) {
539 argv[i++] = RUNTIME_ARG;
540 argv[i++] = target_sdk_version_arg;
541 }
David Brazdil52249162018-02-12 18:04:59 -0800542 if (enable_hidden_api_checks) {
David Brazdil7fcbb812018-01-17 17:05:40 +0000543 argv[i++] = RUNTIME_ARG;
David Brazdil52249162018-02-12 18:04:59 -0800544 argv[i++] = "-Xhidden-api-checks";
David Brazdil7fcbb812018-01-17 17:05:40 +0000545 }
Calin Juravle52c45822017-07-13 22:50:21 -0700546
Calin Juravle62c5a372018-02-01 17:03:23 +0000547 if (dex_metadata_fd > -1) {
548 argv[i++] = dex_metadata_fd_arg.c_str();
549 }
Calin Juravle2efc4022018-02-13 18:31:32 -0800550
551 if(compilation_reason != nullptr) {
552 argv[i++] = compilation_reason_arg.c_str();
553 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700554 // Do not add after dex2oat_flags, they should override others for debugging.
Yi Kong954cf642018-07-17 16:16:24 -0700555 argv[i] = nullptr;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700556
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700557 execv(dex2oat_bin, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800558 PLOG(ERROR) << "execv(" << dex2oat_bin << ") failed";
559 exit(DexoptReturnCodes::kDex2oatExec);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700560}
561
562/*
563 * Whether dexopt should use a swap file when compiling an APK.
564 *
565 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
566 * itself, anyways).
567 *
568 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
569 *
570 * Otherwise, return true if this is a low-mem device.
571 *
572 * Otherwise, return default value.
573 */
574static bool kAlwaysProvideSwapFile = false;
575static bool kDefaultProvideSwapFile = true;
576
577static bool ShouldUseSwapFileForDexopt() {
578 if (kAlwaysProvideSwapFile) {
579 return true;
580 }
581
582 // Check the "override" property. If it exists, return value == "true".
583 char dex2oat_prop_buf[kPropertyValueMax];
584 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
585 if (strcmp(dex2oat_prop_buf, "true") == 0) {
586 return true;
587 } else {
588 return false;
589 }
590 }
591
592 // Shortcut for default value. This is an implementation optimization for the process sketched
593 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
594 // as low-mem is never returning false. The compiler will optimize this away if it can.
595 if (kDefaultProvideSwapFile) {
596 return true;
597 }
598
599 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
600 if (is_low_mem) {
601 return true;
602 }
603
604 // Default value must be false here.
605 return kDefaultProvideSwapFile;
606}
607
Richard Uhler76cc0272016-12-08 10:46:35 +0000608static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700609 if (set_to_bg) {
610 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800611 PLOG(ERROR) << "set_sched_policy failed";
612 exit(DexoptReturnCodes::kSetSchedPolicy);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700613 }
614 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800615 PLOG(ERROR) << "setpriority failed";
616 exit(DexoptReturnCodes::kSetPriority);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700617 }
618 }
619}
620
Calin Juravle29591732017-11-20 17:46:19 -0800621static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
622 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800623 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800624 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800625 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800626 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800627 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700628 }
Calin Juravle114f0812017-03-08 19:05:07 -0800629 // Profiles should belong to the app; make sure of that by giving ownership to
630 // the app uid. If we cannot do that, there's no point in returning the fd
631 // since dex2oat/profman will fail with SElinux denials.
632 if (fchown(fd.get(), uid, uid) < 0) {
633 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800634 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800635 }
Calin Juravle29591732017-11-20 17:46:19 -0800636 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800637}
638
Calin Juravle29591732017-11-20 17:46:19 -0800639static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800640 // Do not follow symlinks when opening a profile:
641 // - primary profiles should not contain symlinks in their paths
642 // - secondary dex paths should have been already resolved and validated
643 flags |= O_NOFOLLOW;
644
Calin Juravle29591732017-11-20 17:46:19 -0800645 // Check if we need to create the profile
646 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
647 unique_fd fd;
648 if ((flags & O_CREAT) != 0) {
649 fd = create_profile(uid, profile, flags);
650 } else {
651 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
652 }
653
Calin Juravle114f0812017-03-08 19:05:07 -0800654 if (fd.get() < 0) {
655 if (errno != ENOENT) {
656 // Profiles might be missing for various reasons. For example, in a
657 // multi-user environment, the profile directory for one user can be created
658 // after we start a merge. In this case the current profile for that user
659 // will not be found.
660 // Also, the secondary dex profiles might be deleted by the app at any time,
661 // so we can't we need to prepare if they are missing.
662 PLOG(ERROR) << "Failed to open profile " << profile;
663 }
664 return invalid_unique_fd();
665 }
666
Jeff Sharkey90aff262016-12-12 14:28:24 -0700667 return fd;
668}
669
Calin Juravle824a64d2018-01-18 20:23:17 -0800670static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
671 const std::string& location, bool is_secondary_dex) {
672 std::string profile = create_current_profile_path(user, package_name, location,
673 is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800674 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800675}
676
Calin Juravle824a64d2018-01-18 20:23:17 -0800677static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
678 const std::string& location, bool read_write, bool is_secondary_dex) {
679 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800680 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
681}
682
683static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
Calin Juravle824a64d2018-01-18 20:23:17 -0800684 const std::string& location) {
685 std::string profile = create_snapshot_profile_path(package_name, location);
Calin Juravle29591732017-11-20 17:46:19 -0800686 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800687}
688
Calin Juravle824a64d2018-01-18 20:23:17 -0800689static void open_profile_files(uid_t uid, const std::string& package_name,
690 const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800691 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700692 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle824a64d2018-01-18 20:23:17 -0800693 *reference_profile_fd = open_reference_profile(uid, package_name, location,
694 /*read_write*/ true, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700695
Calin Juravle114f0812017-03-08 19:05:07 -0800696 // For secondary dex files, we don't really need the user but we use it for sanity checks.
697 // Note: the user owning the dex file should be the current user.
698 std::vector<userid_t> users;
699 if (is_secondary_dex){
700 users.push_back(multiuser_get_user_id(uid));
701 } else {
702 users = get_known_users(/*volume_uuid*/ nullptr);
703 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700704 for (auto user : users) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800705 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
706 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700707 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800708 if (profile_fd.get() >= 0) {
709 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700710 }
711 }
712}
713
714static void drop_capabilities(uid_t uid) {
715 if (setgid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800716 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
717 exit(DexoptReturnCodes::kSetGid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700718 }
719 if (setuid(uid) != 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800720 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
721 exit(DexoptReturnCodes::kSetUid);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700722 }
723 // drop capabilities
724 struct __user_cap_header_struct capheader;
725 struct __user_cap_data_struct capdata[2];
726 memset(&capheader, 0, sizeof(capheader));
727 memset(&capdata, 0, sizeof(capdata));
728 capheader.version = _LINUX_CAPABILITY_VERSION_3;
729 if (capset(&capheader, &capdata[0]) < 0) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800730 PLOG(ERROR) << "capset failed";
731 exit(DexoptReturnCodes::kCapSet);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700732 }
733}
734
735static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
736static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
737static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
738static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
739static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
740
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800741[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000742static void run_profman(const std::vector<unique_fd>& profile_fds,
743 const unique_fd& reference_profile_fd,
744 const std::vector<unique_fd>* apk_fds,
Calin Juravle59f7ab82018-04-27 17:50:23 -0700745 const std::vector<std::string>* dex_locations,
Calin Juravlef63d4792018-01-30 17:43:34 +0000746 bool copy_and_update) {
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700747 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700748
Calin Juravlef63d4792018-01-30 17:43:34 +0000749 if (copy_and_update) {
750 CHECK_EQ(1u, profile_fds.size());
751 CHECK(apk_fds != nullptr);
752 CHECK_EQ(1u, apk_fds->size());
753 }
754 std::vector<std::string> profile_args(profile_fds.size());
755 for (size_t k = 0; k < profile_fds.size(); k++) {
756 profile_args[k] = "--profile-file-fd=" + std::to_string(profile_fds[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700757 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800758 std::string reference_profile_arg = "--reference-profile-file-fd="
759 + std::to_string(reference_profile_fd.get());
760
761 std::vector<std::string> apk_args;
762 if (apk_fds != nullptr) {
763 for (size_t k = 0; k < apk_fds->size(); k++) {
764 apk_args.push_back("--apk-fd=" + std::to_string((*apk_fds)[k].get()));
765 }
766 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700767
Calin Juravle59f7ab82018-04-27 17:50:23 -0700768 std::vector<std::string> dex_location_args;
769 if (dex_locations != nullptr) {
770 for (size_t k = 0; k < dex_locations->size(); k++) {
771 dex_location_args.push_back("--dex-location=" + (*dex_locations)[k]);
772 }
773 }
774
Jeff Sharkey90aff262016-12-12 14:28:24 -0700775 // program name, reference profile fd, the final NULL and the profile fds
Calin Juravlea30265a2018-06-11 13:28:15 -0700776 const char* argv[3 + profile_args.size() + apk_args.size()
777 + dex_location_args.size() + (copy_and_update ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700778 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700779 argv[i++] = profman_bin;
Calin Juravle0d0a4922018-01-23 19:54:11 -0800780 argv[i++] = reference_profile_arg.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -0700781 for (size_t k = 0; k < profile_args.size(); k++) {
782 argv[i++] = profile_args[k].c_str();
783 }
Calin Juravle0d0a4922018-01-23 19:54:11 -0800784 for (size_t k = 0; k < apk_args.size(); k++) {
785 argv[i++] = apk_args[k].c_str();
786 }
Calin Juravle59f7ab82018-04-27 17:50:23 -0700787 for (size_t k = 0; k < dex_location_args.size(); k++) {
788 argv[i++] = dex_location_args[k].c_str();
789 }
Calin Juravlef63d4792018-01-30 17:43:34 +0000790 if (copy_and_update) {
791 argv[i++] = "--copy-and-update-profile-key";
792 }
Calin Juravle59f7ab82018-04-27 17:50:23 -0700793
Jeff Sharkey90aff262016-12-12 14:28:24 -0700794 // Do not add after dex2oat_flags, they should override others for debugging.
Yi Kong954cf642018-07-17 16:16:24 -0700795 argv[i] = nullptr;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700796
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700797 execv(profman_bin, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800798 PLOG(ERROR) << "execv(" << profman_bin << ") failed";
799 exit(DexoptReturnCodes::kProfmanExec); /* only get here on exec failure */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800}
801
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800802[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000803static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
804 const unique_fd& reference_profile_fd,
Calin Juravle59f7ab82018-04-27 17:50:23 -0700805 const std::vector<unique_fd>* apk_fds = nullptr,
806 const std::vector<std::string>* dex_locations = nullptr) {
807 run_profman(profiles_fd, reference_profile_fd, apk_fds, dex_locations,
808 /*copy_and_update*/false);
Calin Juravlef63d4792018-01-30 17:43:34 +0000809}
810
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800811[[ noreturn ]]
Calin Juravlef63d4792018-01-30 17:43:34 +0000812static void run_profman_copy_and_update(unique_fd&& profile_fd,
813 unique_fd&& reference_profile_fd,
Calin Juravle59f7ab82018-04-27 17:50:23 -0700814 unique_fd&& apk_fd,
815 const std::string& dex_location) {
Calin Juravlef63d4792018-01-30 17:43:34 +0000816 std::vector<unique_fd> profiles_fd;
817 profiles_fd.push_back(std::move(profile_fd));
818 std::vector<unique_fd> apk_fds;
819 apk_fds.push_back(std::move(apk_fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -0700820 std::vector<std::string> dex_locations;
821 dex_locations.push_back(dex_location);
Calin Juravlef63d4792018-01-30 17:43:34 +0000822
Calin Juravle59f7ab82018-04-27 17:50:23 -0700823 run_profman(profiles_fd, reference_profile_fd, &apk_fds, &dex_locations,
824 /*copy_and_update*/true);
Calin Juravlef63d4792018-01-30 17:43:34 +0000825}
826
Jeff Sharkey90aff262016-12-12 14:28:24 -0700827// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800828// The location is the package name for primary apks or the dex path for secondary dex files.
829// Returns true if there is enough information in the current profiles that makes it
830// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700831// If the return value is true all the current profiles would have been merged into
832// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800833static bool analyze_profiles(uid_t uid, const std::string& package_name,
834 const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800835 std::vector<unique_fd> profiles_fd;
836 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -0800837 open_profile_files(uid, package_name, location, is_secondary_dex,
838 &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800839 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700840 // Skip profile guided compilation because no profiles were found.
841 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700842 return false;
843 }
844
Jeff Sharkey90aff262016-12-12 14:28:24 -0700845 pid_t pid = fork();
846 if (pid == 0) {
847 /* child -- drop privileges before continuing */
848 drop_capabilities(uid);
849 run_profman_merge(profiles_fd, reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850 }
851 /* parent */
852 int return_code = wait_child(pid);
853 bool need_to_compile = false;
854 bool should_clear_current_profiles = false;
855 bool should_clear_reference_profile = false;
856 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800857 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700858 } else {
859 return_code = WEXITSTATUS(return_code);
860 switch (return_code) {
861 case PROFMAN_BIN_RETURN_CODE_COMPILE:
862 need_to_compile = true;
863 should_clear_current_profiles = true;
864 should_clear_reference_profile = false;
865 break;
866 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
867 need_to_compile = false;
868 should_clear_current_profiles = false;
869 should_clear_reference_profile = false;
870 break;
871 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800872 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873 need_to_compile = false;
874 should_clear_current_profiles = true;
875 should_clear_reference_profile = true;
876 break;
877 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
878 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
879 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800880 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700881 need_to_compile = false;
882 should_clear_current_profiles = false;
883 should_clear_reference_profile = false;
884 break;
885 default:
886 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800887 LOG(WARNING) << "Unknown error code while processing profiles for location "
888 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700889 need_to_compile = false;
890 should_clear_current_profiles = true;
891 should_clear_reference_profile = true;
892 break;
893 }
894 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800895
Jeff Sharkey90aff262016-12-12 14:28:24 -0700896 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800897 if (is_secondary_dex) {
898 // For secondary dex files, the owning user is the current user.
Calin Juravle824a64d2018-01-18 20:23:17 -0800899 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
900 is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -0800901 } else {
Calin Juravle824a64d2018-01-18 20:23:17 -0800902 clear_primary_current_profiles(package_name, location);
Calin Juravle114f0812017-03-08 19:05:07 -0800903 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700904 }
905 if (should_clear_reference_profile) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800906 clear_reference_profile(package_name, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700907 }
908 return need_to_compile;
909}
910
Calin Juravle114f0812017-03-08 19:05:07 -0800911// Decides if profile guided compilation is needed or not based on existing profiles.
912// The analysis is done for the primary apks of the given package.
913// Returns true if there is enough information in the current profiles that makes it
914// worth to recompile the package.
915// If the return value is true all the current profiles would have been merged into
916// the reference profiles accessible with open_reference_profile().
Calin Juravle824a64d2018-01-18 20:23:17 -0800917bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
918 const std::string& profile_name) {
919 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
Calin Juravle114f0812017-03-08 19:05:07 -0800920}
921
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800922[[ noreturn ]]
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800923static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
924 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700925 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800926 const std::vector<unique_fd>& apk_fds,
927 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700928 std::vector<std::string> profman_args;
929 static const char* PROFMAN_BIN = "/system/bin/profman";
930 profman_args.push_back(PROFMAN_BIN);
931 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800932 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700933 if (reference_profile_fd != -1) {
934 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800935 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700936 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800937 for (size_t i = 0; i < profile_fds.size(); i++) {
938 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700939 }
940 for (const std::string& dex_location : dex_locations) {
941 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
942 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800943 for (size_t i = 0; i < apk_fds.size(); i++) {
944 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700945 }
946 const char **argv = new const char*[profman_args.size() + 1];
947 size_t i = 0;
948 for (const std::string& profman_arg : profman_args) {
949 argv[i++] = profman_arg.c_str();
950 }
Yi Kong954cf642018-07-17 16:16:24 -0700951 argv[i] = nullptr;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700952
953 execv(PROFMAN_BIN, (char * const *)argv);
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800954 PLOG(ERROR) << "execv(" << PROFMAN_BIN << ") failed";
955 exit(DexoptReturnCodes::kProfmanExec); /* only get here on exec failure */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700956}
957
Calin Juravle408cd4a2018-01-20 23:34:18 -0800958bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
959 const std::string& code_path) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800960 std::vector<unique_fd> profile_fds;
961 unique_fd reference_profile_fd;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800962 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
963 pkgname.c_str(), profile_name.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700964
Calin Juravle408cd4a2018-01-20 23:34:18 -0800965 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
Calin Juravle114f0812017-03-08 19:05:07 -0800966 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700967
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800968 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700969 const bool has_profiles = !profile_fds.empty();
970
971 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800972 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700973 return false;
974 }
975
Calin Juravle114f0812017-03-08 19:05:07 -0800976 unique_fd output_fd(open(out_file_name.c_str(),
977 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700978 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
Calin Juravle408cd4a2018-01-20 23:34:18 -0800979 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700980 return false;
981 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800982
Jeff Sharkey90aff262016-12-12 14:28:24 -0700983 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800984 std::vector<unique_fd> apk_fds;
Calin Juravle408cd4a2018-01-20 23:34:18 -0800985 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
986 if (apk_fd == -1) {
987 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
988 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700989 }
Calin Juravle408cd4a2018-01-20 23:34:18 -0800990 dex_locations.push_back(get_location_from_path(code_path.c_str()));
991 apk_fds.push_back(std::move(apk_fd));
992
Jeff Sharkey90aff262016-12-12 14:28:24 -0700993
994 pid_t pid = fork();
995 if (pid == 0) {
996 /* child -- drop privileges before continuing */
997 drop_capabilities(uid);
998 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
999 apk_fds, output_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001000 }
1001 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -07001002 int return_code = wait_child(pid);
1003 if (!WIFEXITED(return_code)) {
1004 LOG(WARNING) << "profman failed for package " << pkgname << ": "
1005 << return_code;
1006 return false;
1007 }
1008 return true;
1009}
1010
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001011bool copy_system_profile(const std::string& system_profile,
Calin Juravle824a64d2018-01-18 20:23:17 -08001012 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001013 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
1014 unique_fd out_fd(open_reference_profile(packageUid,
Calin Juravle824a64d2018-01-18 20:23:17 -08001015 package_name,
1016 profile_name,
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001017 /*read_write*/ true,
1018 /*secondary*/ false));
1019 if (in_fd.get() < 0) {
1020 PLOG(WARNING) << "Could not open profile " << system_profile;
1021 return false;
1022 }
1023 if (out_fd.get() < 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001024 PLOG(WARNING) << "Could not open profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001025 return false;
1026 }
1027
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001028 // As a security measure we want to write the profile information with the reduced capabilities
1029 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001030 pid_t pid = fork();
1031 if (pid == 0) {
1032 /* child -- drop privileges before continuing */
1033 drop_capabilities(packageUid);
1034
1035 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1036 if (errno != EWOULDBLOCK) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001037 PLOG(WARNING) << "Error locking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001038 }
1039 // This implies that the app owning this profile is running
1040 // (and has acquired the lock).
1041 //
1042 // The app never acquires the lock for the reference profiles of primary apks.
1043 // Only dex2oat from installd will do that. Since installd is single threaded
1044 // we should not see this case. Nevertheless be prepared for it.
Calin Juravle824a64d2018-01-18 20:23:17 -08001045 PLOG(WARNING) << "Failed to flock " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001046 return false;
1047 }
1048
1049 bool truncated = ftruncate(out_fd.get(), 0) == 0;
1050 if (!truncated) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001051 PLOG(WARNING) << "Could not truncate " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001052 }
1053
1054 // Copy over data.
1055 static constexpr size_t kBufferSize = 4 * 1024;
1056 char buffer[kBufferSize];
1057 while (true) {
1058 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
1059 if (bytes == 0) {
1060 break;
1061 }
1062 write(out_fd.get(), buffer, bytes);
1063 }
1064 if (flock(out_fd.get(), LOCK_UN) != 0) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001065 PLOG(WARNING) << "Error unlocking profile " << package_name;
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001066 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -07001067 // Use _exit since we don't want to run the global destructors in the child.
1068 // b/62597429
1069 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001070 }
1071 /* parent */
1072 int return_code = wait_child(pid);
1073 return return_code == 0;
1074}
1075
Jeff Sharkey90aff262016-12-12 14:28:24 -07001076static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
1077 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
1078 if (EndsWith(oat_path, ".dex")) {
1079 std::string new_path = oat_path;
1080 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -08001081 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -07001082 return new_path;
1083 }
1084
1085 // An odex entry. Not that this may not be an extension, e.g., in the OTA
1086 // case (where the base name will have an extension for the B artifact).
1087 size_t odex_pos = oat_path.rfind(".odex");
1088 if (odex_pos != std::string::npos) {
1089 std::string new_path = oat_path;
1090 new_path.replace(odex_pos, strlen(".odex"), new_ext);
1091 CHECK_NE(new_path.find(new_ext), std::string::npos);
1092 return new_path;
1093 }
1094
1095 // Don't know how to handle this.
1096 return "";
1097}
1098
1099// Translate the given oat path to an art (app image) path. An empty string
1100// denotes an error.
1101static std::string create_image_filename(const std::string& oat_path) {
1102 return replace_file_extension(oat_path, ".art");
1103}
1104
1105// Translate the given oat path to a vdex path. An empty string denotes an error.
1106static std::string create_vdex_filename(const std::string& oat_path) {
1107 return replace_file_extension(oat_path, ".vdex");
1108}
1109
Jeff Sharkey90aff262016-12-12 14:28:24 -07001110static int open_output_file(const char* file_name, bool recreate, int permissions) {
1111 int flags = O_RDWR | O_CREAT;
1112 if (recreate) {
1113 if (unlink(file_name) < 0) {
1114 if (errno != ENOENT) {
1115 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1116 }
1117 }
1118 flags |= O_EXCL;
1119 }
1120 return open(file_name, flags, permissions);
1121}
1122
Calin Juravle2289c0a2017-02-15 12:44:14 -08001123static bool set_permissions_and_ownership(
1124 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1125 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1126 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001127 if (fchmod(fd,
1128 S_IRUSR|S_IWUSR|S_IRGRP |
1129 (is_public ? S_IROTH : 0)) < 0) {
1130 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1131 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001132 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001133 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1134 return false;
1135 }
1136 return true;
1137}
1138
1139static bool IsOutputDalvikCache(const char* oat_dir) {
1140 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1141 // into '!'. Play it safe by handling it both.
1142 // TODO: ensure we never get null.
1143 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1144 return oat_dir == nullptr || oat_dir[0] == '!';
1145}
1146
Calin Juravled23dee72017-07-06 16:29:11 -07001147// Best-effort check whether we can fit the the path into our buffers.
1148// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1149// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1150// extension to the cache path (5 bytes).
1151// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1152static bool validate_dex_path_size(const std::string& dex_path) {
1153 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1154 LOG(ERROR) << "dex_path too long: " << dex_path;
1155 return false;
1156 }
1157 return true;
1158}
1159
Jeff Sharkey90aff262016-12-12 14:28:24 -07001160static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001161 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001162 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001163 return false;
1164 }
1165
1166 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001167 // Oat dirs for secondary dex files are already validated.
1168 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1170 return false;
1171 }
1172 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1173 return false;
1174 }
1175 } else {
1176 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1177 return false;
1178 }
1179 }
1180 return true;
1181}
1182
1183// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1184// on destruction. It will also run the given cleanup (unless told not to) after closing.
1185//
1186// Usage example:
1187//
Calin Juravle7a570e82017-01-14 16:23:30 -08001188// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001189// [name]() {
1190// unlink(name.c_str());
1191// });
1192// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1193// wrapper if captured as a reference.
1194//
1195// if (file.get() == -1) {
1196// // Error opening...
1197// }
1198//
1199// ...
1200// if (error) {
1201// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1202// // and delete the file (after the fd is closed).
1203// return -1;
1204// }
1205//
1206// (Success case)
1207// file.SetCleanup(false);
1208// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1209// // (leaving the file around; after the fd is closed).
1210//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001211class Dex2oatFileWrapper {
1212 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001213 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001214 }
1215
Calin Juravle7a570e82017-01-14 16:23:30 -08001216 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1217 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1218
1219 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1220 value_ = other.value_;
1221 cleanup_ = other.cleanup_;
1222 do_cleanup_ = other.do_cleanup_;
1223 auto_close_ = other.auto_close_;
1224 other.release();
1225 }
1226
1227 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1228 value_ = other.value_;
1229 cleanup_ = other.cleanup_;
1230 do_cleanup_ = other.do_cleanup_;
1231 auto_close_ = other.auto_close_;
1232 other.release();
1233 return *this;
1234 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001235
1236 ~Dex2oatFileWrapper() {
1237 reset(-1);
1238 }
1239
1240 int get() {
1241 return value_;
1242 }
1243
1244 void SetCleanup(bool cleanup) {
1245 do_cleanup_ = cleanup;
1246 }
1247
1248 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001249 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001250 close(value_);
1251 }
1252 if (do_cleanup_ && cleanup_ != nullptr) {
1253 cleanup_();
1254 }
1255
1256 value_ = new_value;
1257 }
1258
Calin Juravle7a570e82017-01-14 16:23:30 -08001259 void reset(int new_value, std::function<void ()> new_cleanup) {
1260 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001261 close(value_);
1262 }
1263 if (do_cleanup_ && cleanup_ != nullptr) {
1264 cleanup_();
1265 }
1266
1267 value_ = new_value;
1268 cleanup_ = new_cleanup;
1269 }
1270
Calin Juravle7a570e82017-01-14 16:23:30 -08001271 void DisableAutoClose() {
1272 auto_close_ = false;
1273 }
1274
Jeff Sharkey90aff262016-12-12 14:28:24 -07001275 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001276 void release() {
1277 value_ = -1;
1278 do_cleanup_ = false;
1279 cleanup_ = nullptr;
1280 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001281 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001282 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001283 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001284 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001285};
1286
Calin Juravle7a570e82017-01-14 16:23:30 -08001287// (re)Creates the app image if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001288Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
1289 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001290
1291 // We don't create an image for secondary dex files.
1292 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001293 return Dex2oatFileWrapper();
1294 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001295
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 const std::string image_path = create_image_filename(out_oat_path);
1297 if (image_path.empty()) {
1298 // Happens when the out_oat_path has an unknown extension.
1299 return Dex2oatFileWrapper();
1300 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001301
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001302 // In case there is a stale image, remove it now. Ignore any error.
1303 unlink(image_path.c_str());
1304
1305 // Not enabled, exit.
1306 if (!generate_app_image) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001307 return Dex2oatFileWrapper();
1308 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001309 char app_image_format[kPropertyValueMax];
1310 bool have_app_image_format =
Yi Kong954cf642018-07-17 16:16:24 -07001311 get_property("dalvik.vm.appimageformat", app_image_format, nullptr) > 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001312 if (!have_app_image_format) {
1313 return Dex2oatFileWrapper();
1314 }
1315 // Recreate is true since we do not want to modify a mapped image. If the app is
1316 // already running and we modify the image file, it can cause crashes (b/27493510).
1317 Dex2oatFileWrapper wrapper_fd(
1318 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1319 [image_path]() { unlink(image_path.c_str()); });
1320 if (wrapper_fd.get() < 0) {
1321 // Could not create application image file. Go on since we can compile without it.
1322 LOG(ERROR) << "installd could not create '" << image_path
1323 << "' for image file during dexopt";
1324 // If we have a valid image file path but no image fd, explicitly erase the image file.
1325 if (unlink(image_path.c_str()) < 0) {
1326 if (errno != ENOENT) {
1327 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1328 }
1329 }
1330 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001331 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001332 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1333 wrapper_fd.reset(-1);
1334 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001335
Calin Juravle7a570e82017-01-14 16:23:30 -08001336 return wrapper_fd;
1337}
1338
1339// Creates the dexopt swap file if necessary and return its fd.
1340// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001341unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001342 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001343 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001344 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001345 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001346 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001347 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001348 if (swap_fd.get() < 0) {
1349 // Could not create swap file. Optimistically go on and hope that we can compile
1350 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001351 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001352 } else {
1353 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001354 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001355 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1356 }
1357 }
1358 return swap_fd;
1359}
1360
1361// Opens the reference profiles if needed.
1362// 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 -08001363Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001364 const std::string& dex_path, const char* profile_name, bool profile_guided,
Calin Juravle824a64d2018-01-18 20:23:17 -08001365 bool is_public, int uid, bool is_secondary_dex) {
Calin Juravle5bd1c722018-02-01 17:23:54 +00001366 // If we are not profile guided compilation, or we are compiling system server
1367 // do not bother to open the profiles; we won't be using them.
1368 if (!profile_guided || (pkgname[0] == '*')) {
1369 return Dex2oatFileWrapper();
1370 }
1371
1372 // If this is a secondary dex path which is public do not open the profile.
1373 // We cannot compile public secondary dex paths with profiles. That's because
1374 // it will expose how the dex files are used by their owner.
1375 //
1376 // Note that the PackageManager is responsible to set the is_public flag for
1377 // primary apks and we do not check it here. In some cases, e.g. when
1378 // compiling with a public profile from the .dm file the PackageManager will
1379 // set is_public toghether with the profile guided compilation.
1380 if (is_secondary_dex && is_public) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001381 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001382 }
Calin Juravle114f0812017-03-08 19:05:07 -08001383
1384 // Open reference profile in read only mode as dex2oat does not get write permissions.
Calin Juravlec4f6a0b2018-02-01 01:27:24 +00001385 std::string location;
1386 if (is_secondary_dex) {
1387 location = dex_path;
1388 } else {
1389 if (profile_name == nullptr) {
1390 // This path is taken for system server re-compilation lunched from ZygoteInit.
1391 return Dex2oatFileWrapper();
1392 } else {
1393 location = profile_name;
1394 }
1395 }
Calin Juravle824a64d2018-01-18 20:23:17 -08001396 unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
1397 is_secondary_dex);
1398 const auto& cleanup = [pkgname, location, is_secondary_dex]() {
1399 clear_reference_profile(pkgname, location, is_secondary_dex);
Calin Juravle114f0812017-03-08 19:05:07 -08001400 };
1401 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001402}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001403
Calin Juravle7a570e82017-01-14 16:23:30 -08001404// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1405// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001406bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001407 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001408 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001409 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1410 CHECK(in_vdex_wrapper_fd != nullptr);
1411 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001412 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1413 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001414 char in_odex_path[PKG_PATH_MAX];
1415 int dexopt_action = abs(dexopt_needed);
1416 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001417 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001418
1419 // Infer the name of the output VDEX.
1420 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1421 if (out_vdex_path_str.empty()) {
1422 return false;
1423 }
1424
1425 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001426 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001427 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1428 const char* path = nullptr;
1429 if (is_odex_location) {
1430 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1431 path = in_odex_path;
1432 } else {
1433 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001434 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001435 }
1436 } else {
1437 path = out_oat_path;
1438 }
1439 in_vdex_path_str = create_vdex_filename(path);
1440 if (in_vdex_path_str.empty()) {
1441 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001442 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001443 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001444 // We can update in place when all these conditions are met:
1445 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1446 // on /system typically cannot be updated in place).
1447 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1448 // cannot be currently used by a running process.
1449 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1450 // different vdex files to operate.
1451 update_vdex_in_place =
1452 (in_vdex_path_str == out_vdex_path_str) &&
1453 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1454 !profile_guided;
1455 if (update_vdex_in_place) {
1456 // Open the file read-write to be able to update it.
1457 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1458 if (in_vdex_wrapper_fd->get() == -1) {
1459 // If we failed to open the file, we cannot update it in place.
1460 update_vdex_in_place = false;
1461 }
1462 } else {
1463 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1464 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001465 }
1466
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001467 // If we are updating the vdex in place, we do not need to recreate a vdex,
1468 // and can use the same existing one.
1469 if (update_vdex_in_place) {
1470 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1471 // have bogus stale vdex files.
1472 out_vdex_wrapper_fd->reset(
1473 in_vdex_wrapper_fd->get(),
1474 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1475 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1476 // wrapper).
1477 in_vdex_wrapper_fd->DisableAutoClose();
1478 } else {
1479 out_vdex_wrapper_fd->reset(
1480 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1481 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1482 if (out_vdex_wrapper_fd->get() < 0) {
1483 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1484 return false;
1485 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001486 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001487 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001488 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001489 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1490 return false;
1491 }
1492
1493 // If we got here we successfully opened the vdex files.
1494 return true;
1495}
1496
1497// Opens the output oat file for the given apk.
1498// If successful it stores the output path into out_oat_path and returns true.
1499Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001500 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1501 char* out_oat_path) {
1502 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001503 return Dex2oatFileWrapper();
1504 }
1505 const std::string out_oat_path_str(out_oat_path);
1506 Dex2oatFileWrapper wrapper_fd(
1507 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1508 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1509 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001510 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001511 } else if (!set_permissions_and_ownership(
1512 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001513 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1514 wrapper_fd.reset(-1);
1515 }
1516 return wrapper_fd;
1517}
1518
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001519// Creates RDONLY fds for oat and vdex files, if exist.
1520// Returns false if it fails to create oat out path for the given apk path.
1521// Note that the method returns true even if the files could not be opened.
1522bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1523 const std::string& oat_dir,
1524 const std::string& instruction_set,
1525 bool is_secondary_dex,
1526 unique_fd* oat_file_fd,
1527 unique_fd* vdex_file_fd) {
1528 char oat_path[PKG_PATH_MAX];
1529 if (!create_oat_out_path(apk_path.c_str(),
1530 instruction_set.c_str(),
1531 oat_dir.c_str(),
1532 is_secondary_dex,
1533 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001534 LOG(ERROR) << "Could not create oat out path for "
1535 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001536 return false;
1537 }
1538 oat_file_fd->reset(open(oat_path, O_RDONLY));
1539 if (oat_file_fd->get() < 0) {
1540 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1541 }
1542
1543 std::string vdex_filename = create_vdex_filename(oat_path);
1544 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1545 if (vdex_file_fd->get() < 0) {
1546 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1547 }
1548
1549 return true;
1550}
1551
Calin Juravle7a570e82017-01-14 16:23:30 -08001552// Updates the access times of out_oat_path based on those from apk_path.
1553void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1554 struct stat input_stat;
1555 memset(&input_stat, 0, sizeof(input_stat));
1556 if (stat(apk_path, &input_stat) != 0) {
1557 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1558 return;
1559 }
1560
1561 struct utimbuf ut;
1562 ut.actime = input_stat.st_atime;
1563 ut.modtime = input_stat.st_mtime;
1564 if (utime(out_oat_path, &ut) != 0) {
1565 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1566 }
1567}
1568
Calin Juravle80a21252017-01-17 14:43:25 -08001569// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001570// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1571// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1572// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001573static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1574 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1575 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001576 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001577 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001578 const char* dexoptanalyzer_bin =
1579 is_debug_runtime()
1580 ? "/system/bin/dexoptanalyzerd"
1581 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001582 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1583
Calin Juravled23dee72017-07-06 16:29:11 -07001584 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1585 LOG(ERROR) << "Instruction set " << instruction_set
1586 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001587 return;
1588 }
1589
Calin Juravled23dee72017-07-06 16:29:11 -07001590 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001591 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1592 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1593 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001594 std::string isa_arg = "--isa=" + instruction_set;
1595 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001596 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001597 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001598 std::string class_loader_context_arg = "--class-loader-context=";
1599 if (class_loader_context != nullptr) {
1600 class_loader_context_arg += class_loader_context;
1601 }
Calin Juravle80a21252017-01-17 14:43:25 -08001602
Calin Juravle80a21252017-01-17 14:43:25 -08001603 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001604 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001605 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001606 (vdex_fd >= 0 ? 1 : 0) +
1607 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001608 (downgrade ? 1 : 0) +
1609 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001610 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001611 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001612 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001613 argv[i++] = dex_file_arg.c_str();
1614 argv[i++] = isa_arg.c_str();
1615 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001616 if (oat_fd >= 0) {
1617 argv[i++] = oat_fd_arg.c_str();
1618 }
1619 if (vdex_fd >= 0) {
1620 argv[i++] = vdex_fd_arg.c_str();
1621 }
1622 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001623 if (profile_was_updated) {
1624 argv[i++] = assume_profile_changed;
1625 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001626 if (downgrade) {
1627 argv[i++] = downgrade_flag;
1628 }
Calin Juravle58cab072017-09-12 01:02:26 -07001629 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001630 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001631 }
Yi Kong954cf642018-07-17 16:16:24 -07001632 argv[i] = nullptr;
Calin Juravle80a21252017-01-17 14:43:25 -08001633
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001634 execv(dexoptanalyzer_bin, (char * const *)argv);
1635 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001636}
1637
1638// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001639static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001640 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001641 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001642 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001643 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001644 return false;
1645 }
Calin Juravle114f0812017-03-08 19:05:07 -08001646 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001647
Calin Juravle80a21252017-01-17 14:43:25 -08001648 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001649 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1650 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001651 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001652 return false;
1653 }
1654
1655 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001656 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001657
Calin Juravle7d765462017-09-04 15:57:10 -07001658 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001659 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001660 return false;
1661 }
1662
1663 return true;
1664}
1665
Calin Juravle7d765462017-09-04 15:57:10 -07001666// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1667// secondary dex files. This return codes are returned by the child process created for
1668// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001669
Andreas Gampe194fe422018-02-28 20:16:19 -08001670enum DexoptAnalyzerSkipCodes {
1671 // The dexoptanalyzer was not invoked because of validation or IO errors.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001672 // Specific errors are encoded in the name.
1673 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1674 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1675 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1676 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1677 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
Andreas Gampe194fe422018-02-28 20:16:19 -08001678 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001679 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
Andreas Gampe194fe422018-02-28 20:16:19 -08001680};
Calin Juravle7d765462017-09-04 15:57:10 -07001681
1682// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001683// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1684// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001685// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1686// of dexoptanalyzer.
1687static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Andreas Gampe194fe422018-02-28 20:16:19 -08001688 int* dexopt_needed_out, std::string* error_msg) {
Calin Juravle80a21252017-01-17 14:43:25 -08001689 // The result values are defined in dexoptanalyzer.
1690 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001691 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001692 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001693 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001694 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001695 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001696 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Vladimir Marko1752a112018-09-03 18:15:16 +01001697 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001698 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; 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
Andreas Gampe194fe422018-02-28 20:16:19 -08001701 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1702 " Expected odex file status for secondary dex %s"
1703 " : dexoptanalyzer result=%d",
1704 dex_path.c_str(),
1705 result);
Calin Juravle80a21252017-01-17 14:43:25 -08001706 return false;
Andreas Gampe194fe422018-02-28 20:16:19 -08001707 }
1708
1709 // Use a second switch for enum switch-case analysis.
1710 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001711 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
Calin Juravle7d765462017-09-04 15:57:10 -07001712 // If the file does not exist there's no need for dexopt.
1713 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1714 return true;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001715
1716 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1717 *error_msg = "Dexoptanalyzer path validation failed";
1718 return false;
1719 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1720 *error_msg = "Dexoptanalyzer open zip failed";
1721 return false;
1722 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1723 *error_msg = "Dexoptanalyzer dir preparation failed";
1724 return false;
1725 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1726 *error_msg = "Dexoptanalyzer open output failed";
1727 return false;
1728 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1729 *error_msg = "Dexoptanalyzer failed to execute";
Calin Juravle80a21252017-01-17 14:43:25 -08001730 return false;
1731 }
Andreas Gampe194fe422018-02-28 20:16:19 -08001732
1733 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1734 dex_path.c_str(),
1735 result);
1736 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001737}
1738
Calin Juravle7d765462017-09-04 15:57:10 -07001739enum SecondaryDexAccess {
1740 kSecondaryDexAccessReadOk = 0,
1741 kSecondaryDexAccessDoesNotExist = 1,
1742 kSecondaryDexAccessPermissionError = 2,
1743 kSecondaryDexAccessIOError = 3
1744};
1745
1746static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1747 // Check if the path exists and can be read. If not, there's nothing to do.
1748 if (access(dex_path.c_str(), R_OK) == 0) {
1749 return kSecondaryDexAccessReadOk;
1750 } else {
1751 if (errno == ENOENT) {
1752 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1753 return kSecondaryDexAccessDoesNotExist;
1754 } else {
1755 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1756 return errno == EACCES
1757 ? kSecondaryDexAccessPermissionError
1758 : kSecondaryDexAccessIOError;
1759 }
1760 }
1761}
1762
1763static bool is_file_public(const std::string& filename) {
1764 struct stat file_stat;
1765 if (stat(filename.c_str(), &file_stat) == 0) {
1766 return (file_stat.st_mode & S_IROTH) != 0;
1767 }
1768 return false;
1769}
1770
1771// Create the oat file structure for the secondary dex 'dex_path' and assign
1772// the individual path component to the 'out_' parameters.
1773static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
Andreas Gampe194fe422018-02-28 20:16:19 -08001774 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001775 size_t dirIndex = dex_path.rfind('/');
1776 if (dirIndex == std::string::npos) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001777 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001778 return false;
1779 }
1780 // TODO(calin): we have similar computations in at lest 3 other places
1781 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1782 // using string append.
1783 std::string apk_dir = dex_path.substr(0, dirIndex);
1784 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1785 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1786
1787 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1788 /*is_secondary_dex*/true, out_oat_path)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001789 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
Calin Juravle7d765462017-09-04 15:57:10 -07001790 return false;
1791 }
1792 return true;
1793}
1794
1795// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1796// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
Andreas Gampe194fe422018-02-28 20:16:19 -08001797static bool validate_dexopt_storage_flags(int dexopt_flags,
1798 int* out_storage_flag,
1799 std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001800 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1801 *out_storage_flag = FLAG_STORAGE_CE;
1802 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001803 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
Calin Juravle7d765462017-09-04 15:57:10 -07001804 return false;
1805 }
1806 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1807 *out_storage_flag = FLAG_STORAGE_DE;
1808 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001809 *error_msg = "Secondary dex storage flag must be set";
Calin Juravle7d765462017-09-04 15:57:10 -07001810 return false;
1811 }
1812 return true;
1813}
1814
Calin Juravlec9eab382017-01-25 01:17:17 -08001815// 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 -08001816// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1817// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001818// When returning true, the output parameters will be:
1819// - is_public_out: whether or not the oat file should not be made public
1820// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1821// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001822static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001823 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001824 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Andreas Gampe194fe422018-02-28 20:16:19 -08001825 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1826 /* out */ std::string* error_msg) {
Calin Juravle7d765462017-09-04 15:57:10 -07001827 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001828 int storage_flag;
Andreas Gampe194fe422018-02-28 20:16:19 -08001829 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1830 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001831 return false;
1832 }
Calin Juravle7d765462017-09-04 15:57:10 -07001833 // Compute the oat dir as it's not easy to extract it from the child computation.
1834 char oat_path[PKG_PATH_MAX];
1835 char oat_dir[PKG_PATH_MAX];
1836 char oat_isa_dir[PKG_PATH_MAX];
1837 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08001838 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1839 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
Calin Juravled23dee72017-07-06 16:29:11 -07001840 return false;
1841 }
Calin Juravle7d765462017-09-04 15:57:10 -07001842 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001843
Calin Juravle80a21252017-01-17 14:43:25 -08001844 pid_t pid = fork();
1845 if (pid == 0) {
1846 // child -- drop privileges before continuing.
1847 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001848
1849 // Validate the path structure.
1850 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1851 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001852 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
Calin Juravle7d765462017-09-04 15:57:10 -07001853 }
1854
1855 // Open the dex file.
1856 unique_fd zip_fd;
1857 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1858 if (zip_fd.get() < 0) {
1859 if (errno == ENOENT) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001860 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
Calin Juravle7d765462017-09-04 15:57:10 -07001861 } else {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001862 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
Calin Juravle7d765462017-09-04 15:57:10 -07001863 }
1864 }
1865
1866 // Prepare the oat directories.
1867 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001868 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
Calin Juravle7d765462017-09-04 15:57:10 -07001869 }
1870
1871 // Open the vdex/oat files if any.
1872 unique_fd oat_file_fd;
1873 unique_fd vdex_file_fd;
1874 if (!maybe_open_oat_and_vdex_file(dex_path,
1875 *oat_dir_out,
1876 instruction_set,
1877 true /* is_secondary_dex */,
1878 &oat_file_fd,
1879 &vdex_file_fd)) {
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001880 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
Calin Juravle7d765462017-09-04 15:57:10 -07001881 }
1882
1883 // Analyze profiles.
Calin Juravle824a64d2018-01-18 20:23:17 -08001884 bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
1885 /*is_secondary_dex*/true);
Calin Juravle7d765462017-09-04 15:57:10 -07001886
1887 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001888 exec_dexoptanalyzer(dex_path,
1889 vdex_file_fd.get(),
1890 oat_file_fd.get(),
1891 zip_fd.get(),
1892 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001893 compiler_filter, profile_was_updated,
1894 downgrade,
1895 class_loader_context);
1896 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001897 _exit(kSecondaryDexDexoptAnalyzerSkippedFailExec);
Calin Juravle80a21252017-01-17 14:43:25 -08001898 }
1899
1900 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001901 int result = wait_child(pid);
1902 if (!WIFEXITED(result)) {
Andreas Gampe194fe422018-02-28 20:16:19 -08001903 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1904 dex_path.c_str(),
1905 result);
1906 LOG(ERROR) << *error_msg;
Calin Juravle80a21252017-01-17 14:43:25 -08001907 return false;
1908 }
1909 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001910 // Check that we successfully executed dexoptanalyzer.
Andreas Gampe194fe422018-02-28 20:16:19 -08001911 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1912 result,
1913 dexopt_needed_out,
1914 error_msg);
1915 if (!success) {
1916 LOG(ERROR) << *error_msg;
1917 }
Calin Juravle7d765462017-09-04 15:57:10 -07001918
1919 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1920
Calin Juravle80a21252017-01-17 14:43:25 -08001921 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001922 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1923 // makes the code simpler; force compilation is only needed during tests).
1924 if (success &&
Andreas Gampe3008bbe2018-02-28 20:24:48 -08001925 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
Calin Juravle7d765462017-09-04 15:57:10 -07001926 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001927 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1928 }
1929
Calin Juravle7d765462017-09-04 15:57:10 -07001930 // Check if we should make the oat file public.
1931 // Note that if the dex file is not public the compiled code cannot be made public.
1932 // It is ok to check this flag outside in the parent process.
1933 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1934
Calin Juravle80a21252017-01-17 14:43:25 -08001935 return success;
1936}
1937
Andreas Gampefa2dadd2018-02-28 19:52:47 -08001938static std::string format_dexopt_error(int status, const char* dex_path) {
1939 if (WIFEXITED(status)) {
1940 int int_code = WEXITSTATUS(status);
1941 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1942 if (code_name != nullptr) {
1943 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1944 }
1945 }
1946 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
Andreas Gampe023b2242018-02-28 16:03:25 -08001947}
1948
Calin Juravlec9eab382017-01-25 01:17:17 -08001949int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001950 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001951 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Calin Juravle62c5a372018-02-01 17:03:23 +00001952 bool downgrade, int target_sdk_version, const char* profile_name,
Andreas Gampe023b2242018-02-28 16:03:25 -08001953 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001954 CHECK(pkgname != nullptr);
1955 CHECK(pkgname[0] != 0);
Andreas Gampe023b2242018-02-28 16:03:25 -08001956 CHECK(error_msg != nullptr);
Andreas Gamped32eec22018-02-28 16:02:51 -08001957 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1958 << "dexopt flags contains unknown fields: " << dexopt_flags;
Calin Juravle7a570e82017-01-14 16:23:30 -08001959
Calin Juravled23dee72017-07-06 16:29:11 -07001960 if (!validate_dex_path_size(dex_path)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001961 *error_msg = StringPrintf("Failed to validate %s", dex_path);
Calin Juravle52c45822017-07-13 22:50:21 -07001962 return -1;
1963 }
1964
1965 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
Andreas Gampe023b2242018-02-28 16:03:25 -08001966 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1967 class_loader_context);
1968 LOG(ERROR) << *error_msg;
Calin Juravle52c45822017-07-13 22:50:21 -07001969 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001970 }
1971
Calin Juravleebc8a792017-04-04 20:21:05 -07001972 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001973 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1974 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1975 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001976 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001977 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001978 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08001979 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07001980 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001981
1982 // Check if we're dealing with a secondary dex file and if we need to compile it.
1983 std::string oat_dir_str;
1984 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001985 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001986 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Andreas Gampe194fe422018-02-28 20:16:19 -08001987 downgrade, class_loader_context, error_msg)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001988 oat_dir = oat_dir_str.c_str();
1989 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1990 return 0; // Nothing to do, report success.
1991 }
1992 } else {
Andreas Gampe194fe422018-02-28 20:16:19 -08001993 if (error_msg->empty()) { // TODO: Make this a CHECK.
1994 *error_msg = "Failed processing secondary.";
1995 }
Calin Juravle80a21252017-01-17 14:43:25 -08001996 return -1; // We had an error, logged in the process method.
1997 }
1998 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001999 // Currently these flags are only use for secondary dex files.
2000 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08002001 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
2002 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
2003 }
Calin Juravle7a570e82017-01-14 16:23:30 -08002004
2005 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002006 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08002007 if (input_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002008 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
2009 LOG(ERROR) << *error_msg;
Calin Juravle7a570e82017-01-14 16:23:30 -08002010 return -1;
2011 }
2012
2013 // Create the output OAT file.
2014 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08002015 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08002016 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08002017 if (out_oat_fd.get() < 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002018 *error_msg = "Could not open out oat file.";
Calin Juravle7a570e82017-01-14 16:23:30 -08002019 return -1;
2020 }
2021
2022 // Open vdex files.
2023 Dex2oatFileWrapper in_vdex_fd;
2024 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07002025 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
2026 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002027 *error_msg = "Could not open vdex files.";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002028 return -1;
2029 }
2030
Calin Juravlecb556e32017-04-04 20:22:50 -07002031 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
2032 // selinux context (we generate them on the fly during the dexopt invocation and they don't
2033 // fully inherit their parent context).
2034 // Note that for primary apk the oat files are created before, in a separate installd
2035 // call which also does the restorecon. TODO(calin): unify the paths.
2036 if (is_secondary_dex) {
2037 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
2038 SELINUX_ANDROID_RESTORECON_RECURSE)) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002039 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
2040 LOG(ERROR) << *error_msg;
Calin Juravlecb556e32017-04-04 20:22:50 -07002041 return -1;
2042 }
2043 }
2044
Jeff Sharkey90aff262016-12-12 14:28:24 -07002045 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08002046 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002047
Calin Juravle7a570e82017-01-14 16:23:30 -08002048 // Create the app image file if needed.
Mathieu Chartier1dc3dfa2018-03-12 17:55:06 -07002049 Dex2oatFileWrapper image_fd = maybe_open_app_image(
2050 out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002051
Calin Juravle7a570e82017-01-14 16:23:30 -08002052 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08002053 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
Calin Juravle824a64d2018-01-18 20:23:17 -08002054 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08002055
Calin Juravle62c5a372018-02-01 17:03:23 +00002056 unique_fd dex_metadata_fd;
2057 if (dex_metadata_path != nullptr) {
2058 dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
2059 if (dex_metadata_fd.get() < 0) {
2060 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
2061 }
2062 }
2063
Andreas Gampe023b2242018-02-28 16:03:25 -08002064 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002065
2066 pid_t pid = fork();
2067 if (pid == 0) {
2068 /* child -- drop privileges before continuing */
2069 drop_capabilities(uid);
2070
Richard Uhler76cc0272016-12-08 10:46:35 +00002071 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002072 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002073 PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002074 _exit(DexoptReturnCodes::kFlock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002075 }
2076
Richard Uhler76cc0272016-12-08 10:46:35 +00002077 run_dex2oat(input_fd.get(),
2078 out_oat_fd.get(),
2079 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08002080 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00002081 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07002082 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00002083 out_oat_path,
2084 swap_fd.get(),
2085 instruction_set,
2086 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00002087 debuggable,
2088 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07002089 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00002090 reference_profile_fd.get(),
David Brazdil570d3982018-01-16 20:15:43 +00002091 class_loader_context,
David Brazdil7fcbb812018-01-17 17:05:40 +00002092 target_sdk_version,
Calin Juravle62c5a372018-02-01 17:03:23 +00002093 enable_hidden_api_checks,
Mathieu Chartierf69c2f72018-03-06 13:55:58 -08002094 generate_compact_dex,
Calin Juravle2efc4022018-02-13 18:31:32 -08002095 dex_metadata_fd.get(),
2096 compilation_reason);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002097 } else {
2098 int res = wait_child(pid);
2099 if (res == 0) {
Andreas Gampe023b2242018-02-28 16:03:25 -08002100 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
Jeff Sharkey90aff262016-12-12 14:28:24 -07002101 } else {
Andreas Gampe023b2242018-02-28 16:03:25 -08002102 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
2103 << std::hex << std::setw(4) << res << ", process failed";
2104 *error_msg = format_dexopt_error(res, dex_path);
Andreas Gampe013f02e2017-03-20 18:36:54 -07002105 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002106 }
2107 }
2108
Calin Juravlec9eab382017-01-25 01:17:17 -08002109 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002110
2111 // We've been successful, don't delete output.
2112 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08002113 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002114 image_fd.SetCleanup(false);
2115 reference_profile_fd.SetCleanup(false);
2116
2117 return 0;
2118}
2119
Calin Juravlec9eab382017-01-25 01:17:17 -08002120// Try to remove the given directory. Log an error if the directory exists
2121// and is empty but could not be removed.
2122static bool rmdir_if_empty(const char* dir) {
2123 if (rmdir(dir) == 0) {
2124 return true;
2125 }
2126 if (errno == ENOENT || errno == ENOTEMPTY) {
2127 return true;
2128 }
2129 PLOG(ERROR) << "Failed to remove dir: " << dir;
2130 return false;
2131}
2132
2133// Try to unlink the given file. Log an error if the file exists and could not
2134// be unlinked.
2135static bool unlink_if_exists(const std::string& file) {
2136 if (unlink(file.c_str()) == 0) {
2137 return true;
2138 }
2139 if (errno == ENOENT) {
2140 return true;
2141
2142 }
2143 PLOG(ERROR) << "Could not unlink: " << file;
2144 return false;
2145}
2146
Calin Juravle7d765462017-09-04 15:57:10 -07002147enum ReconcileSecondaryDexResult {
2148 kReconcileSecondaryDexExists = 0,
2149 kReconcileSecondaryDexCleanedUp = 1,
2150 kReconcileSecondaryDexValidationError = 2,
2151 kReconcileSecondaryDexCleanUpError = 3,
2152 kReconcileSecondaryDexAccessIOError = 4,
2153};
Calin Juravlec9eab382017-01-25 01:17:17 -08002154
2155// Reconcile the secondary dex 'dex_path' and its generated oat files.
2156// Return true if all the parameters are valid and the secondary dex file was
2157// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
2158// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
2159// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
2160// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
2161// Return false if there were errors during processing. In this case
2162// out_secondary_dex_exists will be set to false.
2163bool reconcile_secondary_dex_file(const std::string& dex_path,
2164 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
2165 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2166 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07002167 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08002168 if (isas.size() == 0) {
2169 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
2170 return false;
2171 }
2172
Calin Juravle7d765462017-09-04 15:57:10 -07002173 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2174 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
2175 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08002176 return false;
2177 }
2178
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002179 // As a security measure we want to unlink art artifacts with the reduced capabilities
2180 // of the package user id. So we fork and drop capabilities in the child.
2181 pid_t pid = fork();
2182 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07002183 /* child -- drop privileges before continuing */
2184 drop_capabilities(uid);
2185
2186 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2187 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
2188 uid, storage_flag)) {
2189 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2190 _exit(kReconcileSecondaryDexValidationError);
2191 }
2192
2193 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2194 switch (access_check) {
2195 case kSecondaryDexAccessDoesNotExist:
2196 // File does not exist. Proceed with cleaning.
2197 break;
2198 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2199 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2200 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2201 default:
2202 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2203 _exit(kReconcileSecondaryDexValidationError);
2204 }
2205
2206 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002207 char oat_path[PKG_PATH_MAX];
2208 char oat_dir[PKG_PATH_MAX];
2209 char oat_isa_dir[PKG_PATH_MAX];
2210 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002211 for (size_t i = 0; i < isas.size(); i++) {
Andreas Gampe194fe422018-02-28 20:16:19 -08002212 std::string error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002213 if (!create_secondary_dex_oat_layout(
Andreas Gampe194fe422018-02-28 20:16:19 -08002214 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
2215 LOG(ERROR) << error_msg;
Calin Juravle7d765462017-09-04 15:57:10 -07002216 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002217 }
Calin Juravle51314092017-05-18 15:33:05 -07002218
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002219 // Delete oat/vdex/art files.
2220 result = unlink_if_exists(oat_path) && result;
2221 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2222 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002223
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002224 // Delete profiles.
2225 std::string current_profile = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002226 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002227 std::string reference_profile = create_reference_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -08002228 pkgname, dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002229 result = unlink_if_exists(current_profile) && result;
2230 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002231
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002232 // We upgraded once the location of current profile for secondary dex files.
2233 // Check for any previous left-overs and remove them as well.
2234 std::string old_current_profile = dex_path + ".prof";
2235 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002236
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002237 // Try removing the directories as well, they might be empty.
2238 result = rmdir_if_empty(oat_isa_dir) && result;
2239 result = rmdir_if_empty(oat_dir) && result;
2240 }
Calin Juravle7d765462017-09-04 15:57:10 -07002241 if (!result) {
2242 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2243 }
2244 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002245 }
2246
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002247 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002248 if (!WIFEXITED(return_code)) {
2249 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2250 } else {
2251 return_code = WEXITSTATUS(return_code);
2252 }
2253
2254 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2255
2256 switch (return_code) {
2257 case kReconcileSecondaryDexCleanedUp:
2258 case kReconcileSecondaryDexValidationError:
2259 // If we couldn't validate assume the dex file does not exist.
2260 // This will purge the entry from the PM records.
2261 *out_secondary_dex_exists = false;
2262 return true;
2263 case kReconcileSecondaryDexExists:
2264 *out_secondary_dex_exists = true;
2265 return true;
2266 case kReconcileSecondaryDexAccessIOError:
2267 // We had an access IO error.
2268 // Return false so that we can try again.
2269 // The value of out_secondary_dex_exists does not matter in this case and by convention
2270 // is set to false.
2271 *out_secondary_dex_exists = false;
2272 return false;
2273 default:
2274 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2275 *out_secondary_dex_exists = false;
2276 return false;
2277 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002278}
2279
Alan Stokesa25d90c2017-10-16 10:56:00 +01002280// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2281// Returns true if all parameters are valid and the hash successfully computed and stored in
2282// out_secondary_dex_hash.
2283// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2284// the app.
2285// For any other errors (e.g. if any of the parameters are invalid) returns false.
2286bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2287 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2288 std::vector<uint8_t>* out_secondary_dex_hash) {
2289 out_secondary_dex_hash->clear();
2290
2291 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2292
2293 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2294 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2295 << storage_flag;
2296 return false;
2297 }
2298
2299 // Pipe to get the hash result back from our child process.
2300 unique_fd pipe_read, pipe_write;
2301 if (!Pipe(&pipe_read, &pipe_write)) {
2302 PLOG(ERROR) << "Failed to create pipe";
2303 return false;
2304 }
2305
2306 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2307 // access data the app itself can access.
2308 pid_t pid = fork();
2309 if (pid == 0) {
2310 // child -- drop privileges before continuing
2311 drop_capabilities(uid);
2312 pipe_read.reset();
2313
2314 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2315 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002316 _exit(DexoptReturnCodes::kHashValidatePath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002317 }
2318
2319 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2320 if (fd == -1) {
2321 if (errno == EACCES || errno == ENOENT) {
2322 // Not treated as an error.
2323 _exit(0);
2324 }
2325 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002326 _exit(DexoptReturnCodes::kHashOpenPath);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002327 }
2328
2329 SHA256_CTX ctx;
2330 SHA256_Init(&ctx);
2331
2332 std::vector<uint8_t> buffer(65536);
2333 while (true) {
2334 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2335 if (bytes_read == 0) {
2336 break;
2337 } else if (bytes_read == -1) {
2338 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002339 _exit(DexoptReturnCodes::kHashReadDex);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002340 }
2341
2342 SHA256_Update(&ctx, buffer.data(), bytes_read);
2343 }
2344
2345 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2346 SHA256_Final(hash.data(), &ctx);
2347 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
Andreas Gampefa2dadd2018-02-28 19:52:47 -08002348 _exit(DexoptReturnCodes::kHashWrite);
Alan Stokesa25d90c2017-10-16 10:56:00 +01002349 }
2350
2351 _exit(0);
2352 }
2353
2354 // parent
2355 pipe_write.reset();
2356
2357 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2358 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2359 out_secondary_dex_hash->clear();
2360 }
2361 return wait_child(pid) == 0;
2362}
2363
Jeff Sharkey90aff262016-12-12 14:28:24 -07002364// Helper for move_ab, so that we can have common failure-case cleanup.
2365static bool unlink_and_rename(const char* from, const char* to) {
2366 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2367 // return a failure.
2368 struct stat s;
2369 if (stat(to, &s) == 0) {
2370 if (!S_ISREG(s.st_mode)) {
2371 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2372 return false;
2373 }
2374 if (unlink(to) != 0) {
2375 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2376 return false;
2377 }
2378 } else {
2379 // This may be a permission problem. We could investigate the error code, but we'll just
2380 // let the rename failure do the work for us.
2381 }
2382
2383 // Try to rename "to" to "from."
2384 if (rename(from, to) != 0) {
2385 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2386 return false;
2387 }
2388 return true;
2389}
2390
2391// Move/rename a B artifact (from) to an A artifact (to).
2392static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2393 // Check whether B exists.
2394 {
2395 struct stat s;
2396 if (stat(b_path.c_str(), &s) != 0) {
2397 // Silently ignore for now. The service calling this isn't smart enough to understand
2398 // lack of artifacts at the moment.
2399 return false;
2400 }
2401 if (!S_ISREG(s.st_mode)) {
2402 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2403 // Try to unlink, but swallow errors.
2404 unlink(b_path.c_str());
2405 return false;
2406 }
2407 }
2408
2409 // Rename B to A.
2410 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2411 // Delete the b_path so we don't try again (or fail earlier).
2412 if (unlink(b_path.c_str()) != 0) {
2413 PLOG(ERROR) << "Could not unlink " << b_path;
2414 }
2415
2416 return false;
2417 }
2418
2419 return true;
2420}
2421
2422bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2423 // Get the current slot suffix. No suffix, no A/B.
2424 std::string slot_suffix;
2425 {
2426 char buf[kPropertyValueMax];
2427 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2428 return false;
2429 }
2430 slot_suffix = buf;
2431
2432 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2433 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2434 return false;
2435 }
2436 }
2437
2438 // Validate other inputs.
2439 if (validate_apk_path(apk_path) != 0) {
2440 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2441 return false;
2442 }
2443 if (validate_apk_path(oat_dir) != 0) {
2444 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2445 return false;
2446 }
2447
2448 char a_path[PKG_PATH_MAX];
2449 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2450 return false;
2451 }
2452 const std::string a_vdex_path = create_vdex_filename(a_path);
2453 const std::string a_image_path = create_image_filename(a_path);
2454
2455 // B path = A path + slot suffix.
2456 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2457 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2458 const std::string b_image_path = StringPrintf("%s.%s",
2459 a_image_path.c_str(),
2460 slot_suffix.c_str());
2461
2462 bool success = true;
2463 if (move_ab_path(b_path, a_path)) {
2464 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2465 // Note: we can live without an app image. As such, ignore failure to move the image file.
2466 // If we decide to require the app image, or the app image being moved correctly,
2467 // then change accordingly.
2468 constexpr bool kIgnoreAppImageFailure = true;
2469
2470 if (!a_image_path.empty()) {
2471 if (!move_ab_path(b_image_path, a_image_path)) {
2472 unlink(a_image_path.c_str());
2473 if (!kIgnoreAppImageFailure) {
2474 success = false;
2475 }
2476 }
2477 }
2478 } else {
2479 // Cleanup: delete B image, ignore errors.
2480 unlink(b_image_path.c_str());
2481 success = false;
2482 }
2483 } else {
2484 // Cleanup: delete B image, ignore errors.
2485 unlink(b_vdex_path.c_str());
2486 unlink(b_image_path.c_str());
2487 success = false;
2488 }
2489 return success;
2490}
2491
2492bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2493 // Delete the oat/odex file.
2494 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002495 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002496 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002497 return false;
2498 }
2499
2500 // In case of a permission failure report the issue. Otherwise just print a warning.
2501 auto unlink_and_check = [](const char* path) -> bool {
2502 int result = unlink(path);
2503 if (result != 0) {
2504 if (errno == EACCES || errno == EPERM) {
2505 PLOG(ERROR) << "Could not unlink " << path;
2506 return false;
2507 }
2508 PLOG(WARNING) << "Could not unlink " << path;
2509 }
2510 return true;
2511 };
2512
2513 // Delete the oat/odex file.
2514 bool return_value_oat = unlink_and_check(out_path);
2515
2516 // Derive and delete the app image.
2517 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2518
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002519 // Derive and delete the vdex file.
2520 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2521
Jeff Sharkey90aff262016-12-12 14:28:24 -07002522 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002523 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002524}
2525
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002526static bool is_absolute_path(const std::string& path) {
2527 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2528 LOG(ERROR) << "Invalid absolute path " << path;
2529 return false;
2530 } else {
2531 return true;
2532 }
2533}
2534
2535static bool is_valid_instruction_set(const std::string& instruction_set) {
2536 // TODO: add explicit whitelisting of instruction sets
2537 if (instruction_set.find('/') != std::string::npos) {
2538 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2539 return false;
2540 } else {
2541 return true;
2542 }
2543}
2544
2545bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2546 const char *apk_path, const char *instruction_set) {
2547 std::string oat_dir_ = oat_dir;
2548 std::string apk_path_ = apk_path;
2549 std::string instruction_set_ = instruction_set;
2550
2551 if (!is_absolute_path(oat_dir_)) return false;
2552 if (!is_absolute_path(apk_path_)) return false;
2553 if (!is_valid_instruction_set(instruction_set_)) return false;
2554
2555 std::string::size_type end = apk_path_.rfind('.');
2556 std::string::size_type start = apk_path_.rfind('/', end);
2557 if (end == std::string::npos || start == std::string::npos) {
2558 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2559 return false;
2560 }
2561
2562 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2563 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2564 const char* res = res_.c_str();
2565 if (strlen(res) >= PKG_PATH_MAX) {
2566 LOG(ERROR) << "Result too large";
2567 return false;
2568 } else {
2569 strlcpy(path, res, PKG_PATH_MAX);
2570 return true;
2571 }
2572}
2573
2574bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2575 const char *instruction_set) {
2576 std::string apk_path_ = apk_path;
2577 std::string instruction_set_ = instruction_set;
2578
2579 if (!is_absolute_path(apk_path_)) return false;
2580 if (!is_valid_instruction_set(instruction_set_)) return false;
2581
2582 std::string::size_type end = apk_path_.rfind('.');
2583 std::string::size_type start = apk_path_.rfind('/', end);
2584 if (end == std::string::npos || start == std::string::npos) {
2585 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2586 return false;
2587 }
2588
2589 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2590 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2591}
2592
2593bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2594 const char *instruction_set) {
2595 std::string src_ = src;
2596 std::string instruction_set_ = instruction_set;
2597
2598 if (!is_absolute_path(src_)) return false;
2599 if (!is_valid_instruction_set(instruction_set_)) return false;
2600
2601 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2602 if (*it == '/') {
2603 *it = '@';
2604 }
2605 }
2606
2607 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2608 + DALVIK_CACHE_POSTFIX;
2609 const char* res = res_.c_str();
2610 if (strlen(res) >= PKG_PATH_MAX) {
2611 LOG(ERROR) << "Result too large";
2612 return false;
2613 } else {
2614 strlcpy(path, res, PKG_PATH_MAX);
2615 return true;
2616 }
2617}
2618
Calin Juravle59f7ab82018-04-27 17:50:23 -07002619bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2620 std::vector<std::string>* dex_locations) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002621 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2622 for (const std::string& elem : classpaths_elems) {
2623 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2624 if (fd < 0) {
2625 PLOG(ERROR) << "Could not open classpath elem " << elem;
2626 return false;
2627 } else {
2628 apk_fds->push_back(std::move(fd));
Calin Juravle59f7ab82018-04-27 17:50:23 -07002629 dex_locations->push_back(elem);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002630 }
2631 }
2632 return true;
2633}
2634
2635static bool create_app_profile_snapshot(int32_t app_id,
2636 const std::string& package_name,
2637 const std::string& profile_name,
2638 const std::string& classpath) {
Calin Juravle29591732017-11-20 17:46:19 -08002639 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2640
Calin Juravle824a64d2018-01-18 20:23:17 -08002641 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
Calin Juravle29591732017-11-20 17:46:19 -08002642 if (snapshot_fd < 0) {
2643 return false;
2644 }
2645
2646 std::vector<unique_fd> profiles_fd;
2647 unique_fd reference_profile_fd;
Calin Juravle824a64d2018-01-18 20:23:17 -08002648 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2649 &profiles_fd, &reference_profile_fd);
Calin Juravle29591732017-11-20 17:46:19 -08002650 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2651 return false;
2652 }
2653
2654 profiles_fd.push_back(std::move(reference_profile_fd));
2655
Calin Juravle0d0a4922018-01-23 19:54:11 -08002656 // Open the class paths elements. These will be used to filter out profile data that does
2657 // not belong to the classpath during merge.
2658 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002659 std::vector<std::string> dex_locations;
2660 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002661 return false;
2662 }
2663
Calin Juravle29591732017-11-20 17:46:19 -08002664 pid_t pid = fork();
2665 if (pid == 0) {
2666 /* child -- drop privileges before continuing */
2667 drop_capabilities(app_shared_gid);
Calin Juravle59f7ab82018-04-27 17:50:23 -07002668 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds, &dex_locations);
Calin Juravle29591732017-11-20 17:46:19 -08002669 }
2670
2671 /* parent */
2672 int return_code = wait_child(pid);
2673 if (!WIFEXITED(return_code)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08002674 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
Calin Juravle29591732017-11-20 17:46:19 -08002675 return false;
2676 }
2677
2678 return true;
2679}
2680
Calin Juravle0d0a4922018-01-23 19:54:11 -08002681static bool create_boot_image_profile_snapshot(const std::string& package_name,
2682 const std::string& profile_name,
2683 const std::string& classpath) {
2684 // The reference profile directory for the android package might not be prepared. Do it now.
2685 const std::string ref_profile_dir =
2686 create_primary_reference_profile_package_dir_path(package_name);
2687 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2688 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2689 return false;
2690 }
2691
2692 // Open and create the snapshot profile.
2693 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2694
2695 // Collect all non empty profiles.
2696 // The collection will traverse all applications profiles and find the non empty files.
2697 // This has the potential of inspecting a large number of files and directories (depending
2698 // on the number of applications and users). So there is a slight increase in the chance
2699 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2700 // fail the snapshot and aggregate whatever profile we could open.
2701 //
2702 // The profile snapshot is a best effort based on available data it's ok if some data
2703 // from some apps is missing. It will be counter productive for the snapshot to fail
2704 // because we could not open or read some of the files.
2705 std::vector<std::string> profiles;
2706 if (!collect_profiles(&profiles)) {
2707 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2708 }
2709
2710 // If we have no profiles return early.
2711 if (profiles.empty()) {
2712 return true;
2713 }
2714
2715 // Open the classpath elements. These will be used to filter out profile data that does
2716 // not belong to the classpath during merge.
2717 std::vector<unique_fd> apk_fds;
Calin Juravle59f7ab82018-04-27 17:50:23 -07002718 std::vector<std::string> dex_locations;
2719 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
Calin Juravle0d0a4922018-01-23 19:54:11 -08002720 return false;
2721 }
2722
2723 // If we could not open any files from the classpath return an error.
2724 if (apk_fds.empty()) {
2725 LOG(ERROR) << "Could not open any of the classpath elements.";
2726 return false;
2727 }
2728
2729 // Aggregate the profiles in batches of kAggregationBatchSize.
2730 // We do this to avoid opening a huge a amount of files.
2731 static constexpr size_t kAggregationBatchSize = 10;
2732
2733 std::vector<unique_fd> profiles_fd;
2734 for (size_t i = 0; i < profiles.size(); ) {
2735 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2736 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
2737 if (fd.get() >= 0) {
2738 profiles_fd.push_back(std::move(fd));
2739 }
2740 }
2741 pid_t pid = fork();
2742 if (pid == 0) {
2743 /* child -- drop privileges before continuing */
2744 drop_capabilities(AID_SYSTEM);
2745
Calin Juravle59f7ab82018-04-27 17:50:23 -07002746 // The introduction of new access flags into boot jars causes them to
2747 // fail dex file verification.
2748 run_profman_merge(profiles_fd, snapshot_fd, &apk_fds, &dex_locations);
Calin Juravle0d0a4922018-01-23 19:54:11 -08002749 }
2750
2751 /* parent */
2752 int return_code = wait_child(pid);
2753 if (!WIFEXITED(return_code)) {
2754 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2755 return false;
2756 }
2757 return true;
2758 }
2759 return true;
2760}
2761
2762bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2763 const std::string& profile_name, const std::string& classpath) {
2764 if (app_id == -1) {
2765 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2766 } else {
2767 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2768 }
2769}
2770
Calin Juravlec3b049e2018-01-18 22:32:58 -08002771bool prepare_app_profile(const std::string& package_name,
2772 userid_t user_id,
2773 appid_t app_id,
2774 const std::string& profile_name,
Calin Juravlef63d4792018-01-30 17:43:34 +00002775 const std::string& code_path,
Calin Juravlec3b049e2018-01-18 22:32:58 -08002776 const std::unique_ptr<std::string>& dex_metadata) {
2777 // Prepare the current profile.
2778 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2779 /*is_secondary_dex*/ false);
2780 uid_t uid = multiuser_get_uid(user_id, app_id);
2781 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2782 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2783 return false;
2784 }
2785
2786 // Check if we need to install the profile from the dex metadata.
2787 if (dex_metadata == nullptr) {
2788 return true;
2789 }
2790
2791 // We have a dex metdata. Merge the profile into the reference profile.
2792 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2793 /*read_write*/ true, /*is_secondary_dex*/ false);
2794 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2795 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
Calin Juravlef63d4792018-01-30 17:43:34 +00002796 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2797 if (apk_fd < 0) {
2798 PLOG(ERROR) << "Could not open code path " << code_path;
2799 return false;
2800 }
Calin Juravlec3b049e2018-01-18 22:32:58 -08002801
2802 pid_t pid = fork();
2803 if (pid == 0) {
2804 /* child -- drop privileges before continuing */
2805 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2806 drop_capabilities(app_shared_gid);
2807
Calin Juravlef63d4792018-01-30 17:43:34 +00002808 // The copy and update takes ownership over the fds.
2809 run_profman_copy_and_update(std::move(dex_metadata_fd),
2810 std::move(ref_profile_fd),
Calin Juravle59f7ab82018-04-27 17:50:23 -07002811 std::move(apk_fd),
2812 code_path);
Calin Juravlec3b049e2018-01-18 22:32:58 -08002813 }
2814
2815 /* parent */
2816 int return_code = wait_child(pid);
2817 if (!WIFEXITED(return_code)) {
2818 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2819 return false;
2820 }
2821 return true;
2822}
2823
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002824} // namespace installd
2825} // namespace android