blob: 84020928282167ab768b78f3654257ee3f01ed23 [file] [log] [blame]
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mark Salyzyna5e161b2016-09-29 08:08:05 -070016#define LOG_TAG "installed"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070017
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
Alan Stokesa25d90c2017-10-16 10:56:00 +010031#include <android-base/file.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070032#include <android-base/logging.h>
Andreas Gampe6a9cf722017-07-24 16:49:10 -070033#include <android-base/properties.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070034#include <android-base/stringprintf.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070035#include <android-base/strings.h>
36#include <android-base/unique_fd.h>
Calin Juravle80a21252017-01-17 14:43:25 -080037#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070038#include <cutils/properties.h>
39#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070040#include <log/log.h> // TODO: Move everything to base/logging.
Alan Stokesa25d90c2017-10-16 10:56:00 +010041#include <openssl/sha.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070042#include <private/android_filesystem_config.h>
Calin Juravlecb556e32017-04-04 20:22:50 -070043#include <selinux/android.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <system/thread_defs.h>
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070045
46#include "dexopt.h"
Jeff Sharkeyc1149c92017-09-21 14:51:09 -060047#include "globals.h"
Jeff Sharkey90aff262016-12-12 14:28:24 -070048#include "installd_deps.h"
49#include "otapreopt_utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050#include "utils.h"
51
Jeff Sharkey90aff262016-12-12 14:28:24 -070052using android::base::EndsWith;
Alan Stokesa25d90c2017-10-16 10:56:00 +010053using android::base::ReadFully;
54using android::base::StringPrintf;
55using android::base::WriteFully;
Calin Juravle1a0af3b2017-03-09 14:33:33 -080056using android::base::unique_fd;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070057
58namespace android {
59namespace installd {
60
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070061// Should minidebug info be included in compiled artifacts? Even if this value is
62// "true," usage might still be conditional to other constraints, e.g., system
63// property overrides.
64static constexpr bool kEnableMinidebugInfo = true;
65
66static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
67static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
68static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -080069static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -070070
Calin Juravle114f0812017-03-08 19:05:07 -080071// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
72struct FreeDelete {
73 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
74 void operator()(const void* ptr) const {
75 free(const_cast<void*>(ptr));
76 }
77};
78
79// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
80template <typename T>
81using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
82
Calin Juravle1a0af3b2017-03-09 14:33:33 -080083static unique_fd invalid_unique_fd() {
84 return unique_fd(-1);
85}
86
Andreas Gampe6a9cf722017-07-24 16:49:10 -070087static bool is_debug_runtime() {
88 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
89}
90
David Sehra3b5ab62017-10-25 14:27:29 -070091static bool is_debuggable_build() {
92 return android::base::GetBoolProperty("ro.debuggable", false);
93}
94
Jeff Sharkey90aff262016-12-12 14:28:24 -070095static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080096 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070097 if (ufd.get() < 0) {
98 if (errno != ENOENT) {
99 PLOG(WARNING) << "Could not open profile " << profile;
100 return false;
101 } else {
102 // Nothing to clear. That's ok.
103 return true;
104 }
105 }
106
107 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
108 if (errno != EWOULDBLOCK) {
109 PLOG(WARNING) << "Error locking profile " << profile;
110 }
111 // This implies that the app owning this profile is running
112 // (and has acquired the lock).
113 //
114 // If we can't acquire the lock bail out since clearing is useless anyway
115 // (the app will write again to the profile).
116 //
117 // Note:
118 // This does not impact the this is not an issue for the profiling correctness.
119 // In case this is needed because of an app upgrade, profiles will still be
120 // eventually cleared by the app itself due to checksum mismatch.
121 // If this is needed because profman advised, then keeping the data around
122 // until the next run is again not an issue.
123 //
124 // If the app attempts to acquire a lock while we've held one here,
125 // it will simply skip the current write cycle.
126 return false;
127 }
128
129 bool truncated = ftruncate(ufd.get(), 0) == 0;
130 if (!truncated) {
131 PLOG(WARNING) << "Could not truncate " << profile;
132 }
133 if (flock(ufd.get(), LOCK_UN) != 0) {
134 PLOG(WARNING) << "Error unlocking profile " << profile;
135 }
136 return truncated;
137}
138
Calin Juravle114f0812017-03-08 19:05:07 -0800139// Clear the reference profile for the given location.
140// The location is the package name for primary apks or the dex path for secondary dex files.
141static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
142 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700143}
144
Calin Juravle114f0812017-03-08 19:05:07 -0800145// Clear the reference profile for the given location.
146// The location is the package name for primary apks or the dex path for secondary dex files.
147static bool clear_current_profile(const std::string& pkgname, userid_t user,
148 bool is_secondary_dex) {
149 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700150}
151
Calin Juravle114f0812017-03-08 19:05:07 -0800152// Clear the reference profile for the primary apk of the given package.
153bool clear_primary_reference_profile(const std::string& pkgname) {
154 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
155}
156
157// Clear all current profile for the primary apk of the given package.
158bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700159 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800160 // 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 -0700161 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
162 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800163 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700164 }
165 return success;
166}
167
Calin Juravle114f0812017-03-08 19:05:07 -0800168// Clear the current profile for the primary apk of the given package and user.
169bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
170 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
171}
172
Jeff Sharkey90aff262016-12-12 14:28:24 -0700173static int split_count(const char *str)
174{
175 char *ctx;
176 int count = 0;
177 char buf[kPropertyValueMax];
178
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600179 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700180 char *pBuf = buf;
181
182 while(strtok_r(pBuf, " ", &ctx) != NULL) {
183 count++;
184 pBuf = NULL;
185 }
186
187 return count;
188}
189
190static int split(char *buf, const char **argv)
191{
192 char *ctx;
193 int count = 0;
194 char *tok;
195 char *pBuf = buf;
196
197 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
198 argv[count++] = tok;
199 pBuf = NULL;
200 }
201
202 return count;
203}
204
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700205static const char* get_location_from_path(const char* path) {
206 static constexpr char kLocationSeparator = '/';
207 const char *location = strrchr(path, kLocationSeparator);
208 if (location == NULL) {
209 return path;
210 } else {
211 // Skip the separator character.
212 return location + 1;
213 }
214}
215
Jeff Sharkey90aff262016-12-12 14:28:24 -0700216static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
217 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100218 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700219 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
David Brazdil52249162018-02-12 18:04:59 -0800220 const char* class_loader_context, int target_sdk_version, bool enable_hidden_api_checks) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700221 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
222
223 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
224 ALOGE("Instruction set %s longer than max length of %d",
225 instruction_set, MAX_INSTRUCTION_SET_LEN);
226 return;
227 }
228
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700229 // Get the relative path to the input file.
230 const char* relative_input_file_name = get_location_from_path(input_file_name);
231
Jeff Sharkey90aff262016-12-12 14:28:24 -0700232 char dex2oat_Xms_flag[kPropertyValueMax];
233 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
234
235 char dex2oat_Xmx_flag[kPropertyValueMax];
236 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
237
238 char dex2oat_threads_buf[kPropertyValueMax];
239 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
240 ? "dalvik.vm.dex2oat-threads"
241 : "dalvik.vm.boot-dex2oat-threads",
242 dex2oat_threads_buf,
243 NULL) > 0;
244 char dex2oat_threads_arg[kPropertyValueMax + 2];
245 if (have_dex2oat_threads_flag) {
246 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
247 }
248
249 char dex2oat_isa_features_key[kPropertyKeyMax];
250 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
251 char dex2oat_isa_features[kPropertyValueMax];
252 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
253 dex2oat_isa_features, NULL) > 0;
254
255 char dex2oat_isa_variant_key[kPropertyKeyMax];
256 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
257 char dex2oat_isa_variant[kPropertyValueMax];
258 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
259 dex2oat_isa_variant, NULL) > 0;
260
261 const char *dex2oat_norelocation = "-Xnorelocate";
262 bool have_dex2oat_relocation_skip_flag = false;
263
264 char dex2oat_flags[kPropertyValueMax];
265 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
266 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
267 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
268
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100269 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700270 char vold_decrypt[kPropertyValueMax];
271 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
272 bool skip_compilation = (have_vold_decrypt &&
273 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
274 (strcmp(vold_decrypt, "1") == 0)));
275
276 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
277
278 char app_image_format[kPropertyValueMax];
279 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
280 bool have_app_image_format =
281 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
282 if (have_app_image_format) {
283 sprintf(image_format_arg, "--image-format=%s", app_image_format);
284 }
285
286 char dex2oat_large_app_threshold[kPropertyValueMax];
287 bool have_dex2oat_large_app_threshold =
288 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
289 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
290 if (have_dex2oat_large_app_threshold) {
291 sprintf(dex2oat_large_app_threshold_arg,
292 "--very-large-app-threshold=%s",
293 dex2oat_large_app_threshold);
294 }
295
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700296 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700297 const char* dex2oat_bin = "/system/bin/dex2oat";
298 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700299 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700300 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
301 dex2oat_bin = kDex2oatDebugPath;
302 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700303
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700304 bool generate_minidebug_info = kEnableMinidebugInfo &&
305 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
306 kMinidebugInfoSystemPropertyDefault);
307
Jeff Sharkey90aff262016-12-12 14:28:24 -0700308 static const char* RUNTIME_ARG = "--runtime-arg";
309
310 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
311
George Burgess IV36cebe772017-01-25 11:52:01 -0800312 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
313 // use arraysize instead.
314 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
315 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
316 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
317 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
318 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
319 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
320 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
321 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
322 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
323 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
324 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
325 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700326 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800327 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700328 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800329 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700330 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
David Brazdil570d3982018-01-16 20:15:43 +0000331 char target_sdk_version_arg[arraysize("-Xtarget-sdk-version:") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700332 char class_loader_context_arg[class_loader_context_size];
333 if (class_loader_context != nullptr) {
334 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
335 class_loader_context);
336 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700337
338 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700339 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700340 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
341 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
342 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
343 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
344 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
345 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
346 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
347 if (swap_fd >= 0) {
348 have_dex2oat_swap_fd = true;
349 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
350 }
351 if (image_fd >= 0) {
352 have_dex2oat_image_fd = true;
353 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
354 }
355
356 if (have_dex2oat_Xms_flag) {
357 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
358 }
359 if (have_dex2oat_Xmx_flag) {
360 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
361 }
David Brazdil570d3982018-01-16 20:15:43 +0000362 sprintf(target_sdk_version_arg, "-Xtarget-sdk-version:%d", target_sdk_version);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700363
364 // Compute compiler filter.
365
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100366 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700367 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600368 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
369 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700370 have_dex2oat_compiler_filter_flag = true;
371 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100372 } else if (compiler_filter != nullptr) {
373 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700374 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100375 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
376 have_dex2oat_compiler_filter_flag = true;
377 } else {
378 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
379 compiler_filter,
380 kPropertyValueMax);
381 }
382 }
383
384 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700385 char dex2oat_compiler_filter_flag[kPropertyValueMax];
386 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
387 dex2oat_compiler_filter_flag, NULL) > 0;
388 if (have_dex2oat_compiler_filter_flag) {
389 sprintf(dex2oat_compiler_filter_arg,
390 "--compiler-filter=%s",
391 dex2oat_compiler_filter_flag);
392 }
393 }
394
395 // Check whether all apps should be compiled debuggable.
396 if (!debuggable) {
397 char prop_buf[kPropertyValueMax];
398 debuggable =
399 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
400 (prop_buf[0] == '1');
401 }
402 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
403 if (profile_fd != -1) {
404 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
405 }
406
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700407 // Get the directory of the apk to pass as a base classpath directory.
408 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
409 std::string apk_dir(input_file_name);
410 unsigned long dir_index = apk_dir.rfind('/');
411 bool has_base_dir = dir_index != std::string::npos;
412 if (has_base_dir) {
413 apk_dir = apk_dir.substr(0, dir_index);
414 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
415 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700416
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700417
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700418 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700419
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800420 // Disable cdex if update input vdex is true since this combination of options is not
421 // supported.
Mathieu Chartier1fb463e2018-01-09 15:16:10 -0800422 // Disable cdex for non-background compiles since we don't want to regress app install until
423 // there are enough benefits to justify the tradeoff.
424 const bool disable_cdex = !background_job_compile || (input_vdex_fd == output_vdex_fd);
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800425
Jeff Sharkey90aff262016-12-12 14:28:24 -0700426 const char* argv[9 // program name, mandatory arguments and the final NULL
427 + (have_dex2oat_isa_variant ? 1 : 0)
428 + (have_dex2oat_isa_features ? 1 : 0)
429 + (have_dex2oat_Xms_flag ? 2 : 0)
430 + (have_dex2oat_Xmx_flag ? 2 : 0)
431 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
432 + (have_dex2oat_threads_flag ? 1 : 0)
433 + (have_dex2oat_swap_fd ? 1 : 0)
434 + (have_dex2oat_image_fd ? 1 : 0)
435 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
436 + (generate_debug_info ? 1 : 0)
437 + (debuggable ? 1 : 0)
438 + (have_app_image_format ? 1 : 0)
439 + dex2oat_flags_count
440 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700441 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700442 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700443 + (have_dex2oat_large_app_threshold ? 1 : 0)
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800444 + (disable_cdex ? 1 : 0)
David Brazdil570d3982018-01-16 20:15:43 +0000445 + (generate_minidebug_info ? 1 : 0)
David Brazdil7fcbb812018-01-17 17:05:40 +0000446 + (target_sdk_version != 0 ? 2 : 0)
David Brazdil52249162018-02-12 18:04:59 -0800447 + (enable_hidden_api_checks ? 2 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700448 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700449 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700450 argv[i++] = zip_fd_arg;
451 argv[i++] = zip_location_arg;
452 argv[i++] = input_vdex_fd_arg;
453 argv[i++] = output_vdex_fd_arg;
454 argv[i++] = oat_fd_arg;
455 argv[i++] = oat_location_arg;
456 argv[i++] = instruction_set_arg;
457 if (have_dex2oat_isa_variant) {
458 argv[i++] = instruction_set_variant_arg;
459 }
460 if (have_dex2oat_isa_features) {
461 argv[i++] = instruction_set_features_arg;
462 }
463 if (have_dex2oat_Xms_flag) {
464 argv[i++] = RUNTIME_ARG;
465 argv[i++] = dex2oat_Xms_arg;
466 }
467 if (have_dex2oat_Xmx_flag) {
468 argv[i++] = RUNTIME_ARG;
469 argv[i++] = dex2oat_Xmx_arg;
470 }
471 if (have_dex2oat_compiler_filter_flag) {
472 argv[i++] = dex2oat_compiler_filter_arg;
473 }
474 if (have_dex2oat_threads_flag) {
475 argv[i++] = dex2oat_threads_arg;
476 }
477 if (have_dex2oat_swap_fd) {
478 argv[i++] = dex2oat_swap_fd;
479 }
480 if (have_dex2oat_image_fd) {
481 argv[i++] = dex2oat_image_fd;
482 }
483 if (generate_debug_info) {
484 argv[i++] = "--generate-debug-info";
485 }
486 if (debuggable) {
487 argv[i++] = "--debuggable";
488 }
489 if (have_app_image_format) {
490 argv[i++] = image_format_arg;
491 }
492 if (have_dex2oat_large_app_threshold) {
493 argv[i++] = dex2oat_large_app_threshold_arg;
494 }
495 if (dex2oat_flags_count) {
496 i += split(dex2oat_flags, argv + i);
497 }
498 if (have_dex2oat_relocation_skip_flag) {
499 argv[i++] = RUNTIME_ARG;
500 argv[i++] = dex2oat_norelocation;
501 }
502 if (profile_fd != -1) {
503 argv[i++] = profile_arg;
504 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700505 if (has_base_dir) {
506 argv[i++] = base_dir;
507 }
Calin Juravle52c45822017-07-13 22:50:21 -0700508 if (class_loader_context != nullptr) {
509 argv[i++] = class_loader_context_arg;
510 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700511 if (generate_minidebug_info) {
512 argv[i++] = kMinidebugDex2oatFlag;
513 }
Mathieu Chartierb41ffcc2018-01-09 00:02:17 -0800514 if (disable_cdex) {
515 argv[i++] = kDisableCompactDexFlag;
516 }
David Brazdil570d3982018-01-16 20:15:43 +0000517 if (target_sdk_version != 0) {
518 argv[i++] = RUNTIME_ARG;
519 argv[i++] = target_sdk_version_arg;
520 }
David Brazdil52249162018-02-12 18:04:59 -0800521 if (enable_hidden_api_checks) {
David Brazdil7fcbb812018-01-17 17:05:40 +0000522 argv[i++] = RUNTIME_ARG;
David Brazdil52249162018-02-12 18:04:59 -0800523 argv[i++] = "-Xhidden-api-checks";
David Brazdil7fcbb812018-01-17 17:05:40 +0000524 }
Calin Juravle52c45822017-07-13 22:50:21 -0700525
Jeff Sharkey90aff262016-12-12 14:28:24 -0700526 // Do not add after dex2oat_flags, they should override others for debugging.
527 argv[i] = NULL;
528
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700529 execv(dex2oat_bin, (char * const *)argv);
530 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700531}
532
533/*
534 * Whether dexopt should use a swap file when compiling an APK.
535 *
536 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
537 * itself, anyways).
538 *
539 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
540 *
541 * Otherwise, return true if this is a low-mem device.
542 *
543 * Otherwise, return default value.
544 */
545static bool kAlwaysProvideSwapFile = false;
546static bool kDefaultProvideSwapFile = true;
547
548static bool ShouldUseSwapFileForDexopt() {
549 if (kAlwaysProvideSwapFile) {
550 return true;
551 }
552
553 // Check the "override" property. If it exists, return value == "true".
554 char dex2oat_prop_buf[kPropertyValueMax];
555 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
556 if (strcmp(dex2oat_prop_buf, "true") == 0) {
557 return true;
558 } else {
559 return false;
560 }
561 }
562
563 // Shortcut for default value. This is an implementation optimization for the process sketched
564 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
565 // as low-mem is never returning false. The compiler will optimize this away if it can.
566 if (kDefaultProvideSwapFile) {
567 return true;
568 }
569
570 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
571 if (is_low_mem) {
572 return true;
573 }
574
575 // Default value must be false here.
576 return kDefaultProvideSwapFile;
577}
578
Richard Uhler76cc0272016-12-08 10:46:35 +0000579static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700580 if (set_to_bg) {
581 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
582 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
583 exit(70);
584 }
585 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
586 ALOGE("setpriority failed: %s\n", strerror(errno));
587 exit(71);
588 }
589 }
590}
591
Calin Juravle29591732017-11-20 17:46:19 -0800592static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
593 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800594 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800595 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800596 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800597 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800598 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700599 }
Calin Juravle114f0812017-03-08 19:05:07 -0800600 // Profiles should belong to the app; make sure of that by giving ownership to
601 // the app uid. If we cannot do that, there's no point in returning the fd
602 // since dex2oat/profman will fail with SElinux denials.
603 if (fchown(fd.get(), uid, uid) < 0) {
604 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800605 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800606 }
Calin Juravle29591732017-11-20 17:46:19 -0800607 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800608}
609
Calin Juravle29591732017-11-20 17:46:19 -0800610static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800611 // Do not follow symlinks when opening a profile:
612 // - primary profiles should not contain symlinks in their paths
613 // - secondary dex paths should have been already resolved and validated
614 flags |= O_NOFOLLOW;
615
Calin Juravle29591732017-11-20 17:46:19 -0800616 // Check if we need to create the profile
617 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
618 unique_fd fd;
619 if ((flags & O_CREAT) != 0) {
620 fd = create_profile(uid, profile, flags);
621 } else {
622 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
623 }
624
Calin Juravle114f0812017-03-08 19:05:07 -0800625 if (fd.get() < 0) {
626 if (errno != ENOENT) {
627 // Profiles might be missing for various reasons. For example, in a
628 // multi-user environment, the profile directory for one user can be created
629 // after we start a merge. In this case the current profile for that user
630 // will not be found.
631 // Also, the secondary dex profiles might be deleted by the app at any time,
632 // so we can't we need to prepare if they are missing.
633 PLOG(ERROR) << "Failed to open profile " << profile;
634 }
635 return invalid_unique_fd();
636 }
637
Jeff Sharkey90aff262016-12-12 14:28:24 -0700638 return fd;
639}
640
Calin Juravle114f0812017-03-08 19:05:07 -0800641static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
642 bool is_secondary_dex) {
643 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800644 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800645}
646
647static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
648 bool is_secondary_dex) {
649 std::string profile = create_reference_profile_path(location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800650 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
651}
652
653static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
654 const std::string& code_path) {
655 std::string profile = create_snapshot_profile_path(package_name, code_path);
656 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800657}
658
659static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800660 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700661 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800662 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
663 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700664
Calin Juravle114f0812017-03-08 19:05:07 -0800665 // For secondary dex files, we don't really need the user but we use it for sanity checks.
666 // Note: the user owning the dex file should be the current user.
667 std::vector<userid_t> users;
668 if (is_secondary_dex){
669 users.push_back(multiuser_get_user_id(uid));
670 } else {
671 users = get_known_users(/*volume_uuid*/ nullptr);
672 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700673 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800674 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700675 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800676 if (profile_fd.get() >= 0) {
677 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700678 }
679 }
680}
681
682static void drop_capabilities(uid_t uid) {
683 if (setgid(uid) != 0) {
684 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
685 exit(64);
686 }
687 if (setuid(uid) != 0) {
688 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
689 exit(65);
690 }
691 // drop capabilities
692 struct __user_cap_header_struct capheader;
693 struct __user_cap_data_struct capdata[2];
694 memset(&capheader, 0, sizeof(capheader));
695 memset(&capdata, 0, sizeof(capdata));
696 capheader.version = _LINUX_CAPABILITY_VERSION_3;
697 if (capset(&capheader, &capdata[0]) < 0) {
698 ALOGE("capset failed: %s\n", strerror(errno));
699 exit(66);
700 }
701}
702
703static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
704static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
705static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
706static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
707static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
708
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800709static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
710 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700711 static const size_t MAX_INT_LEN = 32;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700712 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700713
714 std::vector<std::string> profile_args(profiles_fd.size());
715 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
716 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800717 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700718 profile_args[k].assign(profile_buf);
719 }
720 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800721 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700722
723 // program name, reference profile fd, the final NULL and the profile fds
724 const char* argv[3 + profiles_fd.size()];
725 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700726 argv[i++] = profman_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727 argv[i++] = reference_profile_arg;
728 for (size_t k = 0; k < profile_args.size(); k++) {
729 argv[i++] = profile_args[k].c_str();
730 }
731 // Do not add after dex2oat_flags, they should override others for debugging.
732 argv[i] = NULL;
733
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700734 execv(profman_bin, (char * const *)argv);
735 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700736 exit(68); /* only get here on exec failure */
737}
738
739// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800740// The location is the package name for primary apks or the dex path for secondary dex files.
741// Returns true if there is enough information in the current profiles that makes it
742// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700743// If the return value is true all the current profiles would have been merged into
744// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800745static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800746 std::vector<unique_fd> profiles_fd;
747 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800748 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800749 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700750 // Skip profile guided compilation because no profiles were found.
751 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700752 return false;
753 }
754
Jeff Sharkey90aff262016-12-12 14:28:24 -0700755 pid_t pid = fork();
756 if (pid == 0) {
757 /* child -- drop privileges before continuing */
758 drop_capabilities(uid);
759 run_profman_merge(profiles_fd, reference_profile_fd);
760 exit(68); /* only get here on exec failure */
761 }
762 /* parent */
763 int return_code = wait_child(pid);
764 bool need_to_compile = false;
765 bool should_clear_current_profiles = false;
766 bool should_clear_reference_profile = false;
767 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800768 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 } else {
770 return_code = WEXITSTATUS(return_code);
771 switch (return_code) {
772 case PROFMAN_BIN_RETURN_CODE_COMPILE:
773 need_to_compile = true;
774 should_clear_current_profiles = true;
775 should_clear_reference_profile = false;
776 break;
777 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
778 need_to_compile = false;
779 should_clear_current_profiles = false;
780 should_clear_reference_profile = false;
781 break;
782 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800783 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 need_to_compile = false;
785 should_clear_current_profiles = true;
786 should_clear_reference_profile = true;
787 break;
788 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
789 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
790 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800791 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700792 need_to_compile = false;
793 should_clear_current_profiles = false;
794 should_clear_reference_profile = false;
795 break;
796 default:
797 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800798 LOG(WARNING) << "Unknown error code while processing profiles for location "
799 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700800 need_to_compile = false;
801 should_clear_current_profiles = true;
802 should_clear_reference_profile = true;
803 break;
804 }
805 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800806
Jeff Sharkey90aff262016-12-12 14:28:24 -0700807 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800808 if (is_secondary_dex) {
809 // For secondary dex files, the owning user is the current user.
810 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
811 } else {
812 clear_primary_current_profiles(location);
813 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700814 }
815 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800816 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700817 }
818 return need_to_compile;
819}
820
Calin Juravle114f0812017-03-08 19:05:07 -0800821// Decides if profile guided compilation is needed or not based on existing profiles.
822// The analysis is done for the primary apks of the given package.
823// Returns true if there is enough information in the current profiles that makes it
824// worth to recompile the package.
825// If the return value is true all the current profiles would have been merged into
826// the reference profiles accessible with open_reference_profile().
827bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
828 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
829}
830
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800831static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
832 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700833 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800834 const std::vector<unique_fd>& apk_fds,
835 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700836 std::vector<std::string> profman_args;
837 static const char* PROFMAN_BIN = "/system/bin/profman";
838 profman_args.push_back(PROFMAN_BIN);
839 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800840 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700841 if (reference_profile_fd != -1) {
842 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800843 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700844 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800845 for (size_t i = 0; i < profile_fds.size(); i++) {
846 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847 }
848 for (const std::string& dex_location : dex_locations) {
849 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
850 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800851 for (size_t i = 0; i < apk_fds.size(); i++) {
852 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700853 }
854 const char **argv = new const char*[profman_args.size() + 1];
855 size_t i = 0;
856 for (const std::string& profman_arg : profman_args) {
857 argv[i++] = profman_arg.c_str();
858 }
859 argv[i] = NULL;
860
861 execv(PROFMAN_BIN, (char * const *)argv);
862 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
863 exit(68); /* only get here on exec failure */
864}
865
Calin Juravle76268c52017-03-09 13:19:42 -0800866bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800867 std::vector<unique_fd> profile_fds;
868 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800869 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700870
Calin Juravle114f0812017-03-08 19:05:07 -0800871 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
872 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700873
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800874 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700875 const bool has_profiles = !profile_fds.empty();
876
877 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800878 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700879 return false;
880 }
881
Calin Juravle114f0812017-03-08 19:05:07 -0800882 unique_fd output_fd(open(out_file_name.c_str(),
883 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700884 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
885 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
886 return false;
887 }
888 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
889 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800890 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700891 for (const std::string& code_full_path : code_full_paths) {
892 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800893 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700894 if (apk_fd == -1) {
895 ALOGE("installd cannot open '%s'\n", full_path);
896 return false;
897 }
898 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800899 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700900 }
901
902 pid_t pid = fork();
903 if (pid == 0) {
904 /* child -- drop privileges before continuing */
905 drop_capabilities(uid);
906 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
907 apk_fds, output_fd);
908 exit(68); /* only get here on exec failure */
909 }
910 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700911 int return_code = wait_child(pid);
912 if (!WIFEXITED(return_code)) {
913 LOG(WARNING) << "profman failed for package " << pkgname << ": "
914 << return_code;
915 return false;
916 }
917 return true;
918}
919
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700920bool copy_system_profile(const std::string& system_profile,
921 uid_t packageUid, const std::string& data_profile_location) {
922 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
923 unique_fd out_fd(open_reference_profile(packageUid,
924 data_profile_location,
925 /*read_write*/ true,
926 /*secondary*/ false));
927 if (in_fd.get() < 0) {
928 PLOG(WARNING) << "Could not open profile " << system_profile;
929 return false;
930 }
931 if (out_fd.get() < 0) {
932 PLOG(WARNING) << "Could not open profile " << data_profile_location;
933 return false;
934 }
935
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700936 // As a security measure we want to write the profile information with the reduced capabilities
937 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700938 pid_t pid = fork();
939 if (pid == 0) {
940 /* child -- drop privileges before continuing */
941 drop_capabilities(packageUid);
942
943 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
944 if (errno != EWOULDBLOCK) {
945 PLOG(WARNING) << "Error locking profile " << data_profile_location;
946 }
947 // This implies that the app owning this profile is running
948 // (and has acquired the lock).
949 //
950 // The app never acquires the lock for the reference profiles of primary apks.
951 // Only dex2oat from installd will do that. Since installd is single threaded
952 // we should not see this case. Nevertheless be prepared for it.
953 PLOG(WARNING) << "Failed to flock " << data_profile_location;
954 return false;
955 }
956
957 bool truncated = ftruncate(out_fd.get(), 0) == 0;
958 if (!truncated) {
959 PLOG(WARNING) << "Could not truncate " << data_profile_location;
960 }
961
962 // Copy over data.
963 static constexpr size_t kBufferSize = 4 * 1024;
964 char buffer[kBufferSize];
965 while (true) {
966 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
967 if (bytes == 0) {
968 break;
969 }
970 write(out_fd.get(), buffer, bytes);
971 }
972 if (flock(out_fd.get(), LOCK_UN) != 0) {
973 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
974 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700975 // Use _exit since we don't want to run the global destructors in the child.
976 // b/62597429
977 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700978 }
979 /* parent */
980 int return_code = wait_child(pid);
981 return return_code == 0;
982}
983
Jeff Sharkey90aff262016-12-12 14:28:24 -0700984static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
985 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
986 if (EndsWith(oat_path, ".dex")) {
987 std::string new_path = oat_path;
988 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
Elliott Hughes969e4f82017-12-20 12:34:09 -0800989 CHECK(EndsWith(new_path, new_ext));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700990 return new_path;
991 }
992
993 // An odex entry. Not that this may not be an extension, e.g., in the OTA
994 // case (where the base name will have an extension for the B artifact).
995 size_t odex_pos = oat_path.rfind(".odex");
996 if (odex_pos != std::string::npos) {
997 std::string new_path = oat_path;
998 new_path.replace(odex_pos, strlen(".odex"), new_ext);
999 CHECK_NE(new_path.find(new_ext), std::string::npos);
1000 return new_path;
1001 }
1002
1003 // Don't know how to handle this.
1004 return "";
1005}
1006
1007// Translate the given oat path to an art (app image) path. An empty string
1008// denotes an error.
1009static std::string create_image_filename(const std::string& oat_path) {
1010 return replace_file_extension(oat_path, ".art");
1011}
1012
1013// Translate the given oat path to a vdex path. An empty string denotes an error.
1014static std::string create_vdex_filename(const std::string& oat_path) {
1015 return replace_file_extension(oat_path, ".vdex");
1016}
1017
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018static int open_output_file(const char* file_name, bool recreate, int permissions) {
1019 int flags = O_RDWR | O_CREAT;
1020 if (recreate) {
1021 if (unlink(file_name) < 0) {
1022 if (errno != ENOENT) {
1023 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1024 }
1025 }
1026 flags |= O_EXCL;
1027 }
1028 return open(file_name, flags, permissions);
1029}
1030
Calin Juravle2289c0a2017-02-15 12:44:14 -08001031static bool set_permissions_and_ownership(
1032 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1033 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1034 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001035 if (fchmod(fd,
1036 S_IRUSR|S_IWUSR|S_IRGRP |
1037 (is_public ? S_IROTH : 0)) < 0) {
1038 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1039 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001040 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001041 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1042 return false;
1043 }
1044 return true;
1045}
1046
1047static bool IsOutputDalvikCache(const char* oat_dir) {
1048 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1049 // into '!'. Play it safe by handling it both.
1050 // TODO: ensure we never get null.
1051 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1052 return oat_dir == nullptr || oat_dir[0] == '!';
1053}
1054
Calin Juravled23dee72017-07-06 16:29:11 -07001055// Best-effort check whether we can fit the the path into our buffers.
1056// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1057// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1058// extension to the cache path (5 bytes).
1059// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1060static bool validate_dex_path_size(const std::string& dex_path) {
1061 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1062 LOG(ERROR) << "dex_path too long: " << dex_path;
1063 return false;
1064 }
1065 return true;
1066}
1067
Jeff Sharkey90aff262016-12-12 14:28:24 -07001068static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001069 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001070 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001071 return false;
1072 }
1073
1074 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001075 // Oat dirs for secondary dex files are already validated.
1076 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001077 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1078 return false;
1079 }
1080 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1081 return false;
1082 }
1083 } else {
1084 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1085 return false;
1086 }
1087 }
1088 return true;
1089}
1090
1091// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1092// on destruction. It will also run the given cleanup (unless told not to) after closing.
1093//
1094// Usage example:
1095//
Calin Juravle7a570e82017-01-14 16:23:30 -08001096// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001097// [name]() {
1098// unlink(name.c_str());
1099// });
1100// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1101// wrapper if captured as a reference.
1102//
1103// if (file.get() == -1) {
1104// // Error opening...
1105// }
1106//
1107// ...
1108// if (error) {
1109// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1110// // and delete the file (after the fd is closed).
1111// return -1;
1112// }
1113//
1114// (Success case)
1115// file.SetCleanup(false);
1116// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1117// // (leaving the file around; after the fd is closed).
1118//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001119class Dex2oatFileWrapper {
1120 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001121 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001122 }
1123
Calin Juravle7a570e82017-01-14 16:23:30 -08001124 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1125 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1126
1127 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1128 value_ = other.value_;
1129 cleanup_ = other.cleanup_;
1130 do_cleanup_ = other.do_cleanup_;
1131 auto_close_ = other.auto_close_;
1132 other.release();
1133 }
1134
1135 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1136 value_ = other.value_;
1137 cleanup_ = other.cleanup_;
1138 do_cleanup_ = other.do_cleanup_;
1139 auto_close_ = other.auto_close_;
1140 other.release();
1141 return *this;
1142 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001143
1144 ~Dex2oatFileWrapper() {
1145 reset(-1);
1146 }
1147
1148 int get() {
1149 return value_;
1150 }
1151
1152 void SetCleanup(bool cleanup) {
1153 do_cleanup_ = cleanup;
1154 }
1155
1156 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001157 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001158 close(value_);
1159 }
1160 if (do_cleanup_ && cleanup_ != nullptr) {
1161 cleanup_();
1162 }
1163
1164 value_ = new_value;
1165 }
1166
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 void reset(int new_value, std::function<void ()> new_cleanup) {
1168 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001169 close(value_);
1170 }
1171 if (do_cleanup_ && cleanup_ != nullptr) {
1172 cleanup_();
1173 }
1174
1175 value_ = new_value;
1176 cleanup_ = new_cleanup;
1177 }
1178
Calin Juravle7a570e82017-01-14 16:23:30 -08001179 void DisableAutoClose() {
1180 auto_close_ = false;
1181 }
1182
Jeff Sharkey90aff262016-12-12 14:28:24 -07001183 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001184 void release() {
1185 value_ = -1;
1186 do_cleanup_ = false;
1187 cleanup_ = nullptr;
1188 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001189 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001190 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001191 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001192 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001193};
1194
Calin Juravle7a570e82017-01-14 16:23:30 -08001195// (re)Creates the app image if needed.
1196Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001197 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001198
1199 // We don't create an image for secondary dex files.
1200 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001201 return Dex2oatFileWrapper();
1202 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001203
Calin Juravle7a570e82017-01-14 16:23:30 -08001204 const std::string image_path = create_image_filename(out_oat_path);
1205 if (image_path.empty()) {
1206 // Happens when the out_oat_path has an unknown extension.
1207 return Dex2oatFileWrapper();
1208 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001209
1210 // Use app images only if it is enabled (by a set image format) and we are compiling
1211 // profile-guided (so the app image doesn't conservatively contain all classes).
1212 if (!profile_guided) {
1213 // In case there is a stale image, remove it now. Ignore any error.
1214 unlink(image_path.c_str());
1215 return Dex2oatFileWrapper();
1216 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 char app_image_format[kPropertyValueMax];
1218 bool have_app_image_format =
1219 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1220 if (!have_app_image_format) {
1221 return Dex2oatFileWrapper();
1222 }
1223 // Recreate is true since we do not want to modify a mapped image. If the app is
1224 // already running and we modify the image file, it can cause crashes (b/27493510).
1225 Dex2oatFileWrapper wrapper_fd(
1226 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1227 [image_path]() { unlink(image_path.c_str()); });
1228 if (wrapper_fd.get() < 0) {
1229 // Could not create application image file. Go on since we can compile without it.
1230 LOG(ERROR) << "installd could not create '" << image_path
1231 << "' for image file during dexopt";
1232 // If we have a valid image file path but no image fd, explicitly erase the image file.
1233 if (unlink(image_path.c_str()) < 0) {
1234 if (errno != ENOENT) {
1235 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1236 }
1237 }
1238 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001239 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001240 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1241 wrapper_fd.reset(-1);
1242 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001243
Calin Juravle7a570e82017-01-14 16:23:30 -08001244 return wrapper_fd;
1245}
1246
1247// Creates the dexopt swap file if necessary and return its fd.
1248// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001249unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001250 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001251 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001252 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001253 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001254 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001255 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001256 if (swap_fd.get() < 0) {
1257 // Could not create swap file. Optimistically go on and hope that we can compile
1258 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001259 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001260 } else {
1261 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001262 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001263 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1264 }
1265 }
1266 return swap_fd;
1267}
1268
1269// Opens the reference profiles if needed.
1270// 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 -08001271Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1272 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1273 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001274 // Public apps should not be compiled with profile information ever. Same goes for the special
1275 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001276 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001277 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001278 }
Calin Juravle114f0812017-03-08 19:05:07 -08001279
1280 // Open reference profile in read only mode as dex2oat does not get write permissions.
1281 const std::string location = is_secondary_dex ? dex_path : pkgname;
1282 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1283 const auto& cleanup = [location, is_secondary_dex]() {
1284 clear_reference_profile(location.c_str(), is_secondary_dex);
1285 };
1286 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001287}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001288
Calin Juravle7a570e82017-01-14 16:23:30 -08001289// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1290// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001291bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001292 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001293 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001294 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1295 CHECK(in_vdex_wrapper_fd != nullptr);
1296 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001297 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1298 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001299 char in_odex_path[PKG_PATH_MAX];
1300 int dexopt_action = abs(dexopt_needed);
1301 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001302 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001303
1304 // Infer the name of the output VDEX.
1305 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1306 if (out_vdex_path_str.empty()) {
1307 return false;
1308 }
1309
1310 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001311 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001312 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1313 const char* path = nullptr;
1314 if (is_odex_location) {
1315 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1316 path = in_odex_path;
1317 } else {
1318 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001319 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001320 }
1321 } else {
1322 path = out_oat_path;
1323 }
1324 in_vdex_path_str = create_vdex_filename(path);
1325 if (in_vdex_path_str.empty()) {
1326 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001327 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001328 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001329 // We can update in place when all these conditions are met:
1330 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1331 // on /system typically cannot be updated in place).
1332 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1333 // cannot be currently used by a running process.
1334 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1335 // different vdex files to operate.
1336 update_vdex_in_place =
1337 (in_vdex_path_str == out_vdex_path_str) &&
1338 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1339 !profile_guided;
1340 if (update_vdex_in_place) {
1341 // Open the file read-write to be able to update it.
1342 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1343 if (in_vdex_wrapper_fd->get() == -1) {
1344 // If we failed to open the file, we cannot update it in place.
1345 update_vdex_in_place = false;
1346 }
1347 } else {
1348 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1349 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001350 }
1351
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001352 // If we are updating the vdex in place, we do not need to recreate a vdex,
1353 // and can use the same existing one.
1354 if (update_vdex_in_place) {
1355 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1356 // have bogus stale vdex files.
1357 out_vdex_wrapper_fd->reset(
1358 in_vdex_wrapper_fd->get(),
1359 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1360 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1361 // wrapper).
1362 in_vdex_wrapper_fd->DisableAutoClose();
1363 } else {
1364 out_vdex_wrapper_fd->reset(
1365 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1366 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1367 if (out_vdex_wrapper_fd->get() < 0) {
1368 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1369 return false;
1370 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001371 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001372 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001373 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001374 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1375 return false;
1376 }
1377
1378 // If we got here we successfully opened the vdex files.
1379 return true;
1380}
1381
1382// Opens the output oat file for the given apk.
1383// If successful it stores the output path into out_oat_path and returns true.
1384Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001385 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1386 char* out_oat_path) {
1387 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001388 return Dex2oatFileWrapper();
1389 }
1390 const std::string out_oat_path_str(out_oat_path);
1391 Dex2oatFileWrapper wrapper_fd(
1392 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1393 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1394 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001395 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001396 } else if (!set_permissions_and_ownership(
1397 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001398 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1399 wrapper_fd.reset(-1);
1400 }
1401 return wrapper_fd;
1402}
1403
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001404// Creates RDONLY fds for oat and vdex files, if exist.
1405// Returns false if it fails to create oat out path for the given apk path.
1406// Note that the method returns true even if the files could not be opened.
1407bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1408 const std::string& oat_dir,
1409 const std::string& instruction_set,
1410 bool is_secondary_dex,
1411 unique_fd* oat_file_fd,
1412 unique_fd* vdex_file_fd) {
1413 char oat_path[PKG_PATH_MAX];
1414 if (!create_oat_out_path(apk_path.c_str(),
1415 instruction_set.c_str(),
1416 oat_dir.c_str(),
1417 is_secondary_dex,
1418 oat_path)) {
Calin Juravle7d765462017-09-04 15:57:10 -07001419 LOG(ERROR) << "Could not create oat out path for "
1420 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001421 return false;
1422 }
1423 oat_file_fd->reset(open(oat_path, O_RDONLY));
1424 if (oat_file_fd->get() < 0) {
1425 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1426 }
1427
1428 std::string vdex_filename = create_vdex_filename(oat_path);
1429 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1430 if (vdex_file_fd->get() < 0) {
1431 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1432 }
1433
1434 return true;
1435}
1436
Calin Juravle7a570e82017-01-14 16:23:30 -08001437// Updates the access times of out_oat_path based on those from apk_path.
1438void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1439 struct stat input_stat;
1440 memset(&input_stat, 0, sizeof(input_stat));
1441 if (stat(apk_path, &input_stat) != 0) {
1442 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1443 return;
1444 }
1445
1446 struct utimbuf ut;
1447 ut.actime = input_stat.st_atime;
1448 ut.modtime = input_stat.st_mtime;
1449 if (utime(out_oat_path, &ut) != 0) {
1450 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1451 }
1452}
1453
Calin Juravle80a21252017-01-17 14:43:25 -08001454// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001455// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1456// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1457// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001458static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1459 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1460 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001461 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001462 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001463 const char* dexoptanalyzer_bin =
1464 is_debug_runtime()
1465 ? "/system/bin/dexoptanalyzerd"
1466 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001467 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1468
Calin Juravled23dee72017-07-06 16:29:11 -07001469 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1470 LOG(ERROR) << "Instruction set " << instruction_set
1471 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001472 return;
1473 }
1474
Calin Juravled23dee72017-07-06 16:29:11 -07001475 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001476 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1477 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1478 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001479 std::string isa_arg = "--isa=" + instruction_set;
1480 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001481 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001482 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001483 std::string class_loader_context_arg = "--class-loader-context=";
1484 if (class_loader_context != nullptr) {
1485 class_loader_context_arg += class_loader_context;
1486 }
Calin Juravle80a21252017-01-17 14:43:25 -08001487
Calin Juravle80a21252017-01-17 14:43:25 -08001488 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001489 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001490 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001491 (vdex_fd >= 0 ? 1 : 0) +
1492 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001493 (downgrade ? 1 : 0) +
1494 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001495 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001496 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001497 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001498 argv[i++] = dex_file_arg.c_str();
1499 argv[i++] = isa_arg.c_str();
1500 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001501 if (oat_fd >= 0) {
1502 argv[i++] = oat_fd_arg.c_str();
1503 }
1504 if (vdex_fd >= 0) {
1505 argv[i++] = vdex_fd_arg.c_str();
1506 }
1507 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001508 if (profile_was_updated) {
1509 argv[i++] = assume_profile_changed;
1510 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001511 if (downgrade) {
1512 argv[i++] = downgrade_flag;
1513 }
Calin Juravle58cab072017-09-12 01:02:26 -07001514 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001515 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001516 }
Calin Juravle80a21252017-01-17 14:43:25 -08001517 argv[i] = NULL;
1518
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001519 execv(dexoptanalyzer_bin, (char * const *)argv);
1520 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001521}
1522
1523// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001524static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle7d765462017-09-04 15:57:10 -07001525 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001526 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001527 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001528 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001529 return false;
1530 }
Calin Juravle114f0812017-03-08 19:05:07 -08001531 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001532
Calin Juravle80a21252017-01-17 14:43:25 -08001533 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001534 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1535 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001536 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001537 return false;
1538 }
1539
1540 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001541 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001542
Calin Juravle7d765462017-09-04 15:57:10 -07001543 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001544 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001545 return false;
1546 }
1547
1548 return true;
1549}
1550
Calin Juravle7d765462017-09-04 15:57:10 -07001551// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1552// secondary dex files. This return codes are returned by the child process created for
1553// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001554
Calin Juravle7d765462017-09-04 15:57:10 -07001555// The dexoptanalyzer was not invoked because of validation or IO errors.
1556static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1557// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1558static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1559
1560// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001561// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1562// Returns false for errors or unexpected result values.
Calin Juravle7d765462017-09-04 15:57:10 -07001563// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1564// of dexoptanalyzer.
1565static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001566 int* dexopt_needed_out) {
1567 // The result values are defined in dexoptanalyzer.
1568 switch (result) {
Calin Juravle7d765462017-09-04 15:57:10 -07001569 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001570 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001571 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001572 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001573 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001574 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001575 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001576 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001577 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001578 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle7d765462017-09-04 15:57:10 -07001579 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1580 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1581 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001582 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1583 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001584 << " : dexoptanalyzer result=" << result;
1585 return false;
Calin Juravle7d765462017-09-04 15:57:10 -07001586 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1587 // If the file does not exist there's no need for dexopt.
1588 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1589 return true;
1590 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1591 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001592 default:
Calin Juravle7d765462017-09-04 15:57:10 -07001593 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1594 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001595 return false;
1596 }
1597}
1598
Calin Juravle7d765462017-09-04 15:57:10 -07001599enum SecondaryDexAccess {
1600 kSecondaryDexAccessReadOk = 0,
1601 kSecondaryDexAccessDoesNotExist = 1,
1602 kSecondaryDexAccessPermissionError = 2,
1603 kSecondaryDexAccessIOError = 3
1604};
1605
1606static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1607 // Check if the path exists and can be read. If not, there's nothing to do.
1608 if (access(dex_path.c_str(), R_OK) == 0) {
1609 return kSecondaryDexAccessReadOk;
1610 } else {
1611 if (errno == ENOENT) {
1612 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1613 return kSecondaryDexAccessDoesNotExist;
1614 } else {
1615 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1616 return errno == EACCES
1617 ? kSecondaryDexAccessPermissionError
1618 : kSecondaryDexAccessIOError;
1619 }
1620 }
1621}
1622
1623static bool is_file_public(const std::string& filename) {
1624 struct stat file_stat;
1625 if (stat(filename.c_str(), &file_stat) == 0) {
1626 return (file_stat.st_mode & S_IROTH) != 0;
1627 }
1628 return false;
1629}
1630
1631// Create the oat file structure for the secondary dex 'dex_path' and assign
1632// the individual path component to the 'out_' parameters.
1633static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1634 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1635 size_t dirIndex = dex_path.rfind('/');
1636 if (dirIndex == std::string::npos) {
1637 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1638 return false;
1639 }
1640 // TODO(calin): we have similar computations in at lest 3 other places
1641 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1642 // using string append.
1643 std::string apk_dir = dex_path.substr(0, dirIndex);
1644 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1645 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1646
1647 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1648 /*is_secondary_dex*/true, out_oat_path)) {
1649 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1650 return false;
1651 }
1652 return true;
1653}
1654
1655// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1656// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1657static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1658 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1659 *out_storage_flag = FLAG_STORAGE_CE;
1660 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1661 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1662 return false;
1663 }
1664 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1665 *out_storage_flag = FLAG_STORAGE_DE;
1666 } else {
1667 LOG(ERROR) << "Secondary dex storage flag must be set";
1668 return false;
1669 }
1670 return true;
1671}
1672
Calin Juravlec9eab382017-01-25 01:17:17 -08001673// 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 -08001674// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1675// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001676// When returning true, the output parameters will be:
1677// - is_public_out: whether or not the oat file should not be made public
1678// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1679// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle7d765462017-09-04 15:57:10 -07001680static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001681 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001682 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle7d765462017-09-04 15:57:10 -07001683 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1684 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001685 int storage_flag;
Calin Juravle7d765462017-09-04 15:57:10 -07001686 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001687 return false;
1688 }
Calin Juravle7d765462017-09-04 15:57:10 -07001689 // Compute the oat dir as it's not easy to extract it from the child computation.
1690 char oat_path[PKG_PATH_MAX];
1691 char oat_dir[PKG_PATH_MAX];
1692 char oat_isa_dir[PKG_PATH_MAX];
1693 if (!create_secondary_dex_oat_layout(
1694 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1695 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001696 return false;
1697 }
Calin Juravle7d765462017-09-04 15:57:10 -07001698 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001699
Calin Juravle80a21252017-01-17 14:43:25 -08001700 pid_t pid = fork();
1701 if (pid == 0) {
1702 // child -- drop privileges before continuing.
1703 drop_capabilities(uid);
Calin Juravle7d765462017-09-04 15:57:10 -07001704
1705 // Validate the path structure.
1706 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1707 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1708 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1709 }
1710
1711 // Open the dex file.
1712 unique_fd zip_fd;
1713 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1714 if (zip_fd.get() < 0) {
1715 if (errno == ENOENT) {
1716 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1717 } else {
1718 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1719 }
1720 }
1721
1722 // Prepare the oat directories.
1723 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1724 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1725 }
1726
1727 // Open the vdex/oat files if any.
1728 unique_fd oat_file_fd;
1729 unique_fd vdex_file_fd;
1730 if (!maybe_open_oat_and_vdex_file(dex_path,
1731 *oat_dir_out,
1732 instruction_set,
1733 true /* is_secondary_dex */,
1734 &oat_file_fd,
1735 &vdex_file_fd)) {
1736 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1737 }
1738
1739 // Analyze profiles.
1740 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1741
1742 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001743 exec_dexoptanalyzer(dex_path,
1744 vdex_file_fd.get(),
1745 oat_file_fd.get(),
1746 zip_fd.get(),
1747 instruction_set,
Calin Juravle7d765462017-09-04 15:57:10 -07001748 compiler_filter, profile_was_updated,
1749 downgrade,
1750 class_loader_context);
1751 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1752 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001753 }
1754
1755 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001756 int result = wait_child(pid);
1757 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001758 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001759 return false;
1760 }
1761 result = WEXITSTATUS(result);
Calin Juravle7d765462017-09-04 15:57:10 -07001762 // Check that we successfully executed dexoptanalyzer.
1763 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1764
1765 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1766
Calin Juravle80a21252017-01-17 14:43:25 -08001767 // Run dexopt only if needed or forced.
Calin Juravle7d765462017-09-04 15:57:10 -07001768 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1769 // makes the code simpler; force compilation is only needed during tests).
1770 if (success &&
1771 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1772 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001773 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1774 }
1775
Calin Juravle7d765462017-09-04 15:57:10 -07001776 // Check if we should make the oat file public.
1777 // Note that if the dex file is not public the compiled code cannot be made public.
1778 // It is ok to check this flag outside in the parent process.
1779 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1780
Calin Juravle80a21252017-01-17 14:43:25 -08001781 return success;
1782}
1783
Calin Juravlec9eab382017-01-25 01:17:17 -08001784int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001785 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001786 const char* volume_uuid, const char* class_loader_context, const char* se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001787 bool downgrade, int target_sdk_version) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001788 CHECK(pkgname != nullptr);
1789 CHECK(pkgname[0] != 0);
1790 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1791 LOG_FATAL("dexopt flags contains unknown fields\n");
1792 }
1793
Calin Juravled23dee72017-07-06 16:29:11 -07001794 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001795 return -1;
1796 }
1797
1798 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1799 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1800 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001801 }
1802
Calin Juravleebc8a792017-04-04 20:21:05 -07001803 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001804 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1805 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1806 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001807 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001808 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
David Brazdil52249162018-02-12 18:04:59 -08001809 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001810
1811 // Check if we're dealing with a secondary dex file and if we need to compile it.
1812 std::string oat_dir_str;
1813 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001814 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001815 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle7d765462017-09-04 15:57:10 -07001816 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001817 oat_dir = oat_dir_str.c_str();
1818 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1819 return 0; // Nothing to do, report success.
1820 }
1821 } else {
1822 return -1; // We had an error, logged in the process method.
1823 }
1824 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001825 // Currently these flags are only use for secondary dex files.
1826 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001827 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1828 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1829 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001830
1831 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001832 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001833 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001834 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001835 return -1;
1836 }
1837
1838 // Create the output OAT file.
1839 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001840 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001841 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001842 if (out_oat_fd.get() < 0) {
1843 return -1;
1844 }
1845
1846 // Open vdex files.
1847 Dex2oatFileWrapper in_vdex_fd;
1848 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001849 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1850 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001851 return -1;
1852 }
1853
Calin Juravlecb556e32017-04-04 20:22:50 -07001854 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1855 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1856 // fully inherit their parent context).
1857 // Note that for primary apk the oat files are created before, in a separate installd
1858 // call which also does the restorecon. TODO(calin): unify the paths.
1859 if (is_secondary_dex) {
1860 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1861 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1862 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1863 return -1;
1864 }
1865 }
1866
Jeff Sharkey90aff262016-12-12 14:28:24 -07001867 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001868 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001869
Calin Juravle7a570e82017-01-14 16:23:30 -08001870 // Create the app image file if needed.
1871 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001872 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001873
Calin Juravle7a570e82017-01-14 16:23:30 -08001874 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001875 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1876 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001877
Calin Juravlec9eab382017-01-25 01:17:17 -08001878 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001879
1880 pid_t pid = fork();
1881 if (pid == 0) {
1882 /* child -- drop privileges before continuing */
1883 drop_capabilities(uid);
1884
Richard Uhler76cc0272016-12-08 10:46:35 +00001885 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001886 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1887 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1888 _exit(67);
1889 }
1890
Richard Uhler76cc0272016-12-08 10:46:35 +00001891 run_dex2oat(input_fd.get(),
1892 out_oat_fd.get(),
1893 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001894 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001895 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001896 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001897 out_oat_path,
1898 swap_fd.get(),
1899 instruction_set,
1900 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001901 debuggable,
1902 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001903 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00001904 reference_profile_fd.get(),
David Brazdil570d3982018-01-16 20:15:43 +00001905 class_loader_context,
David Brazdil7fcbb812018-01-17 17:05:40 +00001906 target_sdk_version,
David Brazdil52249162018-02-12 18:04:59 -08001907 enable_hidden_api_checks);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001908 _exit(68); /* only get here on exec failure */
1909 } else {
1910 int res = wait_child(pid);
1911 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001912 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001913 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001914 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001915 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001916 }
1917 }
1918
Calin Juravlec9eab382017-01-25 01:17:17 -08001919 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001920
1921 // We've been successful, don't delete output.
1922 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001923 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001924 image_fd.SetCleanup(false);
1925 reference_profile_fd.SetCleanup(false);
1926
1927 return 0;
1928}
1929
Calin Juravlec9eab382017-01-25 01:17:17 -08001930// Try to remove the given directory. Log an error if the directory exists
1931// and is empty but could not be removed.
1932static bool rmdir_if_empty(const char* dir) {
1933 if (rmdir(dir) == 0) {
1934 return true;
1935 }
1936 if (errno == ENOENT || errno == ENOTEMPTY) {
1937 return true;
1938 }
1939 PLOG(ERROR) << "Failed to remove dir: " << dir;
1940 return false;
1941}
1942
1943// Try to unlink the given file. Log an error if the file exists and could not
1944// be unlinked.
1945static bool unlink_if_exists(const std::string& file) {
1946 if (unlink(file.c_str()) == 0) {
1947 return true;
1948 }
1949 if (errno == ENOENT) {
1950 return true;
1951
1952 }
1953 PLOG(ERROR) << "Could not unlink: " << file;
1954 return false;
1955}
1956
Calin Juravle7d765462017-09-04 15:57:10 -07001957enum ReconcileSecondaryDexResult {
1958 kReconcileSecondaryDexExists = 0,
1959 kReconcileSecondaryDexCleanedUp = 1,
1960 kReconcileSecondaryDexValidationError = 2,
1961 kReconcileSecondaryDexCleanUpError = 3,
1962 kReconcileSecondaryDexAccessIOError = 4,
1963};
Calin Juravlec9eab382017-01-25 01:17:17 -08001964
1965// Reconcile the secondary dex 'dex_path' and its generated oat files.
1966// Return true if all the parameters are valid and the secondary dex file was
1967// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1968// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1969// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1970// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1971// Return false if there were errors during processing. In this case
1972// out_secondary_dex_exists will be set to false.
1973bool reconcile_secondary_dex_file(const std::string& dex_path,
1974 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1975 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1976 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle7d765462017-09-04 15:57:10 -07001977 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001978 if (isas.size() == 0) {
1979 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1980 return false;
1981 }
1982
Calin Juravle7d765462017-09-04 15:57:10 -07001983 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1984 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1985 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001986 return false;
1987 }
1988
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001989 // As a security measure we want to unlink art artifacts with the reduced capabilities
1990 // of the package user id. So we fork and drop capabilities in the child.
1991 pid_t pid = fork();
1992 if (pid == 0) {
Calin Juravle7d765462017-09-04 15:57:10 -07001993 /* child -- drop privileges before continuing */
1994 drop_capabilities(uid);
1995
1996 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1997 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1998 uid, storage_flag)) {
1999 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2000 _exit(kReconcileSecondaryDexValidationError);
2001 }
2002
2003 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
2004 switch (access_check) {
2005 case kSecondaryDexAccessDoesNotExist:
2006 // File does not exist. Proceed with cleaning.
2007 break;
2008 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
2009 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
2010 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
2011 default:
2012 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
2013 _exit(kReconcileSecondaryDexValidationError);
2014 }
2015
2016 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002017 char oat_path[PKG_PATH_MAX];
2018 char oat_dir[PKG_PATH_MAX];
2019 char oat_isa_dir[PKG_PATH_MAX];
2020 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002021 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle7d765462017-09-04 15:57:10 -07002022 if (!create_secondary_dex_oat_layout(
2023 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
2024 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
2025 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002026 }
Calin Juravle51314092017-05-18 15:33:05 -07002027
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002028 // Delete oat/vdex/art files.
2029 result = unlink_if_exists(oat_path) && result;
2030 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2031 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002032
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002033 // Delete profiles.
2034 std::string current_profile = create_current_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002035 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002036 std::string reference_profile = create_reference_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002037 dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002038 result = unlink_if_exists(current_profile) && result;
2039 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002040
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002041 // We upgraded once the location of current profile for secondary dex files.
2042 // Check for any previous left-overs and remove them as well.
2043 std::string old_current_profile = dex_path + ".prof";
2044 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002045
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002046 // Try removing the directories as well, they might be empty.
2047 result = rmdir_if_empty(oat_isa_dir) && result;
2048 result = rmdir_if_empty(oat_dir) && result;
2049 }
Calin Juravle7d765462017-09-04 15:57:10 -07002050 if (!result) {
2051 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2052 }
2053 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002054 }
2055
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002056 int return_code = wait_child(pid);
Calin Juravle7d765462017-09-04 15:57:10 -07002057 if (!WIFEXITED(return_code)) {
2058 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2059 } else {
2060 return_code = WEXITSTATUS(return_code);
2061 }
2062
2063 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2064
2065 switch (return_code) {
2066 case kReconcileSecondaryDexCleanedUp:
2067 case kReconcileSecondaryDexValidationError:
2068 // If we couldn't validate assume the dex file does not exist.
2069 // This will purge the entry from the PM records.
2070 *out_secondary_dex_exists = false;
2071 return true;
2072 case kReconcileSecondaryDexExists:
2073 *out_secondary_dex_exists = true;
2074 return true;
2075 case kReconcileSecondaryDexAccessIOError:
2076 // We had an access IO error.
2077 // Return false so that we can try again.
2078 // The value of out_secondary_dex_exists does not matter in this case and by convention
2079 // is set to false.
2080 *out_secondary_dex_exists = false;
2081 return false;
2082 default:
2083 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2084 *out_secondary_dex_exists = false;
2085 return false;
2086 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002087}
2088
Alan Stokesa25d90c2017-10-16 10:56:00 +01002089// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2090// Returns true if all parameters are valid and the hash successfully computed and stored in
2091// out_secondary_dex_hash.
2092// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2093// the app.
2094// For any other errors (e.g. if any of the parameters are invalid) returns false.
2095bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2096 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2097 std::vector<uint8_t>* out_secondary_dex_hash) {
2098 out_secondary_dex_hash->clear();
2099
2100 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2101
2102 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2103 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2104 << storage_flag;
2105 return false;
2106 }
2107
2108 // Pipe to get the hash result back from our child process.
2109 unique_fd pipe_read, pipe_write;
2110 if (!Pipe(&pipe_read, &pipe_write)) {
2111 PLOG(ERROR) << "Failed to create pipe";
2112 return false;
2113 }
2114
2115 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2116 // access data the app itself can access.
2117 pid_t pid = fork();
2118 if (pid == 0) {
2119 // child -- drop privileges before continuing
2120 drop_capabilities(uid);
2121 pipe_read.reset();
2122
2123 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2124 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2125 _exit(1);
2126 }
2127
2128 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2129 if (fd == -1) {
2130 if (errno == EACCES || errno == ENOENT) {
2131 // Not treated as an error.
2132 _exit(0);
2133 }
2134 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
2135 _exit(1);
2136 }
2137
2138 SHA256_CTX ctx;
2139 SHA256_Init(&ctx);
2140
2141 std::vector<uint8_t> buffer(65536);
2142 while (true) {
2143 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2144 if (bytes_read == 0) {
2145 break;
2146 } else if (bytes_read == -1) {
2147 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
2148 _exit(1);
2149 }
2150
2151 SHA256_Update(&ctx, buffer.data(), bytes_read);
2152 }
2153
2154 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2155 SHA256_Final(hash.data(), &ctx);
2156 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
2157 _exit(1);
2158 }
2159
2160 _exit(0);
2161 }
2162
2163 // parent
2164 pipe_write.reset();
2165
2166 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2167 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2168 out_secondary_dex_hash->clear();
2169 }
2170 return wait_child(pid) == 0;
2171}
2172
Jeff Sharkey90aff262016-12-12 14:28:24 -07002173// Helper for move_ab, so that we can have common failure-case cleanup.
2174static bool unlink_and_rename(const char* from, const char* to) {
2175 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2176 // return a failure.
2177 struct stat s;
2178 if (stat(to, &s) == 0) {
2179 if (!S_ISREG(s.st_mode)) {
2180 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2181 return false;
2182 }
2183 if (unlink(to) != 0) {
2184 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2185 return false;
2186 }
2187 } else {
2188 // This may be a permission problem. We could investigate the error code, but we'll just
2189 // let the rename failure do the work for us.
2190 }
2191
2192 // Try to rename "to" to "from."
2193 if (rename(from, to) != 0) {
2194 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2195 return false;
2196 }
2197 return true;
2198}
2199
2200// Move/rename a B artifact (from) to an A artifact (to).
2201static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2202 // Check whether B exists.
2203 {
2204 struct stat s;
2205 if (stat(b_path.c_str(), &s) != 0) {
2206 // Silently ignore for now. The service calling this isn't smart enough to understand
2207 // lack of artifacts at the moment.
2208 return false;
2209 }
2210 if (!S_ISREG(s.st_mode)) {
2211 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2212 // Try to unlink, but swallow errors.
2213 unlink(b_path.c_str());
2214 return false;
2215 }
2216 }
2217
2218 // Rename B to A.
2219 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2220 // Delete the b_path so we don't try again (or fail earlier).
2221 if (unlink(b_path.c_str()) != 0) {
2222 PLOG(ERROR) << "Could not unlink " << b_path;
2223 }
2224
2225 return false;
2226 }
2227
2228 return true;
2229}
2230
2231bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2232 // Get the current slot suffix. No suffix, no A/B.
2233 std::string slot_suffix;
2234 {
2235 char buf[kPropertyValueMax];
2236 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2237 return false;
2238 }
2239 slot_suffix = buf;
2240
2241 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2242 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2243 return false;
2244 }
2245 }
2246
2247 // Validate other inputs.
2248 if (validate_apk_path(apk_path) != 0) {
2249 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2250 return false;
2251 }
2252 if (validate_apk_path(oat_dir) != 0) {
2253 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2254 return false;
2255 }
2256
2257 char a_path[PKG_PATH_MAX];
2258 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2259 return false;
2260 }
2261 const std::string a_vdex_path = create_vdex_filename(a_path);
2262 const std::string a_image_path = create_image_filename(a_path);
2263
2264 // B path = A path + slot suffix.
2265 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2266 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2267 const std::string b_image_path = StringPrintf("%s.%s",
2268 a_image_path.c_str(),
2269 slot_suffix.c_str());
2270
2271 bool success = true;
2272 if (move_ab_path(b_path, a_path)) {
2273 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2274 // Note: we can live without an app image. As such, ignore failure to move the image file.
2275 // If we decide to require the app image, or the app image being moved correctly,
2276 // then change accordingly.
2277 constexpr bool kIgnoreAppImageFailure = true;
2278
2279 if (!a_image_path.empty()) {
2280 if (!move_ab_path(b_image_path, a_image_path)) {
2281 unlink(a_image_path.c_str());
2282 if (!kIgnoreAppImageFailure) {
2283 success = false;
2284 }
2285 }
2286 }
2287 } else {
2288 // Cleanup: delete B image, ignore errors.
2289 unlink(b_image_path.c_str());
2290 success = false;
2291 }
2292 } else {
2293 // Cleanup: delete B image, ignore errors.
2294 unlink(b_vdex_path.c_str());
2295 unlink(b_image_path.c_str());
2296 success = false;
2297 }
2298 return success;
2299}
2300
2301bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2302 // Delete the oat/odex file.
2303 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002304 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002305 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002306 return false;
2307 }
2308
2309 // In case of a permission failure report the issue. Otherwise just print a warning.
2310 auto unlink_and_check = [](const char* path) -> bool {
2311 int result = unlink(path);
2312 if (result != 0) {
2313 if (errno == EACCES || errno == EPERM) {
2314 PLOG(ERROR) << "Could not unlink " << path;
2315 return false;
2316 }
2317 PLOG(WARNING) << "Could not unlink " << path;
2318 }
2319 return true;
2320 };
2321
2322 // Delete the oat/odex file.
2323 bool return_value_oat = unlink_and_check(out_path);
2324
2325 // Derive and delete the app image.
2326 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2327
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002328 // Derive and delete the vdex file.
2329 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2330
Jeff Sharkey90aff262016-12-12 14:28:24 -07002331 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002332 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002333}
2334
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002335static bool is_absolute_path(const std::string& path) {
2336 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2337 LOG(ERROR) << "Invalid absolute path " << path;
2338 return false;
2339 } else {
2340 return true;
2341 }
2342}
2343
2344static bool is_valid_instruction_set(const std::string& instruction_set) {
2345 // TODO: add explicit whitelisting of instruction sets
2346 if (instruction_set.find('/') != std::string::npos) {
2347 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2348 return false;
2349 } else {
2350 return true;
2351 }
2352}
2353
2354bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2355 const char *apk_path, const char *instruction_set) {
2356 std::string oat_dir_ = oat_dir;
2357 std::string apk_path_ = apk_path;
2358 std::string instruction_set_ = instruction_set;
2359
2360 if (!is_absolute_path(oat_dir_)) return false;
2361 if (!is_absolute_path(apk_path_)) return false;
2362 if (!is_valid_instruction_set(instruction_set_)) return false;
2363
2364 std::string::size_type end = apk_path_.rfind('.');
2365 std::string::size_type start = apk_path_.rfind('/', end);
2366 if (end == std::string::npos || start == std::string::npos) {
2367 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2368 return false;
2369 }
2370
2371 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2372 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2373 const char* res = res_.c_str();
2374 if (strlen(res) >= PKG_PATH_MAX) {
2375 LOG(ERROR) << "Result too large";
2376 return false;
2377 } else {
2378 strlcpy(path, res, PKG_PATH_MAX);
2379 return true;
2380 }
2381}
2382
2383bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2384 const char *instruction_set) {
2385 std::string apk_path_ = apk_path;
2386 std::string instruction_set_ = instruction_set;
2387
2388 if (!is_absolute_path(apk_path_)) return false;
2389 if (!is_valid_instruction_set(instruction_set_)) return false;
2390
2391 std::string::size_type end = apk_path_.rfind('.');
2392 std::string::size_type start = apk_path_.rfind('/', end);
2393 if (end == std::string::npos || start == std::string::npos) {
2394 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2395 return false;
2396 }
2397
2398 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2399 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2400}
2401
2402bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2403 const char *instruction_set) {
2404 std::string src_ = src;
2405 std::string instruction_set_ = instruction_set;
2406
2407 if (!is_absolute_path(src_)) return false;
2408 if (!is_valid_instruction_set(instruction_set_)) return false;
2409
2410 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2411 if (*it == '/') {
2412 *it = '@';
2413 }
2414 }
2415
2416 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2417 + DALVIK_CACHE_POSTFIX;
2418 const char* res = res_.c_str();
2419 if (strlen(res) >= PKG_PATH_MAX) {
2420 LOG(ERROR) << "Result too large";
2421 return false;
2422 } else {
2423 strlcpy(path, res, PKG_PATH_MAX);
2424 return true;
2425 }
2426}
2427
Calin Juravlec3596c32017-12-05 12:29:15 -08002428bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
Calin Juravle29591732017-11-20 17:46:19 -08002429 const std::string& code_path) {
2430 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2431
2432 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, code_path);
2433 if (snapshot_fd < 0) {
2434 return false;
2435 }
2436
2437 std::vector<unique_fd> profiles_fd;
2438 unique_fd reference_profile_fd;
2439 open_profile_files(app_shared_gid, package_name, /*is_secondary_dex*/ false, &profiles_fd,
2440 &reference_profile_fd);
2441 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2442 return false;
2443 }
2444
2445 profiles_fd.push_back(std::move(reference_profile_fd));
2446
2447 pid_t pid = fork();
2448 if (pid == 0) {
2449 /* child -- drop privileges before continuing */
2450 drop_capabilities(app_shared_gid);
2451 run_profman_merge(profiles_fd, snapshot_fd);
2452 exit(42); /* only get here on exec failure */
2453 }
2454
2455 /* parent */
2456 int return_code = wait_child(pid);
2457 if (!WIFEXITED(return_code)) {
2458 LOG(WARNING) << "profman failed for " << package_name << ":" << code_path;
2459 return false;
2460 }
2461
2462 return true;
2463}
2464
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002465} // namespace installd
2466} // namespace android