blob: beffe00e402251c97e2d62db5adfe2d796591f59 [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 Stokes753dc712017-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 Stokes753dc712017-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 Stokes753dc712017-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 Stokes753dc712017-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";
69
Calin Juravle114f0812017-03-08 19:05:07 -080070// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
71struct FreeDelete {
72 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
73 void operator()(const void* ptr) const {
74 free(const_cast<void*>(ptr));
75 }
76};
77
78// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
79template <typename T>
80using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
81
Calin Juravle1a0af3b2017-03-09 14:33:33 -080082static unique_fd invalid_unique_fd() {
83 return unique_fd(-1);
84}
85
Andreas Gampe6a9cf722017-07-24 16:49:10 -070086static bool is_debug_runtime() {
87 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
88}
89
David Sehra3b5ab62017-10-25 14:27:29 -070090static bool is_debuggable_build() {
91 return android::base::GetBoolProperty("ro.debuggable", false);
92}
93
Jeff Sharkey90aff262016-12-12 14:28:24 -070094static bool clear_profile(const std::string& profile) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -080095 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
Jeff Sharkey90aff262016-12-12 14:28:24 -070096 if (ufd.get() < 0) {
97 if (errno != ENOENT) {
98 PLOG(WARNING) << "Could not open profile " << profile;
99 return false;
100 } else {
101 // Nothing to clear. That's ok.
102 return true;
103 }
104 }
105
106 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
107 if (errno != EWOULDBLOCK) {
108 PLOG(WARNING) << "Error locking profile " << profile;
109 }
110 // This implies that the app owning this profile is running
111 // (and has acquired the lock).
112 //
113 // If we can't acquire the lock bail out since clearing is useless anyway
114 // (the app will write again to the profile).
115 //
116 // Note:
117 // This does not impact the this is not an issue for the profiling correctness.
118 // In case this is needed because of an app upgrade, profiles will still be
119 // eventually cleared by the app itself due to checksum mismatch.
120 // If this is needed because profman advised, then keeping the data around
121 // until the next run is again not an issue.
122 //
123 // If the app attempts to acquire a lock while we've held one here,
124 // it will simply skip the current write cycle.
125 return false;
126 }
127
128 bool truncated = ftruncate(ufd.get(), 0) == 0;
129 if (!truncated) {
130 PLOG(WARNING) << "Could not truncate " << profile;
131 }
132 if (flock(ufd.get(), LOCK_UN) != 0) {
133 PLOG(WARNING) << "Error unlocking profile " << profile;
134 }
135 return truncated;
136}
137
Calin Juravle114f0812017-03-08 19:05:07 -0800138// Clear the reference profile for the given location.
139// The location is the package name for primary apks or the dex path for secondary dex files.
140static bool clear_reference_profile(const std::string& location, bool is_secondary_dex) {
141 return clear_profile(create_reference_profile_path(location, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700142}
143
Calin Juravle114f0812017-03-08 19:05:07 -0800144// Clear the reference profile for the given location.
145// The location is the package name for primary apks or the dex path for secondary dex files.
146static bool clear_current_profile(const std::string& pkgname, userid_t user,
147 bool is_secondary_dex) {
148 return clear_profile(create_current_profile_path(user, pkgname, is_secondary_dex));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700149}
150
Calin Juravle114f0812017-03-08 19:05:07 -0800151// Clear the reference profile for the primary apk of the given package.
152bool clear_primary_reference_profile(const std::string& pkgname) {
153 return clear_reference_profile(pkgname, /*is_secondary_dex*/false);
154}
155
156// Clear all current profile for the primary apk of the given package.
157bool clear_primary_current_profiles(const std::string& pkgname) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700158 bool success = true;
Calin Juravle114f0812017-03-08 19:05:07 -0800159 // 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 -0700160 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
161 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800162 success &= clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700163 }
164 return success;
165}
166
Calin Juravle114f0812017-03-08 19:05:07 -0800167// Clear the current profile for the primary apk of the given package and user.
168bool clear_primary_current_profile(const std::string& pkgname, userid_t user) {
169 return clear_current_profile(pkgname, user, /*is_secondary_dex*/false);
170}
171
Jeff Sharkey90aff262016-12-12 14:28:24 -0700172static int split_count(const char *str)
173{
174 char *ctx;
175 int count = 0;
176 char buf[kPropertyValueMax];
177
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600178 strlcpy(buf, str, sizeof(buf));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700179 char *pBuf = buf;
180
181 while(strtok_r(pBuf, " ", &ctx) != NULL) {
182 count++;
183 pBuf = NULL;
184 }
185
186 return count;
187}
188
189static int split(char *buf, const char **argv)
190{
191 char *ctx;
192 int count = 0;
193 char *tok;
194 char *pBuf = buf;
195
196 while((tok = strtok_r(pBuf, " ", &ctx)) != NULL) {
197 argv[count++] = tok;
198 pBuf = NULL;
199 }
200
201 return count;
202}
203
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700204static const char* get_location_from_path(const char* path) {
205 static constexpr char kLocationSeparator = '/';
206 const char *location = strrchr(path, kLocationSeparator);
207 if (location == NULL) {
208 return path;
209 } else {
210 // Skip the separator character.
211 return location + 1;
212 }
213}
214
Jeff Sharkey90aff262016-12-12 14:28:24 -0700215static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
216 const char* input_file_name, const char* output_file_name, int swap_fd,
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100217 const char* instruction_set, const char* compiler_filter,
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700218 bool debuggable, bool post_bootcomplete, bool background_job_compile, int profile_fd,
David Sehra3b5ab62017-10-25 14:27:29 -0700219 const char* class_loader_context) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700220 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
221
222 if (strlen(instruction_set) >= MAX_INSTRUCTION_SET_LEN) {
223 ALOGE("Instruction set %s longer than max length of %d",
224 instruction_set, MAX_INSTRUCTION_SET_LEN);
225 return;
226 }
227
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700228 // Get the relative path to the input file.
229 const char* relative_input_file_name = get_location_from_path(input_file_name);
230
Jeff Sharkey90aff262016-12-12 14:28:24 -0700231 char dex2oat_Xms_flag[kPropertyValueMax];
232 bool have_dex2oat_Xms_flag = get_property("dalvik.vm.dex2oat-Xms", dex2oat_Xms_flag, NULL) > 0;
233
234 char dex2oat_Xmx_flag[kPropertyValueMax];
235 bool have_dex2oat_Xmx_flag = get_property("dalvik.vm.dex2oat-Xmx", dex2oat_Xmx_flag, NULL) > 0;
236
237 char dex2oat_threads_buf[kPropertyValueMax];
238 bool have_dex2oat_threads_flag = get_property(post_bootcomplete
239 ? "dalvik.vm.dex2oat-threads"
240 : "dalvik.vm.boot-dex2oat-threads",
241 dex2oat_threads_buf,
242 NULL) > 0;
243 char dex2oat_threads_arg[kPropertyValueMax + 2];
244 if (have_dex2oat_threads_flag) {
245 sprintf(dex2oat_threads_arg, "-j%s", dex2oat_threads_buf);
246 }
247
248 char dex2oat_isa_features_key[kPropertyKeyMax];
249 sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", instruction_set);
250 char dex2oat_isa_features[kPropertyValueMax];
251 bool have_dex2oat_isa_features = get_property(dex2oat_isa_features_key,
252 dex2oat_isa_features, NULL) > 0;
253
254 char dex2oat_isa_variant_key[kPropertyKeyMax];
255 sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
256 char dex2oat_isa_variant[kPropertyValueMax];
257 bool have_dex2oat_isa_variant = get_property(dex2oat_isa_variant_key,
258 dex2oat_isa_variant, NULL) > 0;
259
260 const char *dex2oat_norelocation = "-Xnorelocate";
261 bool have_dex2oat_relocation_skip_flag = false;
262
263 char dex2oat_flags[kPropertyValueMax];
264 int dex2oat_flags_count = get_property("dalvik.vm.dex2oat-flags",
265 dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
266 ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags);
267
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100268 // If we are booting without the real /data, don't spend time compiling.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700269 char vold_decrypt[kPropertyValueMax];
270 bool have_vold_decrypt = get_property("vold.decrypt", vold_decrypt, "") > 0;
271 bool skip_compilation = (have_vold_decrypt &&
272 (strcmp(vold_decrypt, "trigger_restart_min_framework") == 0 ||
273 (strcmp(vold_decrypt, "1") == 0)));
274
275 bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
276
277 char app_image_format[kPropertyValueMax];
278 char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
279 bool have_app_image_format =
280 image_fd >= 0 && get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
281 if (have_app_image_format) {
282 sprintf(image_format_arg, "--image-format=%s", app_image_format);
283 }
284
285 char dex2oat_large_app_threshold[kPropertyValueMax];
286 bool have_dex2oat_large_app_threshold =
287 get_property("dalvik.vm.dex2oat-very-large", dex2oat_large_app_threshold, NULL) > 0;
288 char dex2oat_large_app_threshold_arg[strlen("--very-large-app-threshold=") + kPropertyValueMax];
289 if (have_dex2oat_large_app_threshold) {
290 sprintf(dex2oat_large_app_threshold_arg,
291 "--very-large-app-threshold=%s",
292 dex2oat_large_app_threshold);
293 }
294
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700295 // If the runtime was requested to use libartd.so, we'll run dex2oatd, otherwise dex2oat.
David Sehra3b5ab62017-10-25 14:27:29 -0700296 const char* dex2oat_bin = "/system/bin/dex2oat";
297 static const char* kDex2oatDebugPath = "/system/bin/dex2oatd";
Andreas Gampea73a0cb2017-11-02 18:14:42 -0700298 if (is_debug_runtime() || (background_job_compile && is_debuggable_build())) {
David Sehra3b5ab62017-10-25 14:27:29 -0700299 DCHECK(access(kDex2oatDebugPath, X_OK) == 0);
300 dex2oat_bin = kDex2oatDebugPath;
301 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700302
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700303 bool generate_minidebug_info = kEnableMinidebugInfo &&
304 android::base::GetBoolProperty(kMinidebugInfoSystemProperty,
305 kMinidebugInfoSystemPropertyDefault);
306
Jeff Sharkey90aff262016-12-12 14:28:24 -0700307 static const char* RUNTIME_ARG = "--runtime-arg";
308
309 static const int MAX_INT_LEN = 12; // '-'+10dig+'\0' -OR- 0x+8dig
310
George Burgess IV36cebe772017-01-25 11:52:01 -0800311 // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
312 // use arraysize instead.
313 char zip_fd_arg[arraysize("--zip-fd=") + MAX_INT_LEN];
314 char zip_location_arg[arraysize("--zip-location=") + PKG_PATH_MAX];
315 char input_vdex_fd_arg[arraysize("--input-vdex-fd=") + MAX_INT_LEN];
316 char output_vdex_fd_arg[arraysize("--output-vdex-fd=") + MAX_INT_LEN];
317 char oat_fd_arg[arraysize("--oat-fd=") + MAX_INT_LEN];
318 char oat_location_arg[arraysize("--oat-location=") + PKG_PATH_MAX];
319 char instruction_set_arg[arraysize("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
320 char instruction_set_variant_arg[arraysize("--instruction-set-variant=") + kPropertyValueMax];
321 char instruction_set_features_arg[arraysize("--instruction-set-features=") + kPropertyValueMax];
322 char dex2oat_Xms_arg[arraysize("-Xms") + kPropertyValueMax];
323 char dex2oat_Xmx_arg[arraysize("-Xmx") + kPropertyValueMax];
324 char dex2oat_compiler_filter_arg[arraysize("--compiler-filter=") + kPropertyValueMax];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700325 bool have_dex2oat_swap_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800326 char dex2oat_swap_fd[arraysize("--swap-fd=") + MAX_INT_LEN];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700327 bool have_dex2oat_image_fd = false;
George Burgess IV36cebe772017-01-25 11:52:01 -0800328 char dex2oat_image_fd[arraysize("--app-image-fd=") + MAX_INT_LEN];
Calin Juravle52c45822017-07-13 22:50:21 -0700329 size_t class_loader_context_size = arraysize("--class-loader-context=") + PKG_PATH_MAX;
330 char class_loader_context_arg[class_loader_context_size];
331 if (class_loader_context != nullptr) {
332 snprintf(class_loader_context_arg, class_loader_context_size, "--class-loader-context=%s",
333 class_loader_context);
334 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700335
336 sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700337 sprintf(zip_location_arg, "--zip-location=%s", relative_input_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700338 sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
339 sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
340 sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
341 sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
342 sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
343 sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
344 sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
345 if (swap_fd >= 0) {
346 have_dex2oat_swap_fd = true;
347 sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
348 }
349 if (image_fd >= 0) {
350 have_dex2oat_image_fd = true;
351 sprintf(dex2oat_image_fd, "--app-image-fd=%d", image_fd);
352 }
353
354 if (have_dex2oat_Xms_flag) {
355 sprintf(dex2oat_Xms_arg, "-Xms%s", dex2oat_Xms_flag);
356 }
357 if (have_dex2oat_Xmx_flag) {
358 sprintf(dex2oat_Xmx_arg, "-Xmx%s", dex2oat_Xmx_flag);
359 }
360
361 // Compute compiler filter.
362
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100363 bool have_dex2oat_compiler_filter_flag = false;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700364 if (skip_compilation) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600365 strlcpy(dex2oat_compiler_filter_arg, "--compiler-filter=extract",
366 sizeof(dex2oat_compiler_filter_arg));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700367 have_dex2oat_compiler_filter_flag = true;
368 have_dex2oat_relocation_skip_flag = true;
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100369 } else if (compiler_filter != nullptr) {
370 if (strlen(compiler_filter) + strlen("--compiler-filter=") <
Jeff Sharkey90aff262016-12-12 14:28:24 -0700371 arraysize(dex2oat_compiler_filter_arg)) {
Nicolas Geoffraybe6ecd62017-05-03 13:21:37 +0100372 sprintf(dex2oat_compiler_filter_arg, "--compiler-filter=%s", compiler_filter);
373 have_dex2oat_compiler_filter_flag = true;
374 } else {
375 ALOGW("Compiler filter name '%s' is too large (max characters is %zu)",
376 compiler_filter,
377 kPropertyValueMax);
378 }
379 }
380
381 if (!have_dex2oat_compiler_filter_flag) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700382 char dex2oat_compiler_filter_flag[kPropertyValueMax];
383 have_dex2oat_compiler_filter_flag = get_property("dalvik.vm.dex2oat-filter",
384 dex2oat_compiler_filter_flag, NULL) > 0;
385 if (have_dex2oat_compiler_filter_flag) {
386 sprintf(dex2oat_compiler_filter_arg,
387 "--compiler-filter=%s",
388 dex2oat_compiler_filter_flag);
389 }
390 }
391
392 // Check whether all apps should be compiled debuggable.
393 if (!debuggable) {
394 char prop_buf[kPropertyValueMax];
395 debuggable =
396 (get_property("dalvik.vm.always_debuggable", prop_buf, "0") > 0) &&
397 (prop_buf[0] == '1');
398 }
399 char profile_arg[strlen("--profile-file-fd=") + MAX_INT_LEN];
400 if (profile_fd != -1) {
401 sprintf(profile_arg, "--profile-file-fd=%d", profile_fd);
402 }
403
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700404 // Get the directory of the apk to pass as a base classpath directory.
405 char base_dir[arraysize("--classpath-dir=") + PKG_PATH_MAX];
406 std::string apk_dir(input_file_name);
407 unsigned long dir_index = apk_dir.rfind('/');
408 bool has_base_dir = dir_index != std::string::npos;
409 if (has_base_dir) {
410 apk_dir = apk_dir.substr(0, dir_index);
411 sprintf(base_dir, "--classpath-dir=%s", apk_dir.c_str());
412 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700413
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700414
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700415 ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700416
417 const char* argv[9 // program name, mandatory arguments and the final NULL
418 + (have_dex2oat_isa_variant ? 1 : 0)
419 + (have_dex2oat_isa_features ? 1 : 0)
420 + (have_dex2oat_Xms_flag ? 2 : 0)
421 + (have_dex2oat_Xmx_flag ? 2 : 0)
422 + (have_dex2oat_compiler_filter_flag ? 1 : 0)
423 + (have_dex2oat_threads_flag ? 1 : 0)
424 + (have_dex2oat_swap_fd ? 1 : 0)
425 + (have_dex2oat_image_fd ? 1 : 0)
426 + (have_dex2oat_relocation_skip_flag ? 2 : 0)
427 + (generate_debug_info ? 1 : 0)
428 + (debuggable ? 1 : 0)
429 + (have_app_image_format ? 1 : 0)
430 + dex2oat_flags_count
431 + (profile_fd == -1 ? 0 : 1)
Calin Juravle52c45822017-07-13 22:50:21 -0700432 + (class_loader_context != nullptr ? 1 : 0)
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700433 + (has_base_dir ? 1 : 0)
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700434 + (have_dex2oat_large_app_threshold ? 1 : 0)
435 + (generate_minidebug_info ? 1 : 0)];
Jeff Sharkey90aff262016-12-12 14:28:24 -0700436 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700437 argv[i++] = dex2oat_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700438 argv[i++] = zip_fd_arg;
439 argv[i++] = zip_location_arg;
440 argv[i++] = input_vdex_fd_arg;
441 argv[i++] = output_vdex_fd_arg;
442 argv[i++] = oat_fd_arg;
443 argv[i++] = oat_location_arg;
444 argv[i++] = instruction_set_arg;
445 if (have_dex2oat_isa_variant) {
446 argv[i++] = instruction_set_variant_arg;
447 }
448 if (have_dex2oat_isa_features) {
449 argv[i++] = instruction_set_features_arg;
450 }
451 if (have_dex2oat_Xms_flag) {
452 argv[i++] = RUNTIME_ARG;
453 argv[i++] = dex2oat_Xms_arg;
454 }
455 if (have_dex2oat_Xmx_flag) {
456 argv[i++] = RUNTIME_ARG;
457 argv[i++] = dex2oat_Xmx_arg;
458 }
459 if (have_dex2oat_compiler_filter_flag) {
460 argv[i++] = dex2oat_compiler_filter_arg;
461 }
462 if (have_dex2oat_threads_flag) {
463 argv[i++] = dex2oat_threads_arg;
464 }
465 if (have_dex2oat_swap_fd) {
466 argv[i++] = dex2oat_swap_fd;
467 }
468 if (have_dex2oat_image_fd) {
469 argv[i++] = dex2oat_image_fd;
470 }
471 if (generate_debug_info) {
472 argv[i++] = "--generate-debug-info";
473 }
474 if (debuggable) {
475 argv[i++] = "--debuggable";
476 }
477 if (have_app_image_format) {
478 argv[i++] = image_format_arg;
479 }
480 if (have_dex2oat_large_app_threshold) {
481 argv[i++] = dex2oat_large_app_threshold_arg;
482 }
483 if (dex2oat_flags_count) {
484 i += split(dex2oat_flags, argv + i);
485 }
486 if (have_dex2oat_relocation_skip_flag) {
487 argv[i++] = RUNTIME_ARG;
488 argv[i++] = dex2oat_norelocation;
489 }
490 if (profile_fd != -1) {
491 argv[i++] = profile_arg;
492 }
Jeff Hao10b8a6e2017-04-05 17:11:39 -0700493 if (has_base_dir) {
494 argv[i++] = base_dir;
495 }
Calin Juravle52c45822017-07-13 22:50:21 -0700496 if (class_loader_context != nullptr) {
497 argv[i++] = class_loader_context_arg;
498 }
Andreas Gampe2a2d7ba2017-11-02 19:39:29 -0700499 if (generate_minidebug_info) {
500 argv[i++] = kMinidebugDex2oatFlag;
501 }
Calin Juravle52c45822017-07-13 22:50:21 -0700502
Jeff Sharkey90aff262016-12-12 14:28:24 -0700503 // Do not add after dex2oat_flags, they should override others for debugging.
504 argv[i] = NULL;
505
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700506 execv(dex2oat_bin, (char * const *)argv);
507 ALOGE("execv(%s) failed: %s\n", dex2oat_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700508}
509
510/*
511 * Whether dexopt should use a swap file when compiling an APK.
512 *
513 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
514 * itself, anyways).
515 *
516 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
517 *
518 * Otherwise, return true if this is a low-mem device.
519 *
520 * Otherwise, return default value.
521 */
522static bool kAlwaysProvideSwapFile = false;
523static bool kDefaultProvideSwapFile = true;
524
525static bool ShouldUseSwapFileForDexopt() {
526 if (kAlwaysProvideSwapFile) {
527 return true;
528 }
529
530 // Check the "override" property. If it exists, return value == "true".
531 char dex2oat_prop_buf[kPropertyValueMax];
532 if (get_property("dalvik.vm.dex2oat-swap", dex2oat_prop_buf, "") > 0) {
533 if (strcmp(dex2oat_prop_buf, "true") == 0) {
534 return true;
535 } else {
536 return false;
537 }
538 }
539
540 // Shortcut for default value. This is an implementation optimization for the process sketched
541 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
542 // as low-mem is never returning false. The compiler will optimize this away if it can.
543 if (kDefaultProvideSwapFile) {
544 return true;
545 }
546
547 bool is_low_mem = property_get_bool("ro.config.low_ram", false);
548 if (is_low_mem) {
549 return true;
550 }
551
552 // Default value must be false here.
553 return kDefaultProvideSwapFile;
554}
555
Richard Uhler76cc0272016-12-08 10:46:35 +0000556static void SetDex2OatScheduling(bool set_to_bg) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700557 if (set_to_bg) {
558 if (set_sched_policy(0, SP_BACKGROUND) < 0) {
559 ALOGE("set_sched_policy failed: %s\n", strerror(errno));
560 exit(70);
561 }
562 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
563 ALOGE("setpriority failed: %s\n", strerror(errno));
564 exit(71);
565 }
566 }
567}
568
Calin Juravle29591732017-11-20 17:46:19 -0800569static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
570 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800571 if (fd.get() < 0) {
Calin Juravle29591732017-11-20 17:46:19 -0800572 if (errno != EEXIST) {
Calin Juravle114f0812017-03-08 19:05:07 -0800573 PLOG(ERROR) << "Failed to create profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800574 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800575 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700576 }
Calin Juravle114f0812017-03-08 19:05:07 -0800577 // Profiles should belong to the app; make sure of that by giving ownership to
578 // the app uid. If we cannot do that, there's no point in returning the fd
579 // since dex2oat/profman will fail with SElinux denials.
580 if (fchown(fd.get(), uid, uid) < 0) {
581 PLOG(ERROR) << "Could not chwon profile " << profile;
Calin Juravle29591732017-11-20 17:46:19 -0800582 return invalid_unique_fd();
Calin Juravle114f0812017-03-08 19:05:07 -0800583 }
Calin Juravle29591732017-11-20 17:46:19 -0800584 return fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800585}
586
Calin Juravle29591732017-11-20 17:46:19 -0800587static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
Calin Juravle114f0812017-03-08 19:05:07 -0800588 // Do not follow symlinks when opening a profile:
589 // - primary profiles should not contain symlinks in their paths
590 // - secondary dex paths should have been already resolved and validated
591 flags |= O_NOFOLLOW;
592
Calin Juravle29591732017-11-20 17:46:19 -0800593 // Check if we need to create the profile
594 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
595 unique_fd fd;
596 if ((flags & O_CREAT) != 0) {
597 fd = create_profile(uid, profile, flags);
598 } else {
599 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
600 }
601
Calin Juravle114f0812017-03-08 19:05:07 -0800602 if (fd.get() < 0) {
603 if (errno != ENOENT) {
604 // Profiles might be missing for various reasons. For example, in a
605 // multi-user environment, the profile directory for one user can be created
606 // after we start a merge. In this case the current profile for that user
607 // will not be found.
608 // Also, the secondary dex profiles might be deleted by the app at any time,
609 // so we can't we need to prepare if they are missing.
610 PLOG(ERROR) << "Failed to open profile " << profile;
611 }
612 return invalid_unique_fd();
613 }
614
Jeff Sharkey90aff262016-12-12 14:28:24 -0700615 return fd;
616}
617
Calin Juravle114f0812017-03-08 19:05:07 -0800618static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& location,
619 bool is_secondary_dex) {
620 std::string profile = create_current_profile_path(user, location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800621 return open_profile(uid, profile, O_RDONLY);
Calin Juravle114f0812017-03-08 19:05:07 -0800622}
623
624static unique_fd open_reference_profile(uid_t uid, const std::string& location, bool read_write,
625 bool is_secondary_dex) {
626 std::string profile = create_reference_profile_path(location, is_secondary_dex);
Calin Juravle29591732017-11-20 17:46:19 -0800627 return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
628}
629
630static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
631 const std::string& code_path) {
632 std::string profile = create_snapshot_profile_path(package_name, code_path);
633 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
Calin Juravle114f0812017-03-08 19:05:07 -0800634}
635
636static void open_profile_files(uid_t uid, const std::string& location, bool is_secondary_dex,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800637 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700638 // Open the reference profile in read-write mode as profman might need to save the merge.
Calin Juravle114f0812017-03-08 19:05:07 -0800639 *reference_profile_fd = open_reference_profile(uid, location, /*read_write*/ true,
640 is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700641
Calin Juravle114f0812017-03-08 19:05:07 -0800642 // For secondary dex files, we don't really need the user but we use it for sanity checks.
643 // Note: the user owning the dex file should be the current user.
644 std::vector<userid_t> users;
645 if (is_secondary_dex){
646 users.push_back(multiuser_get_user_id(uid));
647 } else {
648 users = get_known_users(/*volume_uuid*/ nullptr);
649 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700650 for (auto user : users) {
Calin Juravle114f0812017-03-08 19:05:07 -0800651 unique_fd profile_fd = open_current_profile(uid, user, location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700652 // Add to the lists only if both fds are valid.
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800653 if (profile_fd.get() >= 0) {
654 profiles_fd->push_back(std::move(profile_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700655 }
656 }
657}
658
659static void drop_capabilities(uid_t uid) {
660 if (setgid(uid) != 0) {
661 ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
662 exit(64);
663 }
664 if (setuid(uid) != 0) {
665 ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
666 exit(65);
667 }
668 // drop capabilities
669 struct __user_cap_header_struct capheader;
670 struct __user_cap_data_struct capdata[2];
671 memset(&capheader, 0, sizeof(capheader));
672 memset(&capdata, 0, sizeof(capdata));
673 capheader.version = _LINUX_CAPABILITY_VERSION_3;
674 if (capset(&capheader, &capdata[0]) < 0) {
675 ALOGE("capset failed: %s\n", strerror(errno));
676 exit(66);
677 }
678}
679
680static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
681static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
682static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
683static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
684static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
685
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800686static void run_profman_merge(const std::vector<unique_fd>& profiles_fd,
687 const unique_fd& reference_profile_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700688 static const size_t MAX_INT_LEN = 32;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700689 const char* profman_bin = is_debug_runtime() ? "/system/bin/profmand" : "/system/bin/profman";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700690
691 std::vector<std::string> profile_args(profiles_fd.size());
692 char profile_buf[strlen("--profile-file-fd=") + MAX_INT_LEN];
693 for (size_t k = 0; k < profiles_fd.size(); k++) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800694 sprintf(profile_buf, "--profile-file-fd=%d", profiles_fd[k].get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700695 profile_args[k].assign(profile_buf);
696 }
697 char reference_profile_arg[strlen("--reference-profile-file-fd=") + MAX_INT_LEN];
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800698 sprintf(reference_profile_arg, "--reference-profile-file-fd=%d", reference_profile_fd.get());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700699
700 // program name, reference profile fd, the final NULL and the profile fds
701 const char* argv[3 + profiles_fd.size()];
702 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700703 argv[i++] = profman_bin;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700704 argv[i++] = reference_profile_arg;
705 for (size_t k = 0; k < profile_args.size(); k++) {
706 argv[i++] = profile_args[k].c_str();
707 }
708 // Do not add after dex2oat_flags, they should override others for debugging.
709 argv[i] = NULL;
710
Andreas Gampe6a9cf722017-07-24 16:49:10 -0700711 execv(profman_bin, (char * const *)argv);
712 ALOGE("execv(%s) failed: %s\n", profman_bin, strerror(errno));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700713 exit(68); /* only get here on exec failure */
714}
715
716// Decides if profile guided compilation is needed or not based on existing profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800717// The location is the package name for primary apks or the dex path for secondary dex files.
718// Returns true if there is enough information in the current profiles that makes it
719// worth to recompile the given location.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700720// If the return value is true all the current profiles would have been merged into
721// the reference profiles accessible with open_reference_profile().
Calin Juravle114f0812017-03-08 19:05:07 -0800722static bool analyze_profiles(uid_t uid, const std::string& location, bool is_secondary_dex) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800723 std::vector<unique_fd> profiles_fd;
724 unique_fd reference_profile_fd;
Calin Juravle114f0812017-03-08 19:05:07 -0800725 open_profile_files(uid, location, is_secondary_dex, &profiles_fd, &reference_profile_fd);
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800726 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700727 // Skip profile guided compilation because no profiles were found.
728 // Or if the reference profile info couldn't be opened.
Jeff Sharkey90aff262016-12-12 14:28:24 -0700729 return false;
730 }
731
Jeff Sharkey90aff262016-12-12 14:28:24 -0700732 pid_t pid = fork();
733 if (pid == 0) {
734 /* child -- drop privileges before continuing */
735 drop_capabilities(uid);
736 run_profman_merge(profiles_fd, reference_profile_fd);
737 exit(68); /* only get here on exec failure */
738 }
739 /* parent */
740 int return_code = wait_child(pid);
741 bool need_to_compile = false;
742 bool should_clear_current_profiles = false;
743 bool should_clear_reference_profile = false;
744 if (!WIFEXITED(return_code)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800745 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700746 } else {
747 return_code = WEXITSTATUS(return_code);
748 switch (return_code) {
749 case PROFMAN_BIN_RETURN_CODE_COMPILE:
750 need_to_compile = true;
751 should_clear_current_profiles = true;
752 should_clear_reference_profile = false;
753 break;
754 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
755 need_to_compile = false;
756 should_clear_current_profiles = false;
757 should_clear_reference_profile = false;
758 break;
759 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
Calin Juravle114f0812017-03-08 19:05:07 -0800760 LOG(WARNING) << "Bad profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700761 need_to_compile = false;
762 should_clear_current_profiles = true;
763 should_clear_reference_profile = true;
764 break;
765 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
766 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
767 // Temporary IO problem (e.g. locking). Ignore but log a warning.
Calin Juravle114f0812017-03-08 19:05:07 -0800768 LOG(WARNING) << "IO error while reading profiles for location " << location;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700769 need_to_compile = false;
770 should_clear_current_profiles = false;
771 should_clear_reference_profile = false;
772 break;
773 default:
774 // Unknown return code or error. Unlink profiles.
Calin Juravle114f0812017-03-08 19:05:07 -0800775 LOG(WARNING) << "Unknown error code while processing profiles for location "
776 << location << ": " << return_code;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700777 need_to_compile = false;
778 should_clear_current_profiles = true;
779 should_clear_reference_profile = true;
780 break;
781 }
782 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800783
Jeff Sharkey90aff262016-12-12 14:28:24 -0700784 if (should_clear_current_profiles) {
Calin Juravle114f0812017-03-08 19:05:07 -0800785 if (is_secondary_dex) {
786 // For secondary dex files, the owning user is the current user.
787 clear_current_profile(location, multiuser_get_user_id(uid), is_secondary_dex);
788 } else {
789 clear_primary_current_profiles(location);
790 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700791 }
792 if (should_clear_reference_profile) {
Calin Juravle114f0812017-03-08 19:05:07 -0800793 clear_reference_profile(location, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700794 }
795 return need_to_compile;
796}
797
Calin Juravle114f0812017-03-08 19:05:07 -0800798// Decides if profile guided compilation is needed or not based on existing profiles.
799// The analysis is done for the primary apks of the given package.
800// Returns true if there is enough information in the current profiles that makes it
801// worth to recompile the package.
802// If the return value is true all the current profiles would have been merged into
803// the reference profiles accessible with open_reference_profile().
804bool analyze_primary_profiles(uid_t uid, const std::string& pkgname) {
805 return analyze_profiles(uid, pkgname, /*is_secondary_dex*/false);
806}
807
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800808static void run_profman_dump(const std::vector<unique_fd>& profile_fds,
809 const unique_fd& reference_profile_fd,
Jeff Sharkey90aff262016-12-12 14:28:24 -0700810 const std::vector<std::string>& dex_locations,
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800811 const std::vector<unique_fd>& apk_fds,
812 const unique_fd& output_fd) {
Jeff Sharkey90aff262016-12-12 14:28:24 -0700813 std::vector<std::string> profman_args;
814 static const char* PROFMAN_BIN = "/system/bin/profman";
815 profman_args.push_back(PROFMAN_BIN);
816 profman_args.push_back("--dump-only");
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800817 profman_args.push_back(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700818 if (reference_profile_fd != -1) {
819 profman_args.push_back(StringPrintf("--reference-profile-file-fd=%d",
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800820 reference_profile_fd.get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700821 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800822 for (size_t i = 0; i < profile_fds.size(); i++) {
823 profman_args.push_back(StringPrintf("--profile-file-fd=%d", profile_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700824 }
825 for (const std::string& dex_location : dex_locations) {
826 profman_args.push_back(StringPrintf("--dex-location=%s", dex_location.c_str()));
827 }
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800828 for (size_t i = 0; i < apk_fds.size(); i++) {
829 profman_args.push_back(StringPrintf("--apk-fd=%d", apk_fds[i].get()));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700830 }
831 const char **argv = new const char*[profman_args.size() + 1];
832 size_t i = 0;
833 for (const std::string& profman_arg : profman_args) {
834 argv[i++] = profman_arg.c_str();
835 }
836 argv[i] = NULL;
837
838 execv(PROFMAN_BIN, (char * const *)argv);
839 ALOGE("execv(%s) failed: %s\n", PROFMAN_BIN, strerror(errno));
840 exit(68); /* only get here on exec failure */
841}
842
Calin Juravle76268c52017-03-09 13:19:42 -0800843bool dump_profiles(int32_t uid, const std::string& pkgname, const char* code_paths) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800844 std::vector<unique_fd> profile_fds;
845 unique_fd reference_profile_fd;
Calin Juravle76268c52017-03-09 13:19:42 -0800846 std::string out_file_name = StringPrintf("/data/misc/profman/%s.txt", pkgname.c_str());
Jeff Sharkey90aff262016-12-12 14:28:24 -0700847
Calin Juravle114f0812017-03-08 19:05:07 -0800848 open_profile_files(uid, pkgname, /*is_secondary_dex*/false,
849 &profile_fds, &reference_profile_fd);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700850
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800851 const bool has_reference_profile = (reference_profile_fd.get() != -1);
Jeff Sharkey90aff262016-12-12 14:28:24 -0700852 const bool has_profiles = !profile_fds.empty();
853
854 if (!has_reference_profile && !has_profiles) {
Calin Juravle76268c52017-03-09 13:19:42 -0800855 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700856 return false;
857 }
858
Calin Juravle114f0812017-03-08 19:05:07 -0800859 unique_fd output_fd(open(out_file_name.c_str(),
860 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700861 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
862 ALOGE("installd cannot chmod '%s' dump_profile\n", out_file_name.c_str());
863 return false;
864 }
865 std::vector<std::string> code_full_paths = base::Split(code_paths, ";");
866 std::vector<std::string> dex_locations;
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800867 std::vector<unique_fd> apk_fds;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700868 for (const std::string& code_full_path : code_full_paths) {
869 const char* full_path = code_full_path.c_str();
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800870 unique_fd apk_fd(open(full_path, O_RDONLY | O_NOFOLLOW));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700871 if (apk_fd == -1) {
872 ALOGE("installd cannot open '%s'\n", full_path);
873 return false;
874 }
875 dex_locations.push_back(get_location_from_path(full_path));
Calin Juravle1a0af3b2017-03-09 14:33:33 -0800876 apk_fds.push_back(std::move(apk_fd));
Jeff Sharkey90aff262016-12-12 14:28:24 -0700877 }
878
879 pid_t pid = fork();
880 if (pid == 0) {
881 /* child -- drop privileges before continuing */
882 drop_capabilities(uid);
883 run_profman_dump(profile_fds, reference_profile_fd, dex_locations,
884 apk_fds, output_fd);
885 exit(68); /* only get here on exec failure */
886 }
887 /* parent */
Jeff Sharkey90aff262016-12-12 14:28:24 -0700888 int return_code = wait_child(pid);
889 if (!WIFEXITED(return_code)) {
890 LOG(WARNING) << "profman failed for package " << pkgname << ": "
891 << return_code;
892 return false;
893 }
894 return true;
895}
896
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700897bool copy_system_profile(const std::string& system_profile,
898 uid_t packageUid, const std::string& data_profile_location) {
899 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
900 unique_fd out_fd(open_reference_profile(packageUid,
901 data_profile_location,
902 /*read_write*/ true,
903 /*secondary*/ false));
904 if (in_fd.get() < 0) {
905 PLOG(WARNING) << "Could not open profile " << system_profile;
906 return false;
907 }
908 if (out_fd.get() < 0) {
909 PLOG(WARNING) << "Could not open profile " << data_profile_location;
910 return false;
911 }
912
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700913 // As a security measure we want to write the profile information with the reduced capabilities
914 // of the package user id. So we fork and drop capabilities in the child.
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700915 pid_t pid = fork();
916 if (pid == 0) {
917 /* child -- drop privileges before continuing */
918 drop_capabilities(packageUid);
919
920 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
921 if (errno != EWOULDBLOCK) {
922 PLOG(WARNING) << "Error locking profile " << data_profile_location;
923 }
924 // This implies that the app owning this profile is running
925 // (and has acquired the lock).
926 //
927 // The app never acquires the lock for the reference profiles of primary apks.
928 // Only dex2oat from installd will do that. Since installd is single threaded
929 // we should not see this case. Nevertheless be prepared for it.
930 PLOG(WARNING) << "Failed to flock " << data_profile_location;
931 return false;
932 }
933
934 bool truncated = ftruncate(out_fd.get(), 0) == 0;
935 if (!truncated) {
936 PLOG(WARNING) << "Could not truncate " << data_profile_location;
937 }
938
939 // Copy over data.
940 static constexpr size_t kBufferSize = 4 * 1024;
941 char buffer[kBufferSize];
942 while (true) {
943 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
944 if (bytes == 0) {
945 break;
946 }
947 write(out_fd.get(), buffer, bytes);
948 }
949 if (flock(out_fd.get(), LOCK_UN) != 0) {
950 PLOG(WARNING) << "Error unlocking profile " << data_profile_location;
951 }
Mathieu Chartier78f71fe2017-06-14 13:02:26 -0700952 // Use _exit since we don't want to run the global destructors in the child.
953 // b/62597429
954 _exit(0);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -0700955 }
956 /* parent */
957 int return_code = wait_child(pid);
958 return return_code == 0;
959}
960
Jeff Sharkey90aff262016-12-12 14:28:24 -0700961static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
962 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
963 if (EndsWith(oat_path, ".dex")) {
964 std::string new_path = oat_path;
965 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
966 CHECK(EndsWith(new_path, new_ext.c_str()));
967 return new_path;
968 }
969
970 // An odex entry. Not that this may not be an extension, e.g., in the OTA
971 // case (where the base name will have an extension for the B artifact).
972 size_t odex_pos = oat_path.rfind(".odex");
973 if (odex_pos != std::string::npos) {
974 std::string new_path = oat_path;
975 new_path.replace(odex_pos, strlen(".odex"), new_ext);
976 CHECK_NE(new_path.find(new_ext), std::string::npos);
977 return new_path;
978 }
979
980 // Don't know how to handle this.
981 return "";
982}
983
984// Translate the given oat path to an art (app image) path. An empty string
985// denotes an error.
986static std::string create_image_filename(const std::string& oat_path) {
987 return replace_file_extension(oat_path, ".art");
988}
989
990// Translate the given oat path to a vdex path. An empty string denotes an error.
991static std::string create_vdex_filename(const std::string& oat_path) {
992 return replace_file_extension(oat_path, ".vdex");
993}
994
Jeff Sharkey90aff262016-12-12 14:28:24 -0700995static int open_output_file(const char* file_name, bool recreate, int permissions) {
996 int flags = O_RDWR | O_CREAT;
997 if (recreate) {
998 if (unlink(file_name) < 0) {
999 if (errno != ENOENT) {
1000 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
1001 }
1002 }
1003 flags |= O_EXCL;
1004 }
1005 return open(file_name, flags, permissions);
1006}
1007
Calin Juravle2289c0a2017-02-15 12:44:14 -08001008static bool set_permissions_and_ownership(
1009 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
1010 // Primary apks are owned by the system. Secondary dex files are owned by the app.
1011 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001012 if (fchmod(fd,
1013 S_IRUSR|S_IWUSR|S_IRGRP |
1014 (is_public ? S_IROTH : 0)) < 0) {
1015 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
1016 return false;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001017 } else if (fchown(fd, owning_uid, uid) < 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001018 ALOGE("installd cannot chown '%s' during dexopt\n", path);
1019 return false;
1020 }
1021 return true;
1022}
1023
1024static bool IsOutputDalvikCache(const char* oat_dir) {
1025 // InstallerConnection.java (which invokes installd) transforms Java null arguments
1026 // into '!'. Play it safe by handling it both.
1027 // TODO: ensure we never get null.
1028 // TODO: pass a flag instead of inferring if the output is dalvik cache.
1029 return oat_dir == nullptr || oat_dir[0] == '!';
1030}
1031
Calin Juravled23dee72017-07-06 16:29:11 -07001032// Best-effort check whether we can fit the the path into our buffers.
1033// Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
1034// without a swap file, if necessary. Reference profiles file also add an extra ".prof"
1035// extension to the cache path (5 bytes).
1036// TODO(calin): move away from char* buffers and PKG_PATH_MAX.
1037static bool validate_dex_path_size(const std::string& dex_path) {
1038 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
1039 LOG(ERROR) << "dex_path too long: " << dex_path;
1040 return false;
1041 }
1042 return true;
1043}
1044
Jeff Sharkey90aff262016-12-12 14:28:24 -07001045static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001046 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
Calin Juravled23dee72017-07-06 16:29:11 -07001047 if (!validate_dex_path_size(apk_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001048 return false;
1049 }
1050
1051 if (!IsOutputDalvikCache(oat_dir)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001052 // Oat dirs for secondary dex files are already validated.
1053 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001054 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
1055 return false;
1056 }
1057 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
1058 return false;
1059 }
1060 } else {
1061 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
1062 return false;
1063 }
1064 }
1065 return true;
1066}
1067
1068// Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
1069// on destruction. It will also run the given cleanup (unless told not to) after closing.
1070//
1071// Usage example:
1072//
Calin Juravle7a570e82017-01-14 16:23:30 -08001073// Dex2oatFileWrapper file(open(...),
Jeff Sharkey90aff262016-12-12 14:28:24 -07001074// [name]() {
1075// unlink(name.c_str());
1076// });
1077// // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
1078// wrapper if captured as a reference.
1079//
1080// if (file.get() == -1) {
1081// // Error opening...
1082// }
1083//
1084// ...
1085// if (error) {
1086// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
1087// // and delete the file (after the fd is closed).
1088// return -1;
1089// }
1090//
1091// (Success case)
1092// file.SetCleanup(false);
1093// // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
1094// // (leaving the file around; after the fd is closed).
1095//
Jeff Sharkey90aff262016-12-12 14:28:24 -07001096class Dex2oatFileWrapper {
1097 public:
Calin Juravle7a570e82017-01-14 16:23:30 -08001098 Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001099 }
1100
Calin Juravle7a570e82017-01-14 16:23:30 -08001101 Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
1102 : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
1103
1104 Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
1105 value_ = other.value_;
1106 cleanup_ = other.cleanup_;
1107 do_cleanup_ = other.do_cleanup_;
1108 auto_close_ = other.auto_close_;
1109 other.release();
1110 }
1111
1112 Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
1113 value_ = other.value_;
1114 cleanup_ = other.cleanup_;
1115 do_cleanup_ = other.do_cleanup_;
1116 auto_close_ = other.auto_close_;
1117 other.release();
1118 return *this;
1119 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001120
1121 ~Dex2oatFileWrapper() {
1122 reset(-1);
1123 }
1124
1125 int get() {
1126 return value_;
1127 }
1128
1129 void SetCleanup(bool cleanup) {
1130 do_cleanup_ = cleanup;
1131 }
1132
1133 void reset(int new_value) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001134 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001135 close(value_);
1136 }
1137 if (do_cleanup_ && cleanup_ != nullptr) {
1138 cleanup_();
1139 }
1140
1141 value_ = new_value;
1142 }
1143
Calin Juravle7a570e82017-01-14 16:23:30 -08001144 void reset(int new_value, std::function<void ()> new_cleanup) {
1145 if (auto_close_ && value_ >= 0) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001146 close(value_);
1147 }
1148 if (do_cleanup_ && cleanup_ != nullptr) {
1149 cleanup_();
1150 }
1151
1152 value_ = new_value;
1153 cleanup_ = new_cleanup;
1154 }
1155
Calin Juravle7a570e82017-01-14 16:23:30 -08001156 void DisableAutoClose() {
1157 auto_close_ = false;
1158 }
1159
Jeff Sharkey90aff262016-12-12 14:28:24 -07001160 private:
Calin Juravle7a570e82017-01-14 16:23:30 -08001161 void release() {
1162 value_ = -1;
1163 do_cleanup_ = false;
1164 cleanup_ = nullptr;
1165 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001166 int value_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001167 std::function<void ()> cleanup_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001168 bool do_cleanup_;
Calin Juravle7a570e82017-01-14 16:23:30 -08001169 bool auto_close_;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001170};
1171
Calin Juravle7a570e82017-01-14 16:23:30 -08001172// (re)Creates the app image if needed.
1173Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path, bool profile_guided,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001174 bool is_public, int uid, bool is_secondary_dex) {
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001175
1176 // We don't create an image for secondary dex files.
1177 if (is_secondary_dex) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001178 return Dex2oatFileWrapper();
1179 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001180
Calin Juravle7a570e82017-01-14 16:23:30 -08001181 const std::string image_path = create_image_filename(out_oat_path);
1182 if (image_path.empty()) {
1183 // Happens when the out_oat_path has an unknown extension.
1184 return Dex2oatFileWrapper();
1185 }
Nicolas Geoffrayaa17ab42017-08-15 14:51:05 +01001186
1187 // Use app images only if it is enabled (by a set image format) and we are compiling
1188 // profile-guided (so the app image doesn't conservatively contain all classes).
1189 if (!profile_guided) {
1190 // In case there is a stale image, remove it now. Ignore any error.
1191 unlink(image_path.c_str());
1192 return Dex2oatFileWrapper();
1193 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001194 char app_image_format[kPropertyValueMax];
1195 bool have_app_image_format =
1196 get_property("dalvik.vm.appimageformat", app_image_format, NULL) > 0;
1197 if (!have_app_image_format) {
1198 return Dex2oatFileWrapper();
1199 }
1200 // Recreate is true since we do not want to modify a mapped image. If the app is
1201 // already running and we modify the image file, it can cause crashes (b/27493510).
1202 Dex2oatFileWrapper wrapper_fd(
1203 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
1204 [image_path]() { unlink(image_path.c_str()); });
1205 if (wrapper_fd.get() < 0) {
1206 // Could not create application image file. Go on since we can compile without it.
1207 LOG(ERROR) << "installd could not create '" << image_path
1208 << "' for image file during dexopt";
1209 // If we have a valid image file path but no image fd, explicitly erase the image file.
1210 if (unlink(image_path.c_str()) < 0) {
1211 if (errno != ENOENT) {
1212 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
1213 }
1214 }
1215 } else if (!set_permissions_and_ownership(
Calin Juravle2289c0a2017-02-15 12:44:14 -08001216 wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001217 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
1218 wrapper_fd.reset(-1);
1219 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001220
Calin Juravle7a570e82017-01-14 16:23:30 -08001221 return wrapper_fd;
1222}
1223
1224// Creates the dexopt swap file if necessary and return its fd.
1225// Returns -1 if there's no need for a swap or in case of errors.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001226unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001227 if (!ShouldUseSwapFileForDexopt()) {
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001228 return invalid_unique_fd();
Calin Juravle7a570e82017-01-14 16:23:30 -08001229 }
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001230 auto swap_file_name = std::string(out_oat_path) + ".swap";
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001231 unique_fd swap_fd(open_output_file(
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001232 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
Calin Juravle7a570e82017-01-14 16:23:30 -08001233 if (swap_fd.get() < 0) {
1234 // Could not create swap file. Optimistically go on and hope that we can compile
1235 // without it.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001236 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
Calin Juravle7a570e82017-01-14 16:23:30 -08001237 } else {
1238 // Immediately unlink. We don't really want to hit flash.
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001239 if (unlink(swap_file_name.c_str()) < 0) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001240 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
1241 }
1242 }
1243 return swap_fd;
1244}
1245
1246// Opens the reference profiles if needed.
1247// 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 -08001248Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
1249 const std::string& dex_path, bool profile_guided, bool is_public, int uid,
1250 bool is_secondary_dex) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001251 // Public apps should not be compiled with profile information ever. Same goes for the special
1252 // package '*' used for the system server.
Calin Juravle114f0812017-03-08 19:05:07 -08001253 if (!profile_guided || is_public || (pkgname[0] == '*')) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001254 return Dex2oatFileWrapper();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001255 }
Calin Juravle114f0812017-03-08 19:05:07 -08001256
1257 // Open reference profile in read only mode as dex2oat does not get write permissions.
1258 const std::string location = is_secondary_dex ? dex_path : pkgname;
1259 unique_fd ufd = open_reference_profile(uid, location, /*read_write*/false, is_secondary_dex);
1260 const auto& cleanup = [location, is_secondary_dex]() {
1261 clear_reference_profile(location.c_str(), is_secondary_dex);
1262 };
1263 return Dex2oatFileWrapper(ufd.release(), cleanup);
Calin Juravle7a570e82017-01-14 16:23:30 -08001264}
Jeff Sharkey90aff262016-12-12 14:28:24 -07001265
Calin Juravle7a570e82017-01-14 16:23:30 -08001266// Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
1267// out_vdex_wrapper_fd. Returns true for success or false in case of errors.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001268bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001269 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001270 bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
Calin Juravle7a570e82017-01-14 16:23:30 -08001271 Dex2oatFileWrapper* out_vdex_wrapper_fd) {
1272 CHECK(in_vdex_wrapper_fd != nullptr);
1273 CHECK(out_vdex_wrapper_fd != nullptr);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001274 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1275 // unlink the old one.
Richard Uhler76cc0272016-12-08 10:46:35 +00001276 char in_odex_path[PKG_PATH_MAX];
1277 int dexopt_action = abs(dexopt_needed);
1278 bool is_odex_location = dexopt_needed < 0;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001279 std::string in_vdex_path_str;
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001280
1281 // Infer the name of the output VDEX.
1282 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1283 if (out_vdex_path_str.empty()) {
1284 return false;
1285 }
1286
1287 bool update_vdex_in_place = false;
Nicolas Geoffray3c95f2d2017-04-24 13:34:59 +00001288 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001289 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1290 const char* path = nullptr;
1291 if (is_odex_location) {
1292 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1293 path = in_odex_path;
1294 } else {
1295 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001296 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001297 }
1298 } else {
1299 path = out_oat_path;
1300 }
1301 in_vdex_path_str = create_vdex_filename(path);
1302 if (in_vdex_path_str.empty()) {
1303 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001304 return false;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001305 }
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001306 // We can update in place when all these conditions are met:
1307 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1308 // on /system typically cannot be updated in place).
1309 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1310 // cannot be currently used by a running process.
1311 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1312 // different vdex files to operate.
1313 update_vdex_in_place =
1314 (in_vdex_path_str == out_vdex_path_str) &&
1315 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1316 !profile_guided;
1317 if (update_vdex_in_place) {
1318 // Open the file read-write to be able to update it.
1319 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
1320 if (in_vdex_wrapper_fd->get() == -1) {
1321 // If we failed to open the file, we cannot update it in place.
1322 update_vdex_in_place = false;
1323 }
1324 } else {
1325 in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
1326 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001327 }
1328
Nicolas Geoffrayb03814f2017-06-05 12:38:10 +00001329 // If we are updating the vdex in place, we do not need to recreate a vdex,
1330 // and can use the same existing one.
1331 if (update_vdex_in_place) {
1332 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1333 // have bogus stale vdex files.
1334 out_vdex_wrapper_fd->reset(
1335 in_vdex_wrapper_fd->get(),
1336 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1337 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1338 // wrapper).
1339 in_vdex_wrapper_fd->DisableAutoClose();
1340 } else {
1341 out_vdex_wrapper_fd->reset(
1342 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1343 [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
1344 if (out_vdex_wrapper_fd->get() < 0) {
1345 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1346 return false;
1347 }
Jeff Sharkey90aff262016-12-12 14:28:24 -07001348 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001349 if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
Calin Juravle2289c0a2017-02-15 12:44:14 -08001350 out_vdex_path_str.c_str(), is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001351 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1352 return false;
1353 }
1354
1355 // If we got here we successfully opened the vdex files.
1356 return true;
1357}
1358
1359// Opens the output oat file for the given apk.
1360// If successful it stores the output path into out_oat_path and returns true.
1361Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
Calin Juravle80a21252017-01-17 14:43:25 -08001362 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
1363 char* out_oat_path) {
1364 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001365 return Dex2oatFileWrapper();
1366 }
1367 const std::string out_oat_path_str(out_oat_path);
1368 Dex2oatFileWrapper wrapper_fd(
1369 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1370 [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
1371 if (wrapper_fd.get() < 0) {
Calin Juravle80a21252017-01-17 14:43:25 -08001372 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
Calin Juravle2289c0a2017-02-15 12:44:14 -08001373 } else if (!set_permissions_and_ownership(
1374 wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001375 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1376 wrapper_fd.reset(-1);
1377 }
1378 return wrapper_fd;
1379}
1380
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001381// Creates RDONLY fds for oat and vdex files, if exist.
1382// Returns false if it fails to create oat out path for the given apk path.
1383// Note that the method returns true even if the files could not be opened.
1384bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1385 const std::string& oat_dir,
1386 const std::string& instruction_set,
1387 bool is_secondary_dex,
1388 unique_fd* oat_file_fd,
1389 unique_fd* vdex_file_fd) {
1390 char oat_path[PKG_PATH_MAX];
1391 if (!create_oat_out_path(apk_path.c_str(),
1392 instruction_set.c_str(),
1393 oat_dir.c_str(),
1394 is_secondary_dex,
1395 oat_path)) {
Calin Juravle46e27bc2017-09-04 15:57:10 -07001396 LOG(ERROR) << "Could not create oat out path for "
1397 << apk_path << " with oat dir " << oat_dir;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001398 return false;
1399 }
1400 oat_file_fd->reset(open(oat_path, O_RDONLY));
1401 if (oat_file_fd->get() < 0) {
1402 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1403 }
1404
1405 std::string vdex_filename = create_vdex_filename(oat_path);
1406 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1407 if (vdex_file_fd->get() < 0) {
1408 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1409 }
1410
1411 return true;
1412}
1413
Calin Juravle7a570e82017-01-14 16:23:30 -08001414// Updates the access times of out_oat_path based on those from apk_path.
1415void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
1416 struct stat input_stat;
1417 memset(&input_stat, 0, sizeof(input_stat));
1418 if (stat(apk_path, &input_stat) != 0) {
1419 PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
1420 return;
1421 }
1422
1423 struct utimbuf ut;
1424 ut.actime = input_stat.st_atime;
1425 ut.modtime = input_stat.st_mtime;
1426 if (utime(out_oat_path, &ut) != 0) {
1427 PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
1428 }
1429}
1430
Calin Juravle80a21252017-01-17 14:43:25 -08001431// Runs (execv) dexoptanalyzer on the given arguments.
Calin Juravle114f0812017-03-08 19:05:07 -08001432// The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1433// If this is for a profile guided compilation, profile_was_updated will tell whether or not
1434// the profile has changed.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001435static void exec_dexoptanalyzer(const std::string& dex_file, int vdex_fd, int oat_fd,
1436 int zip_fd, const std::string& instruction_set, const std::string& compiler_filter,
1437 bool profile_was_updated, bool downgrade,
Calin Juravle58cab072017-09-12 01:02:26 -07001438 const char* class_loader_context) {
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001439 CHECK_GE(zip_fd, 0);
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001440 const char* dexoptanalyzer_bin =
1441 is_debug_runtime()
1442 ? "/system/bin/dexoptanalyzerd"
1443 : "/system/bin/dexoptanalyzer";
Calin Juravle80a21252017-01-17 14:43:25 -08001444 static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
1445
Calin Juravled23dee72017-07-06 16:29:11 -07001446 if (instruction_set.size() >= MAX_INSTRUCTION_SET_LEN) {
1447 LOG(ERROR) << "Instruction set " << instruction_set
1448 << " longer than max length of " << MAX_INSTRUCTION_SET_LEN;
Calin Juravle80a21252017-01-17 14:43:25 -08001449 return;
1450 }
1451
Calin Juravled23dee72017-07-06 16:29:11 -07001452 std::string dex_file_arg = "--dex-file=" + dex_file;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001453 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1454 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1455 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
Calin Juravled23dee72017-07-06 16:29:11 -07001456 std::string isa_arg = "--isa=" + instruction_set;
1457 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
Calin Juravle114f0812017-03-08 19:05:07 -08001458 const char* assume_profile_changed = "--assume-profile-changed";
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001459 const char* downgrade_flag = "--downgrade";
Calin Juravle58cab072017-09-12 01:02:26 -07001460 std::string class_loader_context_arg = "--class-loader-context=";
1461 if (class_loader_context != nullptr) {
1462 class_loader_context_arg += class_loader_context;
1463 }
Calin Juravle80a21252017-01-17 14:43:25 -08001464
Calin Juravle80a21252017-01-17 14:43:25 -08001465 // program name, dex file, isa, filter, the final NULL
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001466 const int argc = 6 +
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001467 (profile_was_updated ? 1 : 0) +
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001468 (vdex_fd >= 0 ? 1 : 0) +
1469 (oat_fd >= 0 ? 1 : 0) +
Calin Juravle58cab072017-09-12 01:02:26 -07001470 (downgrade ? 1 : 0) +
1471 (class_loader_context != nullptr ? 1 : 0);
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001472 const char* argv[argc];
Calin Juravle80a21252017-01-17 14:43:25 -08001473 int i = 0;
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001474 argv[i++] = dexoptanalyzer_bin;
Calin Juravled23dee72017-07-06 16:29:11 -07001475 argv[i++] = dex_file_arg.c_str();
1476 argv[i++] = isa_arg.c_str();
1477 argv[i++] = compiler_filter_arg.c_str();
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001478 if (oat_fd >= 0) {
1479 argv[i++] = oat_fd_arg.c_str();
1480 }
1481 if (vdex_fd >= 0) {
1482 argv[i++] = vdex_fd_arg.c_str();
1483 }
1484 argv[i++] = zip_fd_arg.c_str();
Calin Juravle114f0812017-03-08 19:05:07 -08001485 if (profile_was_updated) {
1486 argv[i++] = assume_profile_changed;
1487 }
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001488 if (downgrade) {
1489 argv[i++] = downgrade_flag;
1490 }
Calin Juravle58cab072017-09-12 01:02:26 -07001491 if (class_loader_context != nullptr) {
Calin Juravle91501072017-10-26 15:44:53 -07001492 argv[i++] = class_loader_context_arg.c_str();
Calin Juravle58cab072017-09-12 01:02:26 -07001493 }
Calin Juravle80a21252017-01-17 14:43:25 -08001494 argv[i] = NULL;
1495
Andreas Gampe6a9cf722017-07-24 16:49:10 -07001496 execv(dexoptanalyzer_bin, (char * const *)argv);
1497 ALOGE("execv(%s) failed: %s\n", dexoptanalyzer_bin, strerror(errno));
Calin Juravle80a21252017-01-17 14:43:25 -08001498}
1499
1500// Prepares the oat dir for the secondary dex files.
Calin Juravle114f0812017-03-08 19:05:07 -08001501static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
Calin Juravle46e27bc2017-09-04 15:57:10 -07001502 const char* instruction_set) {
Calin Juravle114f0812017-03-08 19:05:07 -08001503 unsigned long dirIndex = dex_path.rfind('/');
Calin Juravle80a21252017-01-17 14:43:25 -08001504 if (dirIndex == std::string::npos) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001505 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001506 return false;
1507 }
Calin Juravle114f0812017-03-08 19:05:07 -08001508 std::string dex_dir = dex_path.substr(0, dirIndex);
Calin Juravle80a21252017-01-17 14:43:25 -08001509
Calin Juravle80a21252017-01-17 14:43:25 -08001510 // Create oat file output directory.
Calin Juravleebc8a792017-04-04 20:21:05 -07001511 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1512 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001513 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001514 return false;
1515 }
1516
1517 char oat_dir[PKG_PATH_MAX];
Calin Juravle114f0812017-03-08 19:05:07 -08001518 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001519
Calin Juravle46e27bc2017-09-04 15:57:10 -07001520 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001521 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001522 return false;
1523 }
1524
1525 return true;
1526}
1527
Calin Juravle46e27bc2017-09-04 15:57:10 -07001528// Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1529// secondary dex files. This return codes are returned by the child process created for
1530// analyzing secondary dex files in process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001531
Calin Juravle46e27bc2017-09-04 15:57:10 -07001532// The dexoptanalyzer was not invoked because of validation or IO errors.
1533static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED = 200;
1534// The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1535static int constexpr SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE = 201;
1536
1537// Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
Calin Juravle80a21252017-01-17 14:43:25 -08001538// If the result is valid returns true and sets dexopt_needed_out to a valid value.
1539// Returns false for errors or unexpected result values.
Calin Juravle46e27bc2017-09-04 15:57:10 -07001540// The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1541// of dexoptanalyzer.
1542static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
Calin Juravle80a21252017-01-17 14:43:25 -08001543 int* dexopt_needed_out) {
1544 // The result values are defined in dexoptanalyzer.
1545 switch (result) {
Calin Juravle46e27bc2017-09-04 15:57:10 -07001546 case 0: // dexoptanalyzer: no_dexopt_needed
Calin Juravle80a21252017-01-17 14:43:25 -08001547 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001548 case 1: // dexoptanalyzer: dex2oat_from_scratch
Calin Juravle80a21252017-01-17 14:43:25 -08001549 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001550 case 5: // dexoptanalyzer: dex2oat_for_bootimage_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001551 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001552 case 6: // dexoptanalyzer: dex2oat_for_filter_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001553 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001554 case 7: // dexoptanalyzer: dex2oat_for_relocation_odex
Calin Juravle80a21252017-01-17 14:43:25 -08001555 *dexopt_needed_out = -DEX2OAT_FOR_RELOCATION; return true;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001556 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1557 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1558 case 4: // dexoptanalyzer: dex2oat_for_relocation_oat
Calin Juravlec9eab382017-01-25 01:17:17 -08001559 LOG(ERROR) << "Dexoptnalyzer return the status of an oat file."
1560 << " Expected odex file status for secondary dex " << dex_path
Calin Juravle80a21252017-01-17 14:43:25 -08001561 << " : dexoptanalyzer result=" << result;
1562 return false;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001563 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE:
1564 // If the file does not exist there's no need for dexopt.
1565 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1566 return true;
1567 case SECONDARY_DEX_DEXOPTANALYZER_SKIPPED:
1568 return false;
Calin Juravle80a21252017-01-17 14:43:25 -08001569 default:
Calin Juravle46e27bc2017-09-04 15:57:10 -07001570 LOG(ERROR) << "Unexpected result from analyzing secondary dex " << dex_path
1571 << " result=" << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001572 return false;
1573 }
1574}
1575
Calin Juravle46e27bc2017-09-04 15:57:10 -07001576enum SecondaryDexAccess {
1577 kSecondaryDexAccessReadOk = 0,
1578 kSecondaryDexAccessDoesNotExist = 1,
1579 kSecondaryDexAccessPermissionError = 2,
1580 kSecondaryDexAccessIOError = 3
1581};
1582
1583static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1584 // Check if the path exists and can be read. If not, there's nothing to do.
1585 if (access(dex_path.c_str(), R_OK) == 0) {
1586 return kSecondaryDexAccessReadOk;
1587 } else {
1588 if (errno == ENOENT) {
1589 LOG(INFO) << "Secondary dex does not exist: " << dex_path;
1590 return kSecondaryDexAccessDoesNotExist;
1591 } else {
1592 PLOG(ERROR) << "Could not access secondary dex " << dex_path;
1593 return errno == EACCES
1594 ? kSecondaryDexAccessPermissionError
1595 : kSecondaryDexAccessIOError;
1596 }
1597 }
1598}
1599
1600static bool is_file_public(const std::string& filename) {
1601 struct stat file_stat;
1602 if (stat(filename.c_str(), &file_stat) == 0) {
1603 return (file_stat.st_mode & S_IROTH) != 0;
1604 }
1605 return false;
1606}
1607
1608// Create the oat file structure for the secondary dex 'dex_path' and assign
1609// the individual path component to the 'out_' parameters.
1610static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1611 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path) {
1612 size_t dirIndex = dex_path.rfind('/');
1613 if (dirIndex == std::string::npos) {
1614 LOG(ERROR) << "Unexpected dir structure for dex file " << dex_path;
1615 return false;
1616 }
1617 // TODO(calin): we have similar computations in at lest 3 other places
1618 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1619 // using string append.
1620 std::string apk_dir = dex_path.substr(0, dirIndex);
1621 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1622 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1623
1624 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1625 /*is_secondary_dex*/true, out_oat_path)) {
1626 LOG(ERROR) << "Could not create oat path for secondary dex " << dex_path;
1627 return false;
1628 }
1629 return true;
1630}
1631
1632// Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1633// recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
1634static bool validate_dexopt_storage_flags(int dexopt_flags, int* out_storage_flag) {
1635 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1636 *out_storage_flag = FLAG_STORAGE_CE;
1637 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1638 LOG(ERROR) << "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1639 return false;
1640 }
1641 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1642 *out_storage_flag = FLAG_STORAGE_DE;
1643 } else {
1644 LOG(ERROR) << "Secondary dex storage flag must be set";
1645 return false;
1646 }
1647 return true;
1648}
1649
Calin Juravlec9eab382017-01-25 01:17:17 -08001650// 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 -08001651// be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1652// successfully.
Calin Juravleebc8a792017-04-04 20:21:05 -07001653// When returning true, the output parameters will be:
1654// - is_public_out: whether or not the oat file should not be made public
1655// - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1656// - oat_dir_out: the oat dir path where the oat file should be stored
Calin Juravle46e27bc2017-09-04 15:57:10 -07001657static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
Calin Juravle80a21252017-01-17 14:43:25 -08001658 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
Calin Juravleebc8a792017-04-04 20:21:05 -07001659 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
Calin Juravle46e27bc2017-09-04 15:57:10 -07001660 std::string* oat_dir_out, bool downgrade, const char* class_loader_context) {
1661 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
Calin Juravle80a21252017-01-17 14:43:25 -08001662 int storage_flag;
Calin Juravle46e27bc2017-09-04 15:57:10 -07001663 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001664 return false;
1665 }
Calin Juravle46e27bc2017-09-04 15:57:10 -07001666 // Compute the oat dir as it's not easy to extract it from the child computation.
1667 char oat_path[PKG_PATH_MAX];
1668 char oat_dir[PKG_PATH_MAX];
1669 char oat_isa_dir[PKG_PATH_MAX];
1670 if (!create_secondary_dex_oat_layout(
1671 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path)) {
1672 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
Calin Juravled23dee72017-07-06 16:29:11 -07001673 return false;
1674 }
Calin Juravle46e27bc2017-09-04 15:57:10 -07001675 oat_dir_out->assign(oat_dir);
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001676
Calin Juravle80a21252017-01-17 14:43:25 -08001677 pid_t pid = fork();
1678 if (pid == 0) {
1679 // child -- drop privileges before continuing.
1680 drop_capabilities(uid);
Calin Juravle46e27bc2017-09-04 15:57:10 -07001681
1682 // Validate the path structure.
1683 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1684 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1685 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1686 }
1687
1688 // Open the dex file.
1689 unique_fd zip_fd;
1690 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1691 if (zip_fd.get() < 0) {
1692 if (errno == ENOENT) {
1693 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE);
1694 } else {
1695 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1696 }
1697 }
1698
1699 // Prepare the oat directories.
1700 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1701 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1702 }
1703
1704 // Open the vdex/oat files if any.
1705 unique_fd oat_file_fd;
1706 unique_fd vdex_file_fd;
1707 if (!maybe_open_oat_and_vdex_file(dex_path,
1708 *oat_dir_out,
1709 instruction_set,
1710 true /* is_secondary_dex */,
1711 &oat_file_fd,
1712 &vdex_file_fd)) {
1713 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
1714 }
1715
1716 // Analyze profiles.
1717 bool profile_was_updated = analyze_profiles(uid, dex_path, /*is_secondary_dex*/true);
1718
1719 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001720 exec_dexoptanalyzer(dex_path,
1721 vdex_file_fd.get(),
1722 oat_file_fd.get(),
1723 zip_fd.get(),
1724 instruction_set,
Calin Juravle46e27bc2017-09-04 15:57:10 -07001725 compiler_filter, profile_was_updated,
1726 downgrade,
1727 class_loader_context);
1728 PLOG(ERROR) << "Failed to exec dexoptanalyzer";
1729 _exit(SECONDARY_DEX_DEXOPTANALYZER_SKIPPED);
Calin Juravle80a21252017-01-17 14:43:25 -08001730 }
1731
1732 /* parent */
Calin Juravle80a21252017-01-17 14:43:25 -08001733 int result = wait_child(pid);
1734 if (!WIFEXITED(result)) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001735 LOG(ERROR) << "dexoptanalyzer failed for path " << dex_path << ": " << result;
Calin Juravle80a21252017-01-17 14:43:25 -08001736 return false;
1737 }
1738 result = WEXITSTATUS(result);
Calin Juravle46e27bc2017-09-04 15:57:10 -07001739 // Check that we successfully executed dexoptanalyzer.
1740 bool success = process_secondary_dexoptanalyzer_result(dex_path, result, dexopt_needed_out);
1741
1742 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1743
Calin Juravle80a21252017-01-17 14:43:25 -08001744 // Run dexopt only if needed or forced.
Calin Juravle46e27bc2017-09-04 15:57:10 -07001745 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1746 // makes the code simpler; force compilation is only needed during tests).
1747 if (success &&
1748 (result != SECONDARY_DEX_DEXOPTANALYZER_SKIPPED_NO_FILE) &&
1749 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001750 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1751 }
1752
Calin Juravle46e27bc2017-09-04 15:57:10 -07001753 // Check if we should make the oat file public.
1754 // Note that if the dex file is not public the compiled code cannot be made public.
1755 // It is ok to check this flag outside in the parent process.
1756 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1757
Calin Juravle80a21252017-01-17 14:43:25 -08001758 return success;
1759}
1760
Calin Juravlec9eab382017-01-25 01:17:17 -08001761int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
Calin Juravle80a21252017-01-17 14:43:25 -08001762 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
Calin Juravle52c45822017-07-13 22:50:21 -07001763 const char* volume_uuid, const char* class_loader_context, const char* se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001764 bool downgrade) {
Calin Juravle7a570e82017-01-14 16:23:30 -08001765 CHECK(pkgname != nullptr);
1766 CHECK(pkgname[0] != 0);
1767 if ((dexopt_flags & ~DEXOPT_MASK) != 0) {
1768 LOG_FATAL("dexopt flags contains unknown fields\n");
1769 }
1770
Calin Juravled23dee72017-07-06 16:29:11 -07001771 if (!validate_dex_path_size(dex_path)) {
Calin Juravle52c45822017-07-13 22:50:21 -07001772 return -1;
1773 }
1774
1775 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1776 LOG(ERROR) << "Class loader context exceeds the allowed size: " << class_loader_context;
1777 return -1;
Calin Juravled23dee72017-07-06 16:29:11 -07001778 }
1779
Calin Juravleebc8a792017-04-04 20:21:05 -07001780 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
Calin Juravle7a570e82017-01-14 16:23:30 -08001781 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1782 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1783 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001784 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001785 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001786
1787 // Check if we're dealing with a secondary dex file and if we need to compile it.
1788 std::string oat_dir_str;
1789 if (is_secondary_dex) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001790 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
Calin Juravleebc8a792017-04-04 20:21:05 -07001791 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
Calin Juravle46e27bc2017-09-04 15:57:10 -07001792 downgrade, class_loader_context)) {
Calin Juravle80a21252017-01-17 14:43:25 -08001793 oat_dir = oat_dir_str.c_str();
1794 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1795 return 0; // Nothing to do, report success.
1796 }
1797 } else {
1798 return -1; // We had an error, logged in the process method.
1799 }
1800 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001801 // Currently these flags are only use for secondary dex files.
1802 // Verify that they are not set for primary apks.
Calin Juravle80a21252017-01-17 14:43:25 -08001803 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1804 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1805 }
Calin Juravle7a570e82017-01-14 16:23:30 -08001806
1807 // Open the input file.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001808 unique_fd input_fd(open(dex_path, O_RDONLY, 0));
Calin Juravle7a570e82017-01-14 16:23:30 -08001809 if (input_fd.get() < 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001810 ALOGE("installd cannot open '%s' for input during dexopt\n", dex_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001811 return -1;
1812 }
1813
1814 // Create the output OAT file.
1815 char out_oat_path[PKG_PATH_MAX];
Calin Juravlec9eab382017-01-25 01:17:17 -08001816 Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
Calin Juravle80a21252017-01-17 14:43:25 -08001817 instruction_set, is_secondary_dex, out_oat_path);
Calin Juravle7a570e82017-01-14 16:23:30 -08001818 if (out_oat_fd.get() < 0) {
1819 return -1;
1820 }
1821
1822 // Open vdex files.
1823 Dex2oatFileWrapper in_vdex_fd;
1824 Dex2oatFileWrapper out_vdex_fd;
Shubham Ajmerab6bcd222017-10-19 10:08:03 -07001825 if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
1826 is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07001827 return -1;
1828 }
1829
Calin Juravlecb556e32017-04-04 20:22:50 -07001830 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1831 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1832 // fully inherit their parent context).
1833 // Note that for primary apk the oat files are created before, in a separate installd
1834 // call which also does the restorecon. TODO(calin): unify the paths.
1835 if (is_secondary_dex) {
1836 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1837 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1838 LOG(ERROR) << "Failed to restorecon " << oat_dir;
1839 return -1;
1840 }
1841 }
1842
Jeff Sharkey90aff262016-12-12 14:28:24 -07001843 // Create a swap file if necessary.
Calin Juravle1a0af3b2017-03-09 14:33:33 -08001844 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001845
Calin Juravle7a570e82017-01-14 16:23:30 -08001846 // Create the app image file if needed.
1847 Dex2oatFileWrapper image_fd =
Calin Juravle2289c0a2017-02-15 12:44:14 -08001848 maybe_open_app_image(out_oat_path, profile_guided, is_public, uid, is_secondary_dex);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001849
Calin Juravle7a570e82017-01-14 16:23:30 -08001850 // Open the reference profile if needed.
Calin Juravle114f0812017-03-08 19:05:07 -08001851 Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
1852 pkgname, dex_path, profile_guided, is_public, uid, is_secondary_dex);
Calin Juravle7a570e82017-01-14 16:23:30 -08001853
Calin Juravlec9eab382017-01-25 01:17:17 -08001854 ALOGV("DexInv: --- BEGIN '%s' ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001855
1856 pid_t pid = fork();
1857 if (pid == 0) {
1858 /* child -- drop privileges before continuing */
1859 drop_capabilities(uid);
1860
Richard Uhler76cc0272016-12-08 10:46:35 +00001861 SetDex2OatScheduling(boot_complete);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001862 if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
1863 ALOGE("flock(%s) failed: %s\n", out_oat_path, strerror(errno));
1864 _exit(67);
1865 }
1866
Richard Uhler76cc0272016-12-08 10:46:35 +00001867 run_dex2oat(input_fd.get(),
1868 out_oat_fd.get(),
1869 in_vdex_fd.get(),
Calin Juravle7a570e82017-01-14 16:23:30 -08001870 out_vdex_fd.get(),
Richard Uhler76cc0272016-12-08 10:46:35 +00001871 image_fd.get(),
Jeff Hao10b8a6e2017-04-05 17:11:39 -07001872 dex_path,
Richard Uhler76cc0272016-12-08 10:46:35 +00001873 out_oat_path,
1874 swap_fd.get(),
1875 instruction_set,
1876 compiler_filter,
Richard Uhler76cc0272016-12-08 10:46:35 +00001877 debuggable,
1878 boot_complete,
Andreas Gampea73a0cb2017-11-02 18:14:42 -07001879 background_job_compile,
Richard Uhler76cc0272016-12-08 10:46:35 +00001880 reference_profile_fd.get(),
Calin Juravle52c45822017-07-13 22:50:21 -07001881 class_loader_context);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001882 _exit(68); /* only get here on exec failure */
1883 } else {
1884 int res = wait_child(pid);
1885 if (res == 0) {
Calin Juravlec9eab382017-01-25 01:17:17 -08001886 ALOGV("DexInv: --- END '%s' (success) ---\n", dex_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001887 } else {
Calin Juravlec9eab382017-01-25 01:17:17 -08001888 ALOGE("DexInv: --- END '%s' --- status=0x%04x, process failed\n", dex_path, res);
Andreas Gampe013f02e2017-03-20 18:36:54 -07001889 return res;
Jeff Sharkey90aff262016-12-12 14:28:24 -07001890 }
1891 }
1892
Calin Juravlec9eab382017-01-25 01:17:17 -08001893 update_out_oat_access_times(dex_path, out_oat_path);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001894
1895 // We've been successful, don't delete output.
1896 out_oat_fd.SetCleanup(false);
Calin Juravle7a570e82017-01-14 16:23:30 -08001897 out_vdex_fd.SetCleanup(false);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001898 image_fd.SetCleanup(false);
1899 reference_profile_fd.SetCleanup(false);
1900
1901 return 0;
1902}
1903
Calin Juravlec9eab382017-01-25 01:17:17 -08001904// Try to remove the given directory. Log an error if the directory exists
1905// and is empty but could not be removed.
1906static bool rmdir_if_empty(const char* dir) {
1907 if (rmdir(dir) == 0) {
1908 return true;
1909 }
1910 if (errno == ENOENT || errno == ENOTEMPTY) {
1911 return true;
1912 }
1913 PLOG(ERROR) << "Failed to remove dir: " << dir;
1914 return false;
1915}
1916
1917// Try to unlink the given file. Log an error if the file exists and could not
1918// be unlinked.
1919static bool unlink_if_exists(const std::string& file) {
1920 if (unlink(file.c_str()) == 0) {
1921 return true;
1922 }
1923 if (errno == ENOENT) {
1924 return true;
1925
1926 }
1927 PLOG(ERROR) << "Could not unlink: " << file;
1928 return false;
1929}
1930
Calin Juravle46e27bc2017-09-04 15:57:10 -07001931enum ReconcileSecondaryDexResult {
1932 kReconcileSecondaryDexExists = 0,
1933 kReconcileSecondaryDexCleanedUp = 1,
1934 kReconcileSecondaryDexValidationError = 2,
1935 kReconcileSecondaryDexCleanUpError = 3,
1936 kReconcileSecondaryDexAccessIOError = 4,
1937};
Calin Juravlec9eab382017-01-25 01:17:17 -08001938
1939// Reconcile the secondary dex 'dex_path' and its generated oat files.
1940// Return true if all the parameters are valid and the secondary dex file was
1941// processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1942// oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1943// will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1944// the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1945// Return false if there were errors during processing. In this case
1946// out_secondary_dex_exists will be set to false.
1947bool reconcile_secondary_dex_file(const std::string& dex_path,
1948 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1949 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
1950 /*out*/bool* out_secondary_dex_exists) {
Calin Juravle46e27bc2017-09-04 15:57:10 -07001951 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
Calin Juravlec9eab382017-01-25 01:17:17 -08001952 if (isas.size() == 0) {
1953 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1954 return false;
1955 }
1956
Calin Juravle46e27bc2017-09-04 15:57:10 -07001957 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1958 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1959 << storage_flag;
Calin Juravlec9eab382017-01-25 01:17:17 -08001960 return false;
1961 }
1962
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001963 // As a security measure we want to unlink art artifacts with the reduced capabilities
1964 // of the package user id. So we fork and drop capabilities in the child.
1965 pid_t pid = fork();
1966 if (pid == 0) {
Calin Juravle46e27bc2017-09-04 15:57:10 -07001967 /* child -- drop privileges before continuing */
1968 drop_capabilities(uid);
1969
1970 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
1971 if (!validate_secondary_dex_path(pkgname.c_str(), dex_path.c_str(), volume_uuid_cstr,
1972 uid, storage_flag)) {
1973 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
1974 _exit(kReconcileSecondaryDexValidationError);
1975 }
1976
1977 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1978 switch (access_check) {
1979 case kSecondaryDexAccessDoesNotExist:
1980 // File does not exist. Proceed with cleaning.
1981 break;
1982 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1983 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1984 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1985 default:
1986 LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
1987 _exit(kReconcileSecondaryDexValidationError);
1988 }
1989
1990 // The secondary dex does not exist anymore or it's. Clear any generated files.
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001991 char oat_path[PKG_PATH_MAX];
1992 char oat_dir[PKG_PATH_MAX];
1993 char oat_isa_dir[PKG_PATH_MAX];
1994 bool result = true;
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07001995 for (size_t i = 0; i < isas.size(); i++) {
Calin Juravle46e27bc2017-09-04 15:57:10 -07001996 if (!create_secondary_dex_oat_layout(
1997 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path)) {
1998 LOG(ERROR) << "Could not create secondary odex layout: " << dex_path;
1999 _exit(kReconcileSecondaryDexValidationError);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002000 }
Calin Juravle51314092017-05-18 15:33:05 -07002001
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002002 // Delete oat/vdex/art files.
2003 result = unlink_if_exists(oat_path) && result;
2004 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
2005 result = unlink_if_exists(create_image_filename(oat_path)) && result;
Calin Juravlec9eab382017-01-25 01:17:17 -08002006
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002007 // Delete profiles.
2008 std::string current_profile = create_current_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002009 multiuser_get_user_id(uid), dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002010 std::string reference_profile = create_reference_profile_path(
Calin Juravle51314092017-05-18 15:33:05 -07002011 dex_path, /*is_secondary*/true);
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002012 result = unlink_if_exists(current_profile) && result;
2013 result = unlink_if_exists(reference_profile) && result;
Calin Juravle51314092017-05-18 15:33:05 -07002014
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002015 // We upgraded once the location of current profile for secondary dex files.
2016 // Check for any previous left-overs and remove them as well.
2017 std::string old_current_profile = dex_path + ".prof";
2018 result = unlink_if_exists(old_current_profile);
Calin Juravle3760ad32017-07-27 16:31:55 -07002019
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002020 // Try removing the directories as well, they might be empty.
2021 result = rmdir_if_empty(oat_isa_dir) && result;
2022 result = rmdir_if_empty(oat_dir) && result;
2023 }
Calin Juravle46e27bc2017-09-04 15:57:10 -07002024 if (!result) {
2025 PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
2026 }
2027 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
Calin Juravlec9eab382017-01-25 01:17:17 -08002028 }
2029
Shubham Ajmerae6d7ad52017-08-25 13:07:44 -07002030 int return_code = wait_child(pid);
Calin Juravle46e27bc2017-09-04 15:57:10 -07002031 if (!WIFEXITED(return_code)) {
2032 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2033 } else {
2034 return_code = WEXITSTATUS(return_code);
2035 }
2036
2037 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2038
2039 switch (return_code) {
2040 case kReconcileSecondaryDexCleanedUp:
2041 case kReconcileSecondaryDexValidationError:
2042 // If we couldn't validate assume the dex file does not exist.
2043 // This will purge the entry from the PM records.
2044 *out_secondary_dex_exists = false;
2045 return true;
2046 case kReconcileSecondaryDexExists:
2047 *out_secondary_dex_exists = true;
2048 return true;
2049 case kReconcileSecondaryDexAccessIOError:
2050 // We had an access IO error.
2051 // Return false so that we can try again.
2052 // The value of out_secondary_dex_exists does not matter in this case and by convention
2053 // is set to false.
2054 *out_secondary_dex_exists = false;
2055 return false;
2056 default:
2057 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2058 *out_secondary_dex_exists = false;
2059 return false;
2060 }
Calin Juravlec9eab382017-01-25 01:17:17 -08002061}
2062
Alan Stokes753dc712017-10-16 10:56:00 +01002063// Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2064// Returns true if all parameters are valid and the hash successfully computed and stored in
2065// out_secondary_dex_hash.
2066// Also returns true with an empty hash if the file does not currently exist or is not accessible to
2067// the app.
2068// For any other errors (e.g. if any of the parameters are invalid) returns false.
2069bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2070 const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
2071 std::vector<uint8_t>* out_secondary_dex_hash) {
2072 out_secondary_dex_hash->clear();
2073
2074 const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
2075
2076 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2077 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2078 << storage_flag;
2079 return false;
2080 }
2081
2082 // Pipe to get the hash result back from our child process.
2083 unique_fd pipe_read, pipe_write;
2084 if (!Pipe(&pipe_read, &pipe_write)) {
2085 PLOG(ERROR) << "Failed to create pipe";
2086 return false;
2087 }
2088
2089 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2090 // access data the app itself can access.
2091 pid_t pid = fork();
2092 if (pid == 0) {
2093 // child -- drop privileges before continuing
2094 drop_capabilities(uid);
2095 pipe_read.reset();
2096
2097 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2098 LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
2099 _exit(1);
2100 }
2101
2102 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2103 if (fd == -1) {
2104 if (errno == EACCES || errno == ENOENT) {
2105 // Not treated as an error.
2106 _exit(0);
2107 }
2108 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
2109 _exit(1);
2110 }
2111
2112 SHA256_CTX ctx;
2113 SHA256_Init(&ctx);
2114
2115 std::vector<uint8_t> buffer(65536);
2116 while (true) {
2117 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2118 if (bytes_read == 0) {
2119 break;
2120 } else if (bytes_read == -1) {
2121 PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
2122 _exit(1);
2123 }
2124
2125 SHA256_Update(&ctx, buffer.data(), bytes_read);
2126 }
2127
2128 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2129 SHA256_Final(hash.data(), &ctx);
2130 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
2131 _exit(1);
2132 }
2133
2134 _exit(0);
2135 }
2136
2137 // parent
2138 pipe_write.reset();
2139
2140 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2141 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2142 out_secondary_dex_hash->clear();
2143 }
2144 return wait_child(pid) == 0;
2145}
2146
Jeff Sharkey90aff262016-12-12 14:28:24 -07002147// Helper for move_ab, so that we can have common failure-case cleanup.
2148static bool unlink_and_rename(const char* from, const char* to) {
2149 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2150 // return a failure.
2151 struct stat s;
2152 if (stat(to, &s) == 0) {
2153 if (!S_ISREG(s.st_mode)) {
2154 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2155 return false;
2156 }
2157 if (unlink(to) != 0) {
2158 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2159 return false;
2160 }
2161 } else {
2162 // This may be a permission problem. We could investigate the error code, but we'll just
2163 // let the rename failure do the work for us.
2164 }
2165
2166 // Try to rename "to" to "from."
2167 if (rename(from, to) != 0) {
2168 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2169 return false;
2170 }
2171 return true;
2172}
2173
2174// Move/rename a B artifact (from) to an A artifact (to).
2175static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2176 // Check whether B exists.
2177 {
2178 struct stat s;
2179 if (stat(b_path.c_str(), &s) != 0) {
2180 // Silently ignore for now. The service calling this isn't smart enough to understand
2181 // lack of artifacts at the moment.
2182 return false;
2183 }
2184 if (!S_ISREG(s.st_mode)) {
2185 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2186 // Try to unlink, but swallow errors.
2187 unlink(b_path.c_str());
2188 return false;
2189 }
2190 }
2191
2192 // Rename B to A.
2193 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2194 // Delete the b_path so we don't try again (or fail earlier).
2195 if (unlink(b_path.c_str()) != 0) {
2196 PLOG(ERROR) << "Could not unlink " << b_path;
2197 }
2198
2199 return false;
2200 }
2201
2202 return true;
2203}
2204
2205bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2206 // Get the current slot suffix. No suffix, no A/B.
2207 std::string slot_suffix;
2208 {
2209 char buf[kPropertyValueMax];
2210 if (get_property("ro.boot.slot_suffix", buf, nullptr) <= 0) {
2211 return false;
2212 }
2213 slot_suffix = buf;
2214
2215 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2216 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2217 return false;
2218 }
2219 }
2220
2221 // Validate other inputs.
2222 if (validate_apk_path(apk_path) != 0) {
2223 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2224 return false;
2225 }
2226 if (validate_apk_path(oat_dir) != 0) {
2227 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2228 return false;
2229 }
2230
2231 char a_path[PKG_PATH_MAX];
2232 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2233 return false;
2234 }
2235 const std::string a_vdex_path = create_vdex_filename(a_path);
2236 const std::string a_image_path = create_image_filename(a_path);
2237
2238 // B path = A path + slot suffix.
2239 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2240 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2241 const std::string b_image_path = StringPrintf("%s.%s",
2242 a_image_path.c_str(),
2243 slot_suffix.c_str());
2244
2245 bool success = true;
2246 if (move_ab_path(b_path, a_path)) {
2247 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2248 // Note: we can live without an app image. As such, ignore failure to move the image file.
2249 // If we decide to require the app image, or the app image being moved correctly,
2250 // then change accordingly.
2251 constexpr bool kIgnoreAppImageFailure = true;
2252
2253 if (!a_image_path.empty()) {
2254 if (!move_ab_path(b_image_path, a_image_path)) {
2255 unlink(a_image_path.c_str());
2256 if (!kIgnoreAppImageFailure) {
2257 success = false;
2258 }
2259 }
2260 }
2261 } else {
2262 // Cleanup: delete B image, ignore errors.
2263 unlink(b_image_path.c_str());
2264 success = false;
2265 }
2266 } else {
2267 // Cleanup: delete B image, ignore errors.
2268 unlink(b_vdex_path.c_str());
2269 unlink(b_image_path.c_str());
2270 success = false;
2271 }
2272 return success;
2273}
2274
2275bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2276 // Delete the oat/odex file.
2277 char out_path[PKG_PATH_MAX];
Calin Juravle80a21252017-01-17 14:43:25 -08002278 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
Calin Juravle114f0812017-03-08 19:05:07 -08002279 /*is_secondary_dex*/false, out_path)) {
Jeff Sharkey90aff262016-12-12 14:28:24 -07002280 return false;
2281 }
2282
2283 // In case of a permission failure report the issue. Otherwise just print a warning.
2284 auto unlink_and_check = [](const char* path) -> bool {
2285 int result = unlink(path);
2286 if (result != 0) {
2287 if (errno == EACCES || errno == EPERM) {
2288 PLOG(ERROR) << "Could not unlink " << path;
2289 return false;
2290 }
2291 PLOG(WARNING) << "Could not unlink " << path;
2292 }
2293 return true;
2294 };
2295
2296 // Delete the oat/odex file.
2297 bool return_value_oat = unlink_and_check(out_path);
2298
2299 // Derive and delete the app image.
2300 bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2301
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002302 // Derive and delete the vdex file.
2303 bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2304
Jeff Sharkey90aff262016-12-12 14:28:24 -07002305 // Report success.
Nicolas Geoffray192fb962017-05-25 13:58:06 +01002306 return return_value_oat && return_value_art && return_value_vdex;
Jeff Sharkey90aff262016-12-12 14:28:24 -07002307}
2308
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06002309static bool is_absolute_path(const std::string& path) {
2310 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2311 LOG(ERROR) << "Invalid absolute path " << path;
2312 return false;
2313 } else {
2314 return true;
2315 }
2316}
2317
2318static bool is_valid_instruction_set(const std::string& instruction_set) {
2319 // TODO: add explicit whitelisting of instruction sets
2320 if (instruction_set.find('/') != std::string::npos) {
2321 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2322 return false;
2323 } else {
2324 return true;
2325 }
2326}
2327
2328bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2329 const char *apk_path, const char *instruction_set) {
2330 std::string oat_dir_ = oat_dir;
2331 std::string apk_path_ = apk_path;
2332 std::string instruction_set_ = instruction_set;
2333
2334 if (!is_absolute_path(oat_dir_)) return false;
2335 if (!is_absolute_path(apk_path_)) return false;
2336 if (!is_valid_instruction_set(instruction_set_)) return false;
2337
2338 std::string::size_type end = apk_path_.rfind('.');
2339 std::string::size_type start = apk_path_.rfind('/', end);
2340 if (end == std::string::npos || start == std::string::npos) {
2341 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2342 return false;
2343 }
2344
2345 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2346 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2347 const char* res = res_.c_str();
2348 if (strlen(res) >= PKG_PATH_MAX) {
2349 LOG(ERROR) << "Result too large";
2350 return false;
2351 } else {
2352 strlcpy(path, res, PKG_PATH_MAX);
2353 return true;
2354 }
2355}
2356
2357bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2358 const char *instruction_set) {
2359 std::string apk_path_ = apk_path;
2360 std::string instruction_set_ = instruction_set;
2361
2362 if (!is_absolute_path(apk_path_)) return false;
2363 if (!is_valid_instruction_set(instruction_set_)) return false;
2364
2365 std::string::size_type end = apk_path_.rfind('.');
2366 std::string::size_type start = apk_path_.rfind('/', end);
2367 if (end == std::string::npos || start == std::string::npos) {
2368 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2369 return false;
2370 }
2371
2372 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2373 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2374}
2375
2376bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2377 const char *instruction_set) {
2378 std::string src_ = src;
2379 std::string instruction_set_ = instruction_set;
2380
2381 if (!is_absolute_path(src_)) return false;
2382 if (!is_valid_instruction_set(instruction_set_)) return false;
2383
2384 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2385 if (*it == '/') {
2386 *it = '@';
2387 }
2388 }
2389
2390 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2391 + DALVIK_CACHE_POSTFIX;
2392 const char* res = res_.c_str();
2393 if (strlen(res) >= PKG_PATH_MAX) {
2394 LOG(ERROR) << "Result too large";
2395 return false;
2396 } else {
2397 strlcpy(path, res, PKG_PATH_MAX);
2398 return true;
2399 }
2400}
2401
Calin Juravle29591732017-11-20 17:46:19 -08002402bool snapshot_profile(int32_t app_id, const std::string& package_name,
2403 const std::string& code_path) {
2404 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2405
2406 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, code_path);
2407 if (snapshot_fd < 0) {
2408 return false;
2409 }
2410
2411 std::vector<unique_fd> profiles_fd;
2412 unique_fd reference_profile_fd;
2413 open_profile_files(app_shared_gid, package_name, /*is_secondary_dex*/ false, &profiles_fd,
2414 &reference_profile_fd);
2415 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2416 return false;
2417 }
2418
2419 profiles_fd.push_back(std::move(reference_profile_fd));
2420
2421 pid_t pid = fork();
2422 if (pid == 0) {
2423 /* child -- drop privileges before continuing */
2424 drop_capabilities(app_shared_gid);
2425 run_profman_merge(profiles_fd, snapshot_fd);
2426 exit(42); /* only get here on exec failure */
2427 }
2428
2429 /* parent */
2430 int return_code = wait_child(pid);
2431 if (!WIFEXITED(return_code)) {
2432 LOG(WARNING) << "profman failed for " << package_name << ":" << code_path;
2433 return false;
2434 }
2435
2436 return true;
2437}
2438
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002439} // namespace installd
2440} // namespace android