1 /*
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 */
16 #define LOG_TAG "installd"
17
18 #include <array>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/capability.h>
23 #include <sys/file.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <sys/resource.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30
31 #include <iomanip>
32
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
35 #include <android-base/properties.h>
36 #include <android-base/stringprintf.h>
37 #include <android-base/strings.h>
38 #include <android-base/unique_fd.h>
39 #include <async_safe/log.h>
40 #include <cutils/fs.h>
41 #include <cutils/properties.h>
42 #include <cutils/sched_policy.h>
43 #include <log/log.h> // TODO: Move everything to base/logging.
44 #include <openssl/sha.h>
45 #include <private/android_filesystem_config.h>
46 #include <processgroup/processgroup.h>
47 #include <selinux/android.h>
48 #include <server_configurable_flags/get_flags.h>
49 #include <system/thread_defs.h>
50
51 #include "dexopt.h"
52 #include "dexopt_return_codes.h"
53 #include "execv_helper.h"
54 #include "globals.h"
55 #include "installd_deps.h"
56 #include "installd_constants.h"
57 #include "otapreopt_utils.h"
58 #include "run_dex2oat.h"
59 #include "unique_file.h"
60 #include "utils.h"
61
62 using android::base::Basename;
63 using android::base::EndsWith;
64 using android::base::GetBoolProperty;
65 using android::base::GetProperty;
66 using android::base::ReadFdToString;
67 using android::base::ReadFully;
68 using android::base::StringPrintf;
69 using android::base::WriteFully;
70 using android::base::unique_fd;
71
72 namespace android {
73 namespace installd {
74
75
76 // Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
77 struct FreeDelete {
78 // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
operator ()android::installd::FreeDelete79 void operator()(const void* ptr) const {
80 free(const_cast<void*>(ptr));
81 }
82 };
83
84 // Alias for std::unique_ptr<> that uses the C function free() to delete objects.
85 template <typename T>
86 using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
87
invalid_unique_fd()88 static unique_fd invalid_unique_fd() {
89 return unique_fd(-1);
90 }
91
is_debug_runtime()92 static bool is_debug_runtime() {
93 return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
94 }
95
is_debuggable_build()96 static bool is_debuggable_build() {
97 return android::base::GetBoolProperty("ro.debuggable", false);
98 }
99
clear_profile(const std::string & profile)100 static bool clear_profile(const std::string& profile) {
101 unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
102 if (ufd.get() < 0) {
103 if (errno != ENOENT) {
104 PLOG(WARNING) << "Could not open profile " << profile;
105 return false;
106 } else {
107 // Nothing to clear. That's ok.
108 return true;
109 }
110 }
111
112 if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
113 if (errno != EWOULDBLOCK) {
114 PLOG(WARNING) << "Error locking profile " << profile;
115 }
116 // This implies that the app owning this profile is running
117 // (and has acquired the lock).
118 //
119 // If we can't acquire the lock bail out since clearing is useless anyway
120 // (the app will write again to the profile).
121 //
122 // Note:
123 // This does not impact the this is not an issue for the profiling correctness.
124 // In case this is needed because of an app upgrade, profiles will still be
125 // eventually cleared by the app itself due to checksum mismatch.
126 // If this is needed because profman advised, then keeping the data around
127 // until the next run is again not an issue.
128 //
129 // If the app attempts to acquire a lock while we've held one here,
130 // it will simply skip the current write cycle.
131 return false;
132 }
133
134 bool truncated = ftruncate(ufd.get(), 0) == 0;
135 if (!truncated) {
136 PLOG(WARNING) << "Could not truncate " << profile;
137 }
138 if (flock(ufd.get(), LOCK_UN) != 0) {
139 PLOG(WARNING) << "Error unlocking profile " << profile;
140 }
141 return truncated;
142 }
143
144 // Clear the reference profile for the given location.
145 // The location is the profile name for primary apks or the dex path for secondary dex files.
clear_reference_profile(const std::string & package_name,const std::string & location,bool is_secondary_dex)146 static bool clear_reference_profile(const std::string& package_name, const std::string& location,
147 bool is_secondary_dex) {
148 return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
149 }
150
151 // Clear the reference profile for the given location.
152 // The location is the profile name for primary apks or the dex path for secondary dex files.
clear_current_profile(const std::string & package_name,const std::string & location,userid_t user,bool is_secondary_dex)153 static bool clear_current_profile(const std::string& package_name, const std::string& location,
154 userid_t user, bool is_secondary_dex) {
155 return clear_profile(create_current_profile_path(user, package_name, location,
156 is_secondary_dex));
157 }
158
159 // Clear the reference profile for the primary apk of the given package.
160 // The location is the profile name for primary apks or the dex path for secondary dex files.
clear_primary_reference_profile(const std::string & package_name,const std::string & location)161 bool clear_primary_reference_profile(const std::string& package_name,
162 const std::string& location) {
163 return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
164 }
165
166 // Clear all current profile for the primary apk of the given package.
167 // The location is the profile name for primary apks or the dex path for secondary dex files.
clear_primary_current_profiles(const std::string & package_name,const std::string & location)168 bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
169 bool success = true;
170 // For secondary dex files, we don't really need the user but we use it for sanity checks.
171 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
172 for (auto user : users) {
173 success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
174 }
175 return success;
176 }
177
178 // Clear the current profile for the primary apk of the given package and user.
clear_primary_current_profile(const std::string & package_name,const std::string & location,userid_t user)179 bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
180 userid_t user) {
181 return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
182 }
183
184 // Determines which binary we should use for execution (the debug or non-debug version).
185 // e.g. dex2oatd vs dex2oat
select_execution_binary(const char * binary,const char * debug_binary,bool background_job_compile)186 static const char* select_execution_binary(const char* binary, const char* debug_binary,
187 bool background_job_compile) {
188 return select_execution_binary(
189 binary,
190 debug_binary,
191 background_job_compile,
192 is_debug_runtime(),
193 (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
194 is_debuggable_build());
195 }
196
197 // Determines which binary we should use for execution (the debug or non-debug version).
198 // e.g. dex2oatd vs dex2oat
199 // This is convenient method which is much easier to test because it doesn't read
200 // system properties.
select_execution_binary(const char * binary,const char * debug_binary,bool background_job_compile,bool is_debug_runtime,bool is_release,bool is_debuggable_build)201 const char* select_execution_binary(
202 const char* binary,
203 const char* debug_binary,
204 bool background_job_compile,
205 bool is_debug_runtime,
206 bool is_release,
207 bool is_debuggable_build) {
208 // Do not use debug binaries for release candidates (to give more soak time).
209 bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
210
211 // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
212 // the file is present (it may not be on images with very little space available).
213 bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
214
215 return useDebug ? debug_binary : binary;
216 }
217
218 // Namespace for Android Runtime flags applied during boot time.
219 static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
220 // Feature flag name for running the JIT in Zygote experiment, b/119800099.
221 static const char* ENABLE_JITZYGOTE_IMAGE = "enable_apex_image";
222
223 // Phenotype property name for enabling profiling the boot class path.
224 static const char* PROFILE_BOOT_CLASS_PATH = "profilebootclasspath";
225
IsBootClassPathProfilingEnable()226 static bool IsBootClassPathProfilingEnable() {
227 std::string profile_boot_class_path = GetProperty("dalvik.vm.profilebootclasspath", "");
228 profile_boot_class_path =
229 server_configurable_flags::GetServerConfigurableFlag(
230 RUNTIME_NATIVE_BOOT_NAMESPACE,
231 PROFILE_BOOT_CLASS_PATH,
232 /*default_value=*/ profile_boot_class_path);
233 return profile_boot_class_path == "true";
234 }
235
UnlinkIgnoreResult(const std::string & path)236 static void UnlinkIgnoreResult(const std::string& path) {
237 if (unlink(path.c_str()) < 0) {
238 PLOG(ERROR) << "Failed to unlink " << path;
239 }
240 }
241
242 /*
243 * Whether dexopt should use a swap file when compiling an APK.
244 *
245 * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
246 * itself, anyways).
247 *
248 * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
249 *
250 * Otherwise, return true if this is a low-mem device.
251 *
252 * Otherwise, return default value.
253 */
254 static bool kAlwaysProvideSwapFile = false;
255 static bool kDefaultProvideSwapFile = true;
256
ShouldUseSwapFileForDexopt()257 static bool ShouldUseSwapFileForDexopt() {
258 if (kAlwaysProvideSwapFile) {
259 return true;
260 }
261
262 // Check the "override" property. If it exists, return value == "true".
263 std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
264 if (!dex2oat_prop_buf.empty()) {
265 return dex2oat_prop_buf == "true";
266 }
267
268 // Shortcut for default value. This is an implementation optimization for the process sketched
269 // above. If the default value is true, we can avoid to check whether this is a low-mem device,
270 // as low-mem is never returning false. The compiler will optimize this away if it can.
271 if (kDefaultProvideSwapFile) {
272 return true;
273 }
274
275 if (GetBoolProperty("ro.config.low_ram", false)) {
276 return true;
277 }
278
279 // Default value must be false here.
280 return kDefaultProvideSwapFile;
281 }
282
SetDex2OatScheduling(bool set_to_bg)283 static void SetDex2OatScheduling(bool set_to_bg) {
284 if (set_to_bg) {
285 if (!SetTaskProfiles(0, {"Dex2OatBootComplete"})) {
286 LOG(ERROR) << "Failed to set dex2oat task profile";
287 exit(DexoptReturnCodes::kSetSchedPolicy);
288 }
289 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
290 PLOG(ERROR) << "setpriority failed";
291 exit(DexoptReturnCodes::kSetPriority);
292 }
293 }
294 }
295
create_profile(uid_t uid,const std::string & profile,int32_t flags,mode_t mode)296 static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
297 unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, mode)));
298 if (fd.get() < 0) {
299 if (errno != EEXIST) {
300 PLOG(ERROR) << "Failed to create profile " << profile;
301 return invalid_unique_fd();
302 }
303 }
304 // Profiles should belong to the app; make sure of that by giving ownership to
305 // the app uid. If we cannot do that, there's no point in returning the fd
306 // since dex2oat/profman will fail with SElinux denials.
307 if (fchown(fd.get(), uid, uid) < 0) {
308 PLOG(ERROR) << "Could not chown profile " << profile;
309 return invalid_unique_fd();
310 }
311 return fd;
312 }
313
open_profile(uid_t uid,const std::string & profile,int32_t flags,mode_t mode)314 static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags, mode_t mode) {
315 // Do not follow symlinks when opening a profile:
316 // - primary profiles should not contain symlinks in their paths
317 // - secondary dex paths should have been already resolved and validated
318 flags |= O_NOFOLLOW;
319
320 // Check if we need to create the profile
321 // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
322 unique_fd fd;
323 if ((flags & O_CREAT) != 0) {
324 fd = create_profile(uid, profile, flags, mode);
325 } else {
326 fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
327 }
328
329 if (fd.get() < 0) {
330 if (errno != ENOENT) {
331 // Profiles might be missing for various reasons. For example, in a
332 // multi-user environment, the profile directory for one user can be created
333 // after we start a merge. In this case the current profile for that user
334 // will not be found.
335 // Also, the secondary dex profiles might be deleted by the app at any time,
336 // so we can't we need to prepare if they are missing.
337 PLOG(ERROR) << "Failed to open profile " << profile;
338 }
339 return invalid_unique_fd();
340 } else {
341 // If we just create the file we need to set its mode because on Android
342 // open has a mask that only allows owner access.
343 if ((flags & O_CREAT) != 0) {
344 if (fchmod(fd.get(), mode) != 0) {
345 PLOG(ERROR) << "Could not set mode " << std::hex << mode << std::dec
346 << " on profile" << profile;
347 // Not a terminal failure.
348 }
349 }
350 }
351
352 return fd;
353 }
354
open_current_profile(uid_t uid,userid_t user,const std::string & package_name,const std::string & location,bool is_secondary_dex)355 static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
356 const std::string& location, bool is_secondary_dex) {
357 std::string profile = create_current_profile_path(user, package_name, location,
358 is_secondary_dex);
359 return open_profile(uid, profile, O_RDONLY, /*mode=*/ 0);
360 }
361
open_reference_profile(uid_t uid,const std::string & package_name,const std::string & location,bool read_write,bool is_secondary_dex)362 static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
363 const std::string& location, bool read_write, bool is_secondary_dex) {
364 std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
365 return open_profile(
366 uid,
367 profile,
368 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
369 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
370 }
371
open_reference_profile_as_unique_file(uid_t uid,const std::string & package_name,const std::string & location,bool read_write,bool is_secondary_dex)372 static UniqueFile open_reference_profile_as_unique_file(uid_t uid, const std::string& package_name,
373 const std::string& location, bool read_write, bool is_secondary_dex) {
374 std::string profile_path = create_reference_profile_path(package_name, location,
375 is_secondary_dex);
376 unique_fd ufd = open_profile(
377 uid,
378 profile_path,
379 read_write ? (O_CREAT | O_RDWR) : O_RDONLY,
380 S_IRUSR | S_IWUSR | S_IRGRP); // so that ART can also read it when apps run.
381
382 return UniqueFile(ufd.release(), profile_path, [](const std::string& path) {
383 clear_profile(path);
384 });
385 }
386
open_spnashot_profile(uid_t uid,const std::string & package_name,const std::string & location)387 static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
388 const std::string& location) {
389 std::string profile = create_snapshot_profile_path(package_name, location);
390 return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
391 }
392
open_profile_files(uid_t uid,const std::string & package_name,const std::string & location,bool is_secondary_dex,std::vector<unique_fd> * profiles_fd,unique_fd * reference_profile_fd)393 static void open_profile_files(uid_t uid, const std::string& package_name,
394 const std::string& location, bool is_secondary_dex,
395 /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
396 // Open the reference profile in read-write mode as profman might need to save the merge.
397 *reference_profile_fd = open_reference_profile(uid, package_name, location,
398 /*read_write*/ true, is_secondary_dex);
399
400 // For secondary dex files, we don't really need the user but we use it for sanity checks.
401 // Note: the user owning the dex file should be the current user.
402 std::vector<userid_t> users;
403 if (is_secondary_dex){
404 users.push_back(multiuser_get_user_id(uid));
405 } else {
406 users = get_known_users(/*volume_uuid*/ nullptr);
407 }
408 for (auto user : users) {
409 unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
410 is_secondary_dex);
411 // Add to the lists only if both fds are valid.
412 if (profile_fd.get() >= 0) {
413 profiles_fd->push_back(std::move(profile_fd));
414 }
415 }
416 }
417
418 static constexpr int PROFMAN_BIN_RETURN_CODE_SUCCESS = 0;
419 static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 1;
420 static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA = 2;
421 static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 3;
422 static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 4;
423 static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 5;
424 static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS = 6;
425 static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES = 7;
426
427 class RunProfman : public ExecVHelper {
428 public:
SetupArgs(const std::vector<unique_fd> & profile_fds,const unique_fd & reference_profile_fd,const std::vector<unique_fd> & apk_fds,const std::vector<std::string> & dex_locations,bool copy_and_update,bool for_snapshot,bool for_boot_image)429 void SetupArgs(const std::vector<unique_fd>& profile_fds,
430 const unique_fd& reference_profile_fd,
431 const std::vector<unique_fd>& apk_fds,
432 const std::vector<std::string>& dex_locations,
433 bool copy_and_update,
434 bool for_snapshot,
435 bool for_boot_image) {
436
437 // TODO(calin): Assume for now we run in the bg compile job (which is in
438 // most of the invocation). With the current data flow, is not very easy or
439 // clean to discover this in RunProfman (it will require quite a messy refactoring).
440 const char* profman_bin = select_execution_binary(
441 kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
442
443 if (copy_and_update) {
444 CHECK_EQ(1u, profile_fds.size());
445 CHECK_EQ(1u, apk_fds.size());
446 }
447 if (reference_profile_fd != -1) {
448 AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
449 }
450
451 for (const unique_fd& fd : profile_fds) {
452 AddArg("--profile-file-fd=" + std::to_string(fd.get()));
453 }
454
455 for (const unique_fd& fd : apk_fds) {
456 AddArg("--apk-fd=" + std::to_string(fd.get()));
457 }
458
459 for (const std::string& dex_location : dex_locations) {
460 AddArg("--dex-location=" + dex_location);
461 }
462
463 if (copy_and_update) {
464 AddArg("--copy-and-update-profile-key");
465 }
466
467 if (for_snapshot) {
468 AddArg("--force-merge");
469 }
470
471 if (for_boot_image) {
472 AddArg("--boot-image-merge");
473 }
474
475 // The percent won't exceed 100, otherwise, don't set it and use the
476 // default one set in profman.
477 uint32_t min_new_classes_percent_change = ::android::base::GetUintProperty<uint32_t>(
478 "dalvik.vm.bgdexopt.new-classes-percent",
479 /*default*/std::numeric_limits<uint32_t>::max());
480 if (min_new_classes_percent_change <= 100) {
481 AddArg("--min-new-classes-percent-change=" +
482 std::to_string(min_new_classes_percent_change));
483 }
484
485 // The percent won't exceed 100, otherwise, don't set it and use the
486 // default one set in profman.
487 uint32_t min_new_methods_percent_change = ::android::base::GetUintProperty<uint32_t>(
488 "dalvik.vm.bgdexopt.new-methods-percent",
489 /*default*/std::numeric_limits<uint32_t>::max());
490 if (min_new_methods_percent_change <= 100) {
491 AddArg("--min-new-methods-percent-change=" +
492 std::to_string(min_new_methods_percent_change));
493 }
494
495 // Do not add after dex2oat_flags, they should override others for debugging.
496 PrepareArgs(profman_bin);
497 }
498
SetupMerge(const std::vector<unique_fd> & profiles_fd,const unique_fd & reference_profile_fd,const std::vector<unique_fd> & apk_fds=std::vector<unique_fd> (),const std::vector<std::string> & dex_locations=std::vector<std::string> (),bool for_snapshot=false,bool for_boot_image=false)499 void SetupMerge(const std::vector<unique_fd>& profiles_fd,
500 const unique_fd& reference_profile_fd,
501 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
502 const std::vector<std::string>& dex_locations = std::vector<std::string>(),
503 bool for_snapshot = false,
504 bool for_boot_image = false) {
505 SetupArgs(profiles_fd,
506 reference_profile_fd,
507 apk_fds,
508 dex_locations,
509 /*copy_and_update=*/ false,
510 for_snapshot,
511 for_boot_image);
512 }
513
SetupCopyAndUpdate(unique_fd && profile_fd,unique_fd && reference_profile_fd,unique_fd && apk_fd,const std::string & dex_location)514 void SetupCopyAndUpdate(unique_fd&& profile_fd,
515 unique_fd&& reference_profile_fd,
516 unique_fd&& apk_fd,
517 const std::string& dex_location) {
518 // The fds need to stay open longer than the scope of the function, so put them into a local
519 // variable vector.
520 profiles_fd_.push_back(std::move(profile_fd));
521 apk_fds_.push_back(std::move(apk_fd));
522 reference_profile_fd_ = std::move(reference_profile_fd);
523 std::vector<std::string> dex_locations = {dex_location};
524 SetupArgs(profiles_fd_,
525 reference_profile_fd_,
526 apk_fds_,
527 dex_locations,
528 /*copy_and_update=*/true,
529 /*for_snapshot*/false,
530 /*for_boot_image*/false);
531 }
532
SetupDump(const std::vector<unique_fd> & profiles_fd,const unique_fd & reference_profile_fd,const std::vector<std::string> & dex_locations,const std::vector<unique_fd> & apk_fds,const unique_fd & output_fd)533 void SetupDump(const std::vector<unique_fd>& profiles_fd,
534 const unique_fd& reference_profile_fd,
535 const std::vector<std::string>& dex_locations,
536 const std::vector<unique_fd>& apk_fds,
537 const unique_fd& output_fd) {
538 AddArg("--dump-only");
539 AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
540 SetupArgs(profiles_fd,
541 reference_profile_fd,
542 apk_fds,
543 dex_locations,
544 /*copy_and_update=*/false,
545 /*for_snapshot*/false,
546 /*for_boot_image*/false);
547 }
548
549 using ExecVHelper::Exec; // To suppress -Wno-overloaded-virtual
Exec()550 void Exec() {
551 ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
552 }
553
554 private:
555 unique_fd reference_profile_fd_;
556 std::vector<unique_fd> profiles_fd_;
557 std::vector<unique_fd> apk_fds_;
558 };
559
analyze_profiles(uid_t uid,const std::string & package_name,const std::string & location,bool is_secondary_dex)560 static int analyze_profiles(uid_t uid, const std::string& package_name,
561 const std::string& location, bool is_secondary_dex) {
562 std::vector<unique_fd> profiles_fd;
563 unique_fd reference_profile_fd;
564 open_profile_files(uid, package_name, location, is_secondary_dex,
565 &profiles_fd, &reference_profile_fd);
566 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
567 // Skip profile guided compilation because no profiles were found.
568 // Or if the reference profile info couldn't be opened.
569 return PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
570 }
571
572 RunProfman profman_merge;
573 const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>();
574 const std::vector<std::string>& dex_locations = std::vector<std::string>();
575 profman_merge.SetupMerge(
576 profiles_fd,
577 reference_profile_fd,
578 apk_fds,
579 dex_locations,
580 /* for_snapshot= */ false,
581 IsBootClassPathProfilingEnable());
582 pid_t pid = fork();
583 if (pid == 0) {
584 /* child -- drop privileges before continuing */
585 drop_capabilities(uid);
586 profman_merge.Exec();
587 }
588 /* parent */
589 int return_code = wait_child(pid);
590 bool need_to_compile = false;
591 bool empty_profiles = false;
592 bool should_clear_current_profiles = false;
593 bool should_clear_reference_profile = false;
594 if (!WIFEXITED(return_code)) {
595 LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
596 } else {
597 return_code = WEXITSTATUS(return_code);
598 switch (return_code) {
599 case PROFMAN_BIN_RETURN_CODE_COMPILE:
600 need_to_compile = true;
601 should_clear_current_profiles = true;
602 should_clear_reference_profile = false;
603 break;
604 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_NOT_ENOUGH_DELTA:
605 need_to_compile = false;
606 should_clear_current_profiles = false;
607 should_clear_reference_profile = false;
608 break;
609 case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION_EMPTY_PROFILES:
610 need_to_compile = false;
611 empty_profiles = true;
612 should_clear_current_profiles = false;
613 should_clear_reference_profile = false;
614 break;
615 case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
616 LOG(WARNING) << "Bad profiles for location " << location;
617 need_to_compile = false;
618 should_clear_current_profiles = true;
619 should_clear_reference_profile = true;
620 break;
621 case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
622 case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
623 // Temporary IO problem (e.g. locking). Ignore but log a warning.
624 LOG(WARNING) << "IO error while reading profiles for location " << location;
625 need_to_compile = false;
626 should_clear_current_profiles = false;
627 should_clear_reference_profile = false;
628 break;
629 case PROFMAN_BIN_RETURN_CODE_ERROR_DIFFERENT_VERSIONS:
630 need_to_compile = false;
631 should_clear_current_profiles = true;
632 should_clear_reference_profile = true;
633 break;
634 default:
635 // Unknown return code or error. Unlink profiles.
636 LOG(WARNING) << "Unexpected error code while processing profiles for location "
637 << location << ": " << return_code;
638 need_to_compile = false;
639 should_clear_current_profiles = true;
640 should_clear_reference_profile = true;
641 break;
642 }
643 }
644
645 if (should_clear_current_profiles) {
646 if (is_secondary_dex) {
647 // For secondary dex files, the owning user is the current user.
648 clear_current_profile(package_name, location, multiuser_get_user_id(uid),
649 is_secondary_dex);
650 } else {
651 clear_primary_current_profiles(package_name, location);
652 }
653 }
654 if (should_clear_reference_profile) {
655 clear_reference_profile(package_name, location, is_secondary_dex);
656 }
657 int result = 0;
658 if (need_to_compile) {
659 result = PROFILES_ANALYSIS_OPTIMIZE;
660 } else if (empty_profiles) {
661 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES;
662 } else {
663 result = PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA;
664 }
665 return result;
666 }
667
668 // Decides if profile guided compilation is needed or not based on existing profiles.
669 // The analysis is done for a single profile name (which corresponds to a single code path).
670 //
671 // Returns PROFILES_ANALYSIS_OPTIMIZE if there is enough information in the current profiles
672 // that makes it worth to recompile the package.
673 // If the return value is PROFILES_ANALYSIS_OPTIMIZE all the current profiles would have been
674 // merged into the reference profiles accessible with open_reference_profile().
675 //
676 // Return PROFILES_ANALYSIS_DONT_OPTIMIZE_SMALL_DELTA if the package should not optimize.
677 // As a special case returns PROFILES_ANALYSIS_DONT_OPTIMIZE_EMPTY_PROFILES if all profiles are
678 // empty.
analyze_primary_profiles(uid_t uid,const std::string & package_name,const std::string & profile_name)679 int analyze_primary_profiles(uid_t uid, const std::string& package_name,
680 const std::string& profile_name) {
681 return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
682 }
683
dump_profiles(int32_t uid,const std::string & pkgname,const std::string & profile_name,const std::string & code_path)684 bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
685 const std::string& code_path) {
686 std::vector<unique_fd> profile_fds;
687 unique_fd reference_profile_fd;
688 std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
689 pkgname.c_str(), profile_name.c_str());
690
691 open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
692 &profile_fds, &reference_profile_fd);
693
694 const bool has_reference_profile = (reference_profile_fd.get() != -1);
695 const bool has_profiles = !profile_fds.empty();
696
697 if (!has_reference_profile && !has_profiles) {
698 LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
699 return false;
700 }
701
702 unique_fd output_fd(open(out_file_name.c_str(),
703 O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
704 if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
705 LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
706 return false;
707 }
708
709 std::vector<std::string> dex_locations;
710 std::vector<unique_fd> apk_fds;
711 unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
712 if (apk_fd == -1) {
713 PLOG(ERROR) << "installd cannot open " << code_path.c_str();
714 return false;
715 }
716 dex_locations.push_back(Basename(code_path));
717 apk_fds.push_back(std::move(apk_fd));
718
719
720 RunProfman profman_dump;
721 profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
722 pid_t pid = fork();
723 if (pid == 0) {
724 /* child -- drop privileges before continuing */
725 drop_capabilities(uid);
726 profman_dump.Exec();
727 }
728 /* parent */
729 int return_code = wait_child(pid);
730 if (!WIFEXITED(return_code)) {
731 LOG(WARNING) << "profman failed for package " << pkgname << ": "
732 << return_code;
733 return false;
734 }
735 return true;
736 }
737
copy_system_profile(const std::string & system_profile,uid_t packageUid,const std::string & package_name,const std::string & profile_name)738 bool copy_system_profile(const std::string& system_profile,
739 uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
740 unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
741 unique_fd out_fd(open_reference_profile(packageUid,
742 package_name,
743 profile_name,
744 /*read_write*/ true,
745 /*secondary*/ false));
746 if (in_fd.get() < 0) {
747 PLOG(WARNING) << "Could not open profile " << system_profile;
748 return false;
749 }
750 if (out_fd.get() < 0) {
751 PLOG(WARNING) << "Could not open profile " << package_name;
752 return false;
753 }
754
755 // As a security measure we want to write the profile information with the reduced capabilities
756 // of the package user id. So we fork and drop capabilities in the child.
757 pid_t pid = fork();
758 if (pid == 0) {
759 /* child -- drop privileges before continuing */
760 drop_capabilities(packageUid);
761
762 if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
763 if (errno != EWOULDBLOCK) {
764 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error locking profile %s: %d",
765 package_name.c_str(), errno);
766 }
767 // This implies that the app owning this profile is running
768 // (and has acquired the lock).
769 //
770 // The app never acquires the lock for the reference profiles of primary apks.
771 // Only dex2oat from installd will do that. Since installd is single threaded
772 // we should not see this case. Nevertheless be prepared for it.
773 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Failed to flock %s: %d",
774 package_name.c_str(), errno);
775 return false;
776 }
777
778 bool truncated = ftruncate(out_fd.get(), 0) == 0;
779 if (!truncated) {
780 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Could not truncate %s: %d",
781 package_name.c_str(), errno);
782 }
783
784 // Copy over data.
785 static constexpr size_t kBufferSize = 4 * 1024;
786 char buffer[kBufferSize];
787 while (true) {
788 ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
789 if (bytes == 0) {
790 break;
791 }
792 write(out_fd.get(), buffer, bytes);
793 }
794 if (flock(out_fd.get(), LOCK_UN) != 0) {
795 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Error unlocking profile %s: %d",
796 package_name.c_str(), errno);
797 }
798 // Use _exit since we don't want to run the global destructors in the child.
799 // b/62597429
800 _exit(0);
801 }
802 /* parent */
803 int return_code = wait_child(pid);
804 return return_code == 0;
805 }
806
replace_file_extension(const std::string & oat_path,const std::string & new_ext)807 static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
808 // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
809 if (EndsWith(oat_path, ".dex")) {
810 std::string new_path = oat_path;
811 new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
812 CHECK(EndsWith(new_path, new_ext));
813 return new_path;
814 }
815
816 // An odex entry. Not that this may not be an extension, e.g., in the OTA
817 // case (where the base name will have an extension for the B artifact).
818 size_t odex_pos = oat_path.rfind(".odex");
819 if (odex_pos != std::string::npos) {
820 std::string new_path = oat_path;
821 new_path.replace(odex_pos, strlen(".odex"), new_ext);
822 CHECK_NE(new_path.find(new_ext), std::string::npos);
823 return new_path;
824 }
825
826 // Don't know how to handle this.
827 return "";
828 }
829
830 // Translate the given oat path to an art (app image) path. An empty string
831 // denotes an error.
create_image_filename(const std::string & oat_path)832 static std::string create_image_filename(const std::string& oat_path) {
833 return replace_file_extension(oat_path, ".art");
834 }
835
836 // Translate the given oat path to a vdex path. An empty string denotes an error.
create_vdex_filename(const std::string & oat_path)837 static std::string create_vdex_filename(const std::string& oat_path) {
838 return replace_file_extension(oat_path, ".vdex");
839 }
840
open_output_file(const char * file_name,bool recreate,int permissions)841 static int open_output_file(const char* file_name, bool recreate, int permissions) {
842 int flags = O_RDWR | O_CREAT;
843 if (recreate) {
844 if (unlink(file_name) < 0) {
845 if (errno != ENOENT) {
846 PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
847 }
848 }
849 flags |= O_EXCL;
850 }
851 return open(file_name, flags, permissions);
852 }
853
set_permissions_and_ownership(int fd,bool is_public,int uid,const char * path,bool is_secondary_dex)854 static bool set_permissions_and_ownership(
855 int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
856 // Primary apks are owned by the system. Secondary dex files are owned by the app.
857 int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
858 if (fchmod(fd,
859 S_IRUSR|S_IWUSR|S_IRGRP |
860 (is_public ? S_IROTH : 0)) < 0) {
861 ALOGE("installd cannot chmod '%s' during dexopt\n", path);
862 return false;
863 } else if (fchown(fd, owning_uid, uid) < 0) {
864 ALOGE("installd cannot chown '%s' during dexopt\n", path);
865 return false;
866 }
867 return true;
868 }
869
IsOutputDalvikCache(const char * oat_dir)870 static bool IsOutputDalvikCache(const char* oat_dir) {
871 // InstallerConnection.java (which invokes installd) transforms Java null arguments
872 // into '!'. Play it safe by handling it both.
873 // TODO: ensure we never get null.
874 // TODO: pass a flag instead of inferring if the output is dalvik cache.
875 return oat_dir == nullptr || oat_dir[0] == '!';
876 }
877
878 // Best-effort check whether we can fit the the path into our buffers.
879 // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
880 // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
881 // extension to the cache path (5 bytes).
882 // TODO(calin): move away from char* buffers and PKG_PATH_MAX.
validate_dex_path_size(const std::string & dex_path)883 static bool validate_dex_path_size(const std::string& dex_path) {
884 if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
885 LOG(ERROR) << "dex_path too long: " << dex_path;
886 return false;
887 }
888 return true;
889 }
890
create_oat_out_path(const char * apk_path,const char * instruction_set,const char * oat_dir,bool is_secondary_dex,char * out_oat_path)891 static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
892 const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
893 if (!validate_dex_path_size(apk_path)) {
894 return false;
895 }
896
897 if (!IsOutputDalvikCache(oat_dir)) {
898 // Oat dirs for secondary dex files are already validated.
899 if (!is_secondary_dex && validate_apk_path(oat_dir)) {
900 ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
901 return false;
902 }
903 if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
904 return false;
905 }
906 } else {
907 if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
908 return false;
909 }
910 }
911 return true;
912 }
913
914 // (re)Creates the app image if needed.
maybe_open_app_image(const std::string & out_oat_path,bool generate_app_image,bool is_public,int uid,bool is_secondary_dex)915 UniqueFile maybe_open_app_image(const std::string& out_oat_path,
916 bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
917
918 const std::string image_path = create_image_filename(out_oat_path);
919 if (image_path.empty()) {
920 // Happens when the out_oat_path has an unknown extension.
921 return UniqueFile();
922 }
923
924 // In case there is a stale image, remove it now. Ignore any error.
925 unlink(image_path.c_str());
926
927 // Not enabled, exit.
928 if (!generate_app_image) {
929 return UniqueFile();
930 }
931 std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
932 if (app_image_format.empty()) {
933 return UniqueFile();
934 }
935 // Recreate is true since we do not want to modify a mapped image. If the app is
936 // already running and we modify the image file, it can cause crashes (b/27493510).
937 UniqueFile image_file(
938 open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
939 image_path,
940 UnlinkIgnoreResult);
941 if (image_file.fd() < 0) {
942 // Could not create application image file. Go on since we can compile without it.
943 LOG(ERROR) << "installd could not create '" << image_path
944 << "' for image file during dexopt";
945 // If we have a valid image file path but no image fd, explicitly erase the image file.
946 if (unlink(image_path.c_str()) < 0) {
947 if (errno != ENOENT) {
948 PLOG(ERROR) << "Couldn't unlink image file " << image_path;
949 }
950 }
951 } else if (!set_permissions_and_ownership(
952 image_file.fd(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
953 ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
954 image_file.reset();
955 }
956
957 return image_file;
958 }
959
960 // Creates the dexopt swap file if necessary and return its fd.
961 // Returns -1 if there's no need for a swap or in case of errors.
maybe_open_dexopt_swap_file(const std::string & out_oat_path)962 unique_fd maybe_open_dexopt_swap_file(const std::string& out_oat_path) {
963 if (!ShouldUseSwapFileForDexopt()) {
964 return invalid_unique_fd();
965 }
966 auto swap_file_name = out_oat_path + ".swap";
967 unique_fd swap_fd(open_output_file(
968 swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
969 if (swap_fd.get() < 0) {
970 // Could not create swap file. Optimistically go on and hope that we can compile
971 // without it.
972 ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
973 } else {
974 // Immediately unlink. We don't really want to hit flash.
975 if (unlink(swap_file_name.c_str()) < 0) {
976 PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
977 }
978 }
979 return swap_fd;
980 }
981
982 // Opens the reference profiles if needed.
983 // Note that the reference profile might not exist so it's OK if the fd will be -1.
maybe_open_reference_profile(const std::string & pkgname,const std::string & dex_path,const char * profile_name,bool profile_guided,bool is_public,int uid,bool is_secondary_dex)984 UniqueFile maybe_open_reference_profile(const std::string& pkgname,
985 const std::string& dex_path, const char* profile_name, bool profile_guided,
986 bool is_public, int uid, bool is_secondary_dex) {
987 // If we are not profile guided compilation, or we are compiling system server
988 // do not bother to open the profiles; we won't be using them.
989 if (!profile_guided || (pkgname[0] == '*')) {
990 return UniqueFile();
991 }
992
993 // If this is a secondary dex path which is public do not open the profile.
994 // We cannot compile public secondary dex paths with profiles. That's because
995 // it will expose how the dex files are used by their owner.
996 //
997 // Note that the PackageManager is responsible to set the is_public flag for
998 // primary apks and we do not check it here. In some cases, e.g. when
999 // compiling with a public profile from the .dm file the PackageManager will
1000 // set is_public toghether with the profile guided compilation.
1001 if (is_secondary_dex && is_public) {
1002 return UniqueFile();
1003 }
1004
1005 // Open reference profile in read only mode as dex2oat does not get write permissions.
1006 std::string location;
1007 if (is_secondary_dex) {
1008 location = dex_path;
1009 } else {
1010 if (profile_name == nullptr) {
1011 // This path is taken for system server re-compilation lunched from ZygoteInit.
1012 return UniqueFile();
1013 } else {
1014 location = profile_name;
1015 }
1016 }
1017 return open_reference_profile_as_unique_file(uid, pkgname, location, /*read_write*/false,
1018 is_secondary_dex);
1019 }
1020
1021 // Opens the vdex files and assigns the input fd to in_vdex_wrapper and the output fd to
1022 // out_vdex_wrapper. Returns true for success or false in case of errors.
open_vdex_files_for_dex2oat(const char * apk_path,const char * out_oat_path,int dexopt_needed,const char * instruction_set,bool is_public,int uid,bool is_secondary_dex,bool profile_guided,UniqueFile * in_vdex_wrapper,UniqueFile * out_vdex_wrapper)1023 bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
1024 const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
1025 bool profile_guided, UniqueFile* in_vdex_wrapper,
1026 UniqueFile* out_vdex_wrapper) {
1027 CHECK(in_vdex_wrapper != nullptr);
1028 CHECK(out_vdex_wrapper != nullptr);
1029 // Open the existing VDEX. We do this before creating the new output VDEX, which will
1030 // unlink the old one.
1031 char in_odex_path[PKG_PATH_MAX];
1032 int dexopt_action = abs(dexopt_needed);
1033 bool is_odex_location = dexopt_needed < 0;
1034
1035 // Infer the name of the output VDEX.
1036 const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
1037 if (out_vdex_path_str.empty()) {
1038 return false;
1039 }
1040
1041 bool update_vdex_in_place = false;
1042 if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
1043 // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
1044 const char* path = nullptr;
1045 if (is_odex_location) {
1046 if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
1047 path = in_odex_path;
1048 } else {
1049 ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
1050 return false;
1051 }
1052 } else {
1053 path = out_oat_path;
1054 }
1055 std::string in_vdex_path_str = create_vdex_filename(path);
1056 if (in_vdex_path_str.empty()) {
1057 ALOGE("installd cannot compute input vdex location for '%s'\n", path);
1058 return false;
1059 }
1060 // We can update in place when all these conditions are met:
1061 // 1) The vdex location to write to is the same as the vdex location to read (vdex files
1062 // on /system typically cannot be updated in place).
1063 // 2) We dex2oat due to boot image change, because we then know the existing vdex file
1064 // cannot be currently used by a running process.
1065 // 3) We are not doing a profile guided compilation, because dexlayout requires two
1066 // different vdex files to operate.
1067 update_vdex_in_place =
1068 (in_vdex_path_str == out_vdex_path_str) &&
1069 (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
1070 !profile_guided;
1071 if (update_vdex_in_place) {
1072 // Open the file read-write to be able to update it.
1073 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0),
1074 in_vdex_path_str);
1075 if (in_vdex_wrapper->fd() == -1) {
1076 // If we failed to open the file, we cannot update it in place.
1077 update_vdex_in_place = false;
1078 }
1079 } else {
1080 in_vdex_wrapper->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0),
1081 in_vdex_path_str);
1082 }
1083 }
1084
1085 // If we are updating the vdex in place, we do not need to recreate a vdex,
1086 // and can use the same existing one.
1087 if (update_vdex_in_place) {
1088 // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
1089 // have bogus stale vdex files.
1090 out_vdex_wrapper->reset(
1091 in_vdex_wrapper->fd(),
1092 out_vdex_path_str,
1093 UnlinkIgnoreResult);
1094 // Disable auto close for the in wrapper fd (it will be done when destructing the out
1095 // wrapper).
1096 in_vdex_wrapper->DisableAutoClose();
1097 } else {
1098 out_vdex_wrapper->reset(
1099 open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
1100 out_vdex_path_str,
1101 UnlinkIgnoreResult);
1102 if (out_vdex_wrapper->fd() < 0) {
1103 ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
1104 return false;
1105 }
1106 }
1107 if (!set_permissions_and_ownership(out_vdex_wrapper->fd(), is_public, uid,
1108 out_vdex_path_str.c_str(), is_secondary_dex)) {
1109 ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
1110 return false;
1111 }
1112
1113 // If we got here we successfully opened the vdex files.
1114 return true;
1115 }
1116
1117 // Opens the output oat file for the given apk.
open_oat_out_file(const char * apk_path,const char * oat_dir,bool is_public,int uid,const char * instruction_set,bool is_secondary_dex)1118 UniqueFile open_oat_out_file(const char* apk_path, const char* oat_dir,
1119 bool is_public, int uid, const char* instruction_set, bool is_secondary_dex) {
1120 char out_oat_path[PKG_PATH_MAX];
1121 if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
1122 return UniqueFile();
1123 }
1124 UniqueFile oat(
1125 open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
1126 out_oat_path,
1127 UnlinkIgnoreResult);
1128 if (oat.fd() < 0) {
1129 PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
1130 } else if (!set_permissions_and_ownership(
1131 oat.fd(), is_public, uid, out_oat_path, is_secondary_dex)) {
1132 ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
1133 oat.reset();
1134 }
1135 return oat;
1136 }
1137
1138 // Creates RDONLY fds for oat and vdex files, if exist.
1139 // Returns false if it fails to create oat out path for the given apk path.
1140 // Note that the method returns true even if the files could not be opened.
maybe_open_oat_and_vdex_file(const std::string & apk_path,const std::string & oat_dir,const std::string & instruction_set,bool is_secondary_dex,unique_fd * oat_file_fd,unique_fd * vdex_file_fd)1141 bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
1142 const std::string& oat_dir,
1143 const std::string& instruction_set,
1144 bool is_secondary_dex,
1145 unique_fd* oat_file_fd,
1146 unique_fd* vdex_file_fd) {
1147 char oat_path[PKG_PATH_MAX];
1148 if (!create_oat_out_path(apk_path.c_str(),
1149 instruction_set.c_str(),
1150 oat_dir.c_str(),
1151 is_secondary_dex,
1152 oat_path)) {
1153 LOG(ERROR) << "Could not create oat out path for "
1154 << apk_path << " with oat dir " << oat_dir;
1155 return false;
1156 }
1157 oat_file_fd->reset(open(oat_path, O_RDONLY));
1158 if (oat_file_fd->get() < 0) {
1159 PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
1160 }
1161
1162 std::string vdex_filename = create_vdex_filename(oat_path);
1163 vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
1164 if (vdex_file_fd->get() < 0) {
1165 PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
1166 }
1167
1168 return true;
1169 }
1170
1171 // Runs (execv) dexoptanalyzer on the given arguments.
1172 // The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
1173 // If this is for a profile guided compilation, profile_was_updated will tell whether or not
1174 // the profile has changed.
1175 class RunDexoptAnalyzer : public ExecVHelper {
1176 public:
RunDexoptAnalyzer(const std::string & dex_file,int vdex_fd,int oat_fd,int zip_fd,const std::string & instruction_set,const std::string & compiler_filter,int profile_analysis_result,bool downgrade,const char * class_loader_context,const std::string & class_loader_context_fds)1177 RunDexoptAnalyzer(const std::string& dex_file,
1178 int vdex_fd,
1179 int oat_fd,
1180 int zip_fd,
1181 const std::string& instruction_set,
1182 const std::string& compiler_filter,
1183 int profile_analysis_result,
1184 bool downgrade,
1185 const char* class_loader_context,
1186 const std::string& class_loader_context_fds) {
1187 CHECK_GE(zip_fd, 0);
1188
1189 // We always run the analyzer in the background job.
1190 const char* dexoptanalyzer_bin = select_execution_binary(
1191 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1192
1193 std::string dex_file_arg = "--dex-file=" + dex_file;
1194 std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
1195 std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
1196 std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
1197 std::string isa_arg = "--isa=" + instruction_set;
1198 std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
1199 std::string profile_analysis_arg = "--profile-analysis-result="
1200 + std::to_string(profile_analysis_result);
1201 const char* downgrade_flag = "--downgrade";
1202 std::string class_loader_context_arg = "--class-loader-context=";
1203 if (class_loader_context != nullptr) {
1204 class_loader_context_arg += class_loader_context;
1205 }
1206 std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
1207 if (!class_loader_context_fds.empty()) {
1208 class_loader_context_fds_arg += class_loader_context_fds;
1209 }
1210
1211 // program name, dex file, isa, filter
1212 AddArg(dex_file_arg);
1213 AddArg(isa_arg);
1214 AddArg(compiler_filter_arg);
1215 if (oat_fd >= 0) {
1216 AddArg(oat_fd_arg);
1217 }
1218 if (vdex_fd >= 0) {
1219 AddArg(vdex_fd_arg);
1220 }
1221 AddArg(zip_fd_arg);
1222 AddArg(profile_analysis_arg);
1223
1224 if (downgrade) {
1225 AddArg(downgrade_flag);
1226 }
1227 if (class_loader_context != nullptr) {
1228 AddArg(class_loader_context_arg);
1229 if (!class_loader_context_fds.empty()) {
1230 AddArg(class_loader_context_fds_arg);
1231 }
1232 }
1233
1234 // On-device signing related. odsign sets the system property odsign.verification.success if
1235 // AOT artifacts have the expected signatures.
1236 const bool trust_art_apex_data_files =
1237 ::android::base::GetBoolProperty("odsign.verification.success", false);
1238 if (!trust_art_apex_data_files) {
1239 AddRuntimeArg("-Xdeny-art-apex-data-files");
1240 }
1241
1242 PrepareArgs(dexoptanalyzer_bin);
1243 }
1244
1245 // Dexoptanalyzer mode which flattens the given class loader context and
1246 // prints a list of its dex files in that flattened order.
RunDexoptAnalyzer(const char * class_loader_context)1247 RunDexoptAnalyzer(const char* class_loader_context) {
1248 CHECK(class_loader_context != nullptr);
1249
1250 // We always run the analyzer in the background job.
1251 const char* dexoptanalyzer_bin = select_execution_binary(
1252 kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
1253
1254 AddArg("--flatten-class-loader-context");
1255 AddArg(std::string("--class-loader-context=") + class_loader_context);
1256 PrepareArgs(dexoptanalyzer_bin);
1257 }
1258 };
1259
1260 // Prepares the oat dir for the secondary dex files.
prepare_secondary_dex_oat_dir(const std::string & dex_path,int uid,const char * instruction_set)1261 static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
1262 const char* instruction_set) {
1263 unsigned long dirIndex = dex_path.rfind('/');
1264 if (dirIndex == std::string::npos) {
1265 LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
1266 return false;
1267 }
1268 std::string dex_dir = dex_path.substr(0, dirIndex);
1269
1270 // Create oat file output directory.
1271 mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
1272 if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
1273 LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
1274 return false;
1275 }
1276
1277 char oat_dir[PKG_PATH_MAX];
1278 snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
1279
1280 if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
1281 LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
1282 return false;
1283 }
1284
1285 return true;
1286 }
1287
1288 // Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
1289 // secondary dex files. This return codes are returned by the child process created for
1290 // analyzing secondary dex files in process_secondary_dex_dexopt.
1291
1292 enum DexoptAnalyzerSkipCodes {
1293 // The dexoptanalyzer was not invoked because of validation or IO errors.
1294 // Specific errors are encoded in the name.
1295 kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
1296 kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
1297 kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
1298 kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
1299 kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
1300 // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
1301 kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
1302 };
1303
1304 // Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
1305 // If the result is valid returns true and sets dexopt_needed_out to a valid value.
1306 // Returns false for errors or unexpected result values.
1307 // The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
1308 // of dexoptanalyzer.
process_secondary_dexoptanalyzer_result(const std::string & dex_path,int result,int * dexopt_needed_out,std::string * error_msg)1309 static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
1310 int* dexopt_needed_out, std::string* error_msg) {
1311 // The result values are defined in dexoptanalyzer.
1312 switch (result) {
1313 case 0: // dexoptanalyzer: no_dexopt_needed
1314 *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
1315 case 1: // dexoptanalyzer: dex2oat_from_scratch
1316 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
1317 case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
1318 *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
1319 case 5: // dexoptanalyzer: dex2oat_for_filter_odex
1320 *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
1321 case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
1322 case 3: // dexoptanalyzer: dex2oat_for_filter_oat
1323 *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
1324 " Expected odex file status for secondary dex %s"
1325 " : dexoptanalyzer result=%d",
1326 dex_path.c_str(),
1327 result);
1328 return false;
1329 }
1330
1331 // Use a second switch for enum switch-case analysis.
1332 switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
1333 case kSecondaryDexDexoptAnalyzerSkippedNoFile:
1334 // If the file does not exist there's no need for dexopt.
1335 *dexopt_needed_out = NO_DEXOPT_NEEDED;
1336 return true;
1337
1338 case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
1339 *error_msg = "Dexoptanalyzer path validation failed";
1340 return false;
1341 case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
1342 *error_msg = "Dexoptanalyzer open zip failed";
1343 return false;
1344 case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
1345 *error_msg = "Dexoptanalyzer dir preparation failed";
1346 return false;
1347 case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
1348 *error_msg = "Dexoptanalyzer open output failed";
1349 return false;
1350 case kSecondaryDexDexoptAnalyzerSkippedFailExec:
1351 *error_msg = "Dexoptanalyzer failed to execute";
1352 return false;
1353 }
1354
1355 *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
1356 dex_path.c_str(),
1357 result);
1358 return false;
1359 }
1360
1361 enum SecondaryDexAccess {
1362 kSecondaryDexAccessReadOk = 0,
1363 kSecondaryDexAccessDoesNotExist = 1,
1364 kSecondaryDexAccessPermissionError = 2,
1365 kSecondaryDexAccessIOError = 3
1366 };
1367
check_secondary_dex_access(const std::string & dex_path)1368 static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
1369 // Check if the path exists and can be read. If not, there's nothing to do.
1370 if (access(dex_path.c_str(), R_OK) == 0) {
1371 return kSecondaryDexAccessReadOk;
1372 } else {
1373 if (errno == ENOENT) {
1374 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
1375 "Secondary dex does not exist: %s", dex_path.c_str());
1376 return kSecondaryDexAccessDoesNotExist;
1377 } else {
1378 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1379 "Could not access secondary dex: %s (%d)", dex_path.c_str(), errno);
1380 return errno == EACCES
1381 ? kSecondaryDexAccessPermissionError
1382 : kSecondaryDexAccessIOError;
1383 }
1384 }
1385 }
1386
is_file_public(const std::string & filename)1387 static bool is_file_public(const std::string& filename) {
1388 struct stat file_stat;
1389 if (stat(filename.c_str(), &file_stat) == 0) {
1390 return (file_stat.st_mode & S_IROTH) != 0;
1391 }
1392 return false;
1393 }
1394
1395 // Create the oat file structure for the secondary dex 'dex_path' and assign
1396 // the individual path component to the 'out_' parameters.
create_secondary_dex_oat_layout(const std::string & dex_path,const std::string & isa,char * out_oat_dir,char * out_oat_isa_dir,char * out_oat_path,std::string * error_msg)1397 static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
1398 char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
1399 size_t dirIndex = dex_path.rfind('/');
1400 if (dirIndex == std::string::npos) {
1401 *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
1402 return false;
1403 }
1404 // TODO(calin): we have similar computations in at lest 3 other places
1405 // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
1406 // using string append.
1407 std::string apk_dir = dex_path.substr(0, dirIndex);
1408 snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
1409 snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
1410
1411 if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
1412 /*is_secondary_dex*/true, out_oat_path)) {
1413 *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
1414 return false;
1415 }
1416 return true;
1417 }
1418
1419 // Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
1420 // recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
validate_dexopt_storage_flags(int dexopt_flags,int * out_storage_flag,std::string * error_msg)1421 static bool validate_dexopt_storage_flags(int dexopt_flags,
1422 int* out_storage_flag,
1423 std::string* error_msg) {
1424 if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
1425 *out_storage_flag = FLAG_STORAGE_CE;
1426 if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1427 *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
1428 return false;
1429 }
1430 } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
1431 *out_storage_flag = FLAG_STORAGE_DE;
1432 } else {
1433 *error_msg = "Secondary dex storage flag must be set";
1434 return false;
1435 }
1436 return true;
1437 }
1438
get_class_loader_context_dex_paths(const char * class_loader_context,int uid,std::vector<std::string> * context_dex_paths)1439 static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
1440 /* out */ std::vector<std::string>* context_dex_paths) {
1441 if (class_loader_context == nullptr) {
1442 return true;
1443 }
1444
1445 LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
1446
1447 // Pipe to get the hash result back from our child process.
1448 unique_fd pipe_read, pipe_write;
1449 if (!Pipe(&pipe_read, &pipe_write)) {
1450 PLOG(ERROR) << "Failed to create pipe";
1451 return false;
1452 }
1453
1454 pid_t pid = fork();
1455 if (pid == 0) {
1456 // child -- drop privileges before continuing.
1457 drop_capabilities(uid);
1458
1459 // Route stdout to `pipe_write`
1460 while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
1461 pipe_write.reset();
1462 pipe_read.reset();
1463
1464 RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
1465 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1466 }
1467
1468 /* parent */
1469 pipe_write.reset();
1470
1471 std::string str_dex_paths;
1472 if (!ReadFdToString(pipe_read, &str_dex_paths)) {
1473 PLOG(ERROR) << "Failed to read from pipe";
1474 return false;
1475 }
1476 pipe_read.reset();
1477
1478 int return_code = wait_child(pid);
1479 if (!WIFEXITED(return_code)) {
1480 PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
1481 return false;
1482 }
1483
1484 constexpr int kFlattenClassLoaderContextSuccess = 50;
1485 return_code = WEXITSTATUS(return_code);
1486 if (return_code != kFlattenClassLoaderContextSuccess) {
1487 LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
1488 return false;
1489 }
1490
1491 if (!str_dex_paths.empty()) {
1492 *context_dex_paths = android::base::Split(str_dex_paths, ":");
1493 }
1494 return true;
1495 }
1496
open_dex_paths(const std::vector<std::string> & dex_paths,std::vector<unique_fd> * zip_fds,std::string * error_msg)1497 static int open_dex_paths(const std::vector<std::string>& dex_paths,
1498 /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
1499 for (const std::string& dex_path : dex_paths) {
1500 zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
1501 if (zip_fds->back().get() < 0) {
1502 *error_msg = StringPrintf(
1503 "installd cannot open '%s' for input during dexopt", dex_path.c_str());
1504 if (errno == ENOENT) {
1505 return kSecondaryDexDexoptAnalyzerSkippedNoFile;
1506 } else {
1507 return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
1508 }
1509 }
1510 }
1511 return 0;
1512 }
1513
join_fds(const std::vector<unique_fd> & fds)1514 static std::string join_fds(const std::vector<unique_fd>& fds) {
1515 std::stringstream ss;
1516 bool is_first = true;
1517 for (const unique_fd& fd : fds) {
1518 if (is_first) {
1519 is_first = false;
1520 } else {
1521 ss << ":";
1522 }
1523 ss << fd.get();
1524 }
1525 return ss.str();
1526 }
1527
1528 // Processes the dex_path as a secondary dex files and return true if the path dex file should
1529 // be compiled. Returns false for errors (logged) or true if the secondary dex path was process
1530 // successfully.
1531 // When returning true, the output parameters will be:
1532 // - is_public_out: whether or not the oat file should not be made public
1533 // - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
1534 // - oat_dir_out: the oat dir path where the oat file should be stored
process_secondary_dex_dexopt(const std::string & dex_path,const char * pkgname,int dexopt_flags,const char * volume_uuid,int uid,const char * instruction_set,const char * compiler_filter,bool * is_public_out,int * dexopt_needed_out,std::string * oat_dir_out,bool downgrade,const char * class_loader_context,const std::vector<std::string> & context_dex_paths,std::string * error_msg)1535 static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
1536 int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
1537 const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
1538 std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
1539 const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
1540 LOG(DEBUG) << "Processing secondary dex path " << dex_path;
1541 int storage_flag;
1542 if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
1543 LOG(ERROR) << *error_msg;
1544 return false;
1545 }
1546 // Compute the oat dir as it's not easy to extract it from the child computation.
1547 char oat_path[PKG_PATH_MAX];
1548 char oat_dir[PKG_PATH_MAX];
1549 char oat_isa_dir[PKG_PATH_MAX];
1550 if (!create_secondary_dex_oat_layout(
1551 dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
1552 LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
1553 return false;
1554 }
1555 oat_dir_out->assign(oat_dir);
1556
1557 pid_t pid = fork();
1558 if (pid == 0) {
1559 // child -- drop privileges before continuing.
1560 drop_capabilities(uid);
1561
1562 // Validate the path structure.
1563 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
1564 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1565 "Could not validate secondary dex path %s", dex_path.c_str());
1566 _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
1567 }
1568
1569 // Open the dex file.
1570 unique_fd zip_fd;
1571 zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
1572 if (zip_fd.get() < 0) {
1573 if (errno == ENOENT) {
1574 _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
1575 } else {
1576 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
1577 }
1578 }
1579
1580 // Open class loader context dex files.
1581 std::vector<unique_fd> context_zip_fds;
1582 int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
1583 if (open_dex_paths_rc != 0) {
1584 _exit(open_dex_paths_rc);
1585 }
1586
1587 // Prepare the oat directories.
1588 if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
1589 _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
1590 }
1591
1592 // Open the vdex/oat files if any.
1593 unique_fd oat_file_fd;
1594 unique_fd vdex_file_fd;
1595 if (!maybe_open_oat_and_vdex_file(dex_path,
1596 *oat_dir_out,
1597 instruction_set,
1598 true /* is_secondary_dex */,
1599 &oat_file_fd,
1600 &vdex_file_fd)) {
1601 _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
1602 }
1603
1604 // Analyze profiles.
1605 int profile_analysis_result = analyze_profiles(uid, pkgname, dex_path,
1606 /*is_secondary_dex*/true);
1607
1608 // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
1609 // Note that we do not do it before the fork since opening the files is required to happen
1610 // after forking.
1611 RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
1612 vdex_file_fd.get(),
1613 oat_file_fd.get(),
1614 zip_fd.get(),
1615 instruction_set,
1616 compiler_filter,
1617 profile_analysis_result,
1618 downgrade,
1619 class_loader_context,
1620 join_fds(context_zip_fds));
1621 run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
1622 }
1623
1624 /* parent */
1625 int result = wait_child(pid);
1626 if (!WIFEXITED(result)) {
1627 *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
1628 dex_path.c_str(),
1629 result);
1630 LOG(ERROR) << *error_msg;
1631 return false;
1632 }
1633 result = WEXITSTATUS(result);
1634 // Check that we successfully executed dexoptanalyzer.
1635 bool success = process_secondary_dexoptanalyzer_result(dex_path,
1636 result,
1637 dexopt_needed_out,
1638 error_msg);
1639 if (!success) {
1640 LOG(ERROR) << *error_msg;
1641 }
1642
1643 LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
1644
1645 // Run dexopt only if needed or forced.
1646 // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
1647 // makes the code simpler; force compilation is only needed during tests).
1648 if (success &&
1649 (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
1650 ((dexopt_flags & DEXOPT_FORCE) != 0)) {
1651 *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
1652 }
1653
1654 // Check if we should make the oat file public.
1655 // Note that if the dex file is not public the compiled code cannot be made public.
1656 // It is ok to check this flag outside in the parent process.
1657 *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
1658
1659 return success;
1660 }
1661
format_dexopt_error(int status,const char * dex_path)1662 static std::string format_dexopt_error(int status, const char* dex_path) {
1663 if (WIFEXITED(status)) {
1664 int int_code = WEXITSTATUS(status);
1665 const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
1666 if (code_name != nullptr) {
1667 return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
1668 }
1669 }
1670 return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
1671 }
1672
dexopt(const char * dex_path,uid_t uid,const char * pkgname,const char * instruction_set,int dexopt_needed,const char * oat_dir,int dexopt_flags,const char * compiler_filter,const char * volume_uuid,const char * class_loader_context,const char * se_info,bool downgrade,int target_sdk_version,const char * profile_name,const char * dex_metadata_path,const char * compilation_reason,std::string * error_msg)1673 int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
1674 int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
1675 const char* volume_uuid, const char* class_loader_context, const char* se_info,
1676 bool downgrade, int target_sdk_version, const char* profile_name,
1677 const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
1678 CHECK(pkgname != nullptr);
1679 CHECK(pkgname[0] != 0);
1680 CHECK(error_msg != nullptr);
1681 CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
1682 << "dexopt flags contains unknown fields: " << dexopt_flags;
1683
1684 if (!validate_dex_path_size(dex_path)) {
1685 *error_msg = StringPrintf("Failed to validate %s", dex_path);
1686 return -1;
1687 }
1688
1689 if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
1690 *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
1691 class_loader_context);
1692 LOG(ERROR) << *error_msg;
1693 return -1;
1694 }
1695
1696 bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
1697 bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
1698 bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
1699 bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
1700 bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
1701 bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
1702 bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
1703 bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
1704 bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
1705 bool for_restore = (dexopt_flags & DEXOPT_FOR_RESTORE) != 0;
1706
1707 // Check if we're dealing with a secondary dex file and if we need to compile it.
1708 std::string oat_dir_str;
1709 std::vector<std::string> context_dex_paths;
1710 if (is_secondary_dex) {
1711 if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
1712 *error_msg = "Failed acquiring context dex paths";
1713 return -1; // We had an error, logged in the process method.
1714 }
1715
1716 if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
1717 instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
1718 downgrade, class_loader_context, context_dex_paths, error_msg)) {
1719 oat_dir = oat_dir_str.c_str();
1720 if (dexopt_needed == NO_DEXOPT_NEEDED) {
1721 return 0; // Nothing to do, report success.
1722 }
1723 } else {
1724 if (error_msg->empty()) { // TODO: Make this a CHECK.
1725 *error_msg = "Failed processing secondary.";
1726 }
1727 return -1; // We had an error, logged in the process method.
1728 }
1729 } else {
1730 // Currently these flags are only used for secondary dex files.
1731 // Verify that they are not set for primary apks.
1732 CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
1733 CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
1734 }
1735
1736 // Open the input file.
1737 UniqueFile in_dex(open(dex_path, O_RDONLY, 0), dex_path);
1738 if (in_dex.fd() < 0) {
1739 *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
1740 LOG(ERROR) << *error_msg;
1741 return -1;
1742 }
1743
1744 // Open class loader context dex files.
1745 std::vector<unique_fd> context_input_fds;
1746 if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
1747 LOG(ERROR) << *error_msg;
1748 return -1;
1749 }
1750
1751 // Create the output OAT file.
1752 UniqueFile out_oat = open_oat_out_file(dex_path, oat_dir, is_public, uid,
1753 instruction_set, is_secondary_dex);
1754 if (out_oat.fd() < 0) {
1755 *error_msg = "Could not open out oat file.";
1756 return -1;
1757 }
1758
1759 // Open vdex files.
1760 UniqueFile in_vdex;
1761 UniqueFile out_vdex;
1762 if (!open_vdex_files_for_dex2oat(dex_path, out_oat.path().c_str(), dexopt_needed,
1763 instruction_set, is_public, uid, is_secondary_dex, profile_guided, &in_vdex,
1764 &out_vdex)) {
1765 *error_msg = "Could not open vdex files.";
1766 return -1;
1767 }
1768
1769 // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
1770 // selinux context (we generate them on the fly during the dexopt invocation and they don't
1771 // fully inherit their parent context).
1772 // Note that for primary apk the oat files are created before, in a separate installd
1773 // call which also does the restorecon. TODO(calin): unify the paths.
1774 if (is_secondary_dex) {
1775 if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
1776 SELINUX_ANDROID_RESTORECON_RECURSE)) {
1777 *error_msg = std::string("Failed to restorecon ").append(oat_dir);
1778 LOG(ERROR) << *error_msg;
1779 return -1;
1780 }
1781 }
1782
1783 // Create a swap file if necessary.
1784 unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat.path());
1785
1786 // Open the reference profile if needed.
1787 UniqueFile reference_profile = maybe_open_reference_profile(
1788 pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
1789
1790 if (reference_profile.fd() == -1) {
1791 // We don't create an app image without reference profile since there is no speedup from
1792 // loading it in that case and instead will be a small overhead.
1793 generate_app_image = false;
1794 }
1795
1796 // Create the app image file if needed.
1797 UniqueFile out_image = maybe_open_app_image(
1798 out_oat.path(), generate_app_image, is_public, uid, is_secondary_dex);
1799
1800 UniqueFile dex_metadata;
1801 if (dex_metadata_path != nullptr) {
1802 dex_metadata.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)),
1803 dex_metadata_path);
1804 if (dex_metadata.fd() < 0) {
1805 PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
1806 }
1807 }
1808
1809 std::string jitzygote_flag = server_configurable_flags::GetServerConfigurableFlag(
1810 RUNTIME_NATIVE_BOOT_NAMESPACE,
1811 ENABLE_JITZYGOTE_IMAGE,
1812 /*default_value=*/ "");
1813 bool use_jitzygote_image = jitzygote_flag == "true" || IsBootClassPathProfilingEnable();
1814
1815 // Decide whether to use dex2oat64.
1816 bool use_dex2oat64 = false;
1817 // Check whether the device even supports 64-bit ABIs.
1818 if (!GetProperty("ro.product.cpu.abilist64", "").empty()) {
1819 use_dex2oat64 = GetBoolProperty("dalvik.vm.dex2oat64.enabled", false);
1820 }
1821 const char* dex2oat_bin = select_execution_binary(
1822 (use_dex2oat64 ? kDex2oat64Path : kDex2oat32Path),
1823 (use_dex2oat64 ? kDex2oatDebug64Path : kDex2oatDebug32Path),
1824 background_job_compile);
1825
1826 auto execv_helper = std::make_unique<ExecVHelper>();
1827
1828 LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
1829
1830 RunDex2Oat runner(dex2oat_bin, execv_helper.get());
1831 runner.Initialize(out_oat,
1832 out_vdex,
1833 out_image,
1834 in_dex,
1835 in_vdex,
1836 dex_metadata,
1837 reference_profile,
1838 class_loader_context,
1839 join_fds(context_input_fds),
1840 swap_fd.get(),
1841 instruction_set,
1842 compiler_filter,
1843 debuggable,
1844 boot_complete,
1845 for_restore,
1846 target_sdk_version,
1847 enable_hidden_api_checks,
1848 generate_compact_dex,
1849 use_jitzygote_image,
1850 compilation_reason);
1851
1852 pid_t pid = fork();
1853 if (pid == 0) {
1854 // Need to set schedpolicy before dropping privileges
1855 // for cgroup migration. See details at b/175178520.
1856 SetDex2OatScheduling(boot_complete);
1857
1858 /* child -- drop privileges before continuing */
1859 drop_capabilities(uid);
1860
1861 if (flock(out_oat.fd(), LOCK_EX | LOCK_NB) != 0) {
1862 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "flock(%s) failed",
1863 out_oat.path().c_str());
1864 _exit(DexoptReturnCodes::kFlock);
1865 }
1866
1867 runner.Exec(DexoptReturnCodes::kDex2oatExec);
1868 } else {
1869 int res = wait_child(pid);
1870 if (res == 0) {
1871 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
1872 } else {
1873 LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
1874 << std::hex << std::setw(4) << res << ", process failed";
1875 *error_msg = format_dexopt_error(res, dex_path);
1876 return res;
1877 }
1878 }
1879
1880 // We've been successful, don't delete output.
1881 out_oat.DisableCleanup();
1882 out_vdex.DisableCleanup();
1883 out_image.DisableCleanup();
1884 reference_profile.DisableCleanup();
1885
1886 return 0;
1887 }
1888
1889 // Try to remove the given directory. Log an error if the directory exists
1890 // and is empty but could not be removed.
rmdir_if_empty(const char * dir)1891 static bool rmdir_if_empty(const char* dir) {
1892 if (rmdir(dir) == 0) {
1893 return true;
1894 }
1895 if (errno == ENOENT || errno == ENOTEMPTY) {
1896 return true;
1897 }
1898 PLOG(ERROR) << "Failed to remove dir: " << dir;
1899 return false;
1900 }
1901
1902 // Try to unlink the given file. Log an error if the file exists and could not
1903 // be unlinked.
unlink_if_exists(const std::string & file)1904 static bool unlink_if_exists(const std::string& file) {
1905 if (unlink(file.c_str()) == 0) {
1906 return true;
1907 }
1908 if (errno == ENOENT) {
1909 return true;
1910
1911 }
1912 PLOG(ERROR) << "Could not unlink: " << file;
1913 return false;
1914 }
1915
1916 enum ReconcileSecondaryDexResult {
1917 kReconcileSecondaryDexExists = 0,
1918 kReconcileSecondaryDexCleanedUp = 1,
1919 kReconcileSecondaryDexValidationError = 2,
1920 kReconcileSecondaryDexCleanUpError = 3,
1921 kReconcileSecondaryDexAccessIOError = 4,
1922 };
1923
1924 // Reconcile the secondary dex 'dex_path' and its generated oat files.
1925 // Return true if all the parameters are valid and the secondary dex file was
1926 // processed successfully (i.e. the dex_path either exists, or if not, its corresponding
1927 // oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
1928 // will be true if the secondary dex file still exists. If the secondary dex file does not exist,
1929 // the method cleans up any previously generated compiler artifacts (oat, vdex, art).
1930 // Return false if there were errors during processing. In this case
1931 // out_secondary_dex_exists will be set to false.
reconcile_secondary_dex_file(const std::string & dex_path,const std::string & pkgname,int uid,const std::vector<std::string> & isas,const std::optional<std::string> & volume_uuid,int storage_flag,bool * out_secondary_dex_exists)1932 bool reconcile_secondary_dex_file(const std::string& dex_path,
1933 const std::string& pkgname, int uid, const std::vector<std::string>& isas,
1934 const std::optional<std::string>& volume_uuid, int storage_flag,
1935 /*out*/bool* out_secondary_dex_exists) {
1936 *out_secondary_dex_exists = false; // start by assuming the file does not exist.
1937 if (isas.size() == 0) {
1938 LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
1939 return false;
1940 }
1941
1942 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
1943 LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
1944 << storage_flag;
1945 return false;
1946 }
1947
1948 // As a security measure we want to unlink art artifacts with the reduced capabilities
1949 // of the package user id. So we fork and drop capabilities in the child.
1950 pid_t pid = fork();
1951 if (pid == 0) {
1952 /* child -- drop privileges before continuing */
1953 drop_capabilities(uid);
1954
1955 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
1956 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
1957 uid, storage_flag)) {
1958 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1959 "Could not validate secondary dex path %s", dex_path.c_str());
1960 _exit(kReconcileSecondaryDexValidationError);
1961 }
1962
1963 SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
1964 switch (access_check) {
1965 case kSecondaryDexAccessDoesNotExist:
1966 // File does not exist. Proceed with cleaning.
1967 break;
1968 case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
1969 case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
1970 case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
1971 default:
1972 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
1973 "Unexpected result from check_secondary_dex_access: %d", access_check);
1974 _exit(kReconcileSecondaryDexValidationError);
1975 }
1976
1977 // The secondary dex does not exist anymore or it's. Clear any generated files.
1978 char oat_path[PKG_PATH_MAX];
1979 char oat_dir[PKG_PATH_MAX];
1980 char oat_isa_dir[PKG_PATH_MAX];
1981 bool result = true;
1982 for (size_t i = 0; i < isas.size(); i++) {
1983 std::string error_msg;
1984 if (!create_secondary_dex_oat_layout(
1985 dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
1986 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
1987 _exit(kReconcileSecondaryDexValidationError);
1988 }
1989
1990 // Delete oat/vdex/art files.
1991 result = unlink_if_exists(oat_path) && result;
1992 result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
1993 result = unlink_if_exists(create_image_filename(oat_path)) && result;
1994
1995 // Delete profiles.
1996 std::string current_profile = create_current_profile_path(
1997 multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
1998 std::string reference_profile = create_reference_profile_path(
1999 pkgname, dex_path, /*is_secondary*/true);
2000 result = unlink_if_exists(current_profile) && result;
2001 result = unlink_if_exists(reference_profile) && result;
2002
2003 // We upgraded once the location of current profile for secondary dex files.
2004 // Check for any previous left-overs and remove them as well.
2005 std::string old_current_profile = dex_path + ".prof";
2006 result = unlink_if_exists(old_current_profile);
2007
2008 // Try removing the directories as well, they might be empty.
2009 result = rmdir_if_empty(oat_isa_dir) && result;
2010 result = rmdir_if_empty(oat_dir) && result;
2011 }
2012 if (!result) {
2013 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2014 "Could not validate secondary dex path %s", dex_path.c_str());
2015 }
2016 _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
2017 }
2018
2019 int return_code = wait_child(pid);
2020 if (!WIFEXITED(return_code)) {
2021 LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
2022 } else {
2023 return_code = WEXITSTATUS(return_code);
2024 }
2025
2026 LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
2027
2028 switch (return_code) {
2029 case kReconcileSecondaryDexCleanedUp:
2030 case kReconcileSecondaryDexValidationError:
2031 // If we couldn't validate assume the dex file does not exist.
2032 // This will purge the entry from the PM records.
2033 *out_secondary_dex_exists = false;
2034 return true;
2035 case kReconcileSecondaryDexExists:
2036 *out_secondary_dex_exists = true;
2037 return true;
2038 case kReconcileSecondaryDexAccessIOError:
2039 // We had an access IO error.
2040 // Return false so that we can try again.
2041 // The value of out_secondary_dex_exists does not matter in this case and by convention
2042 // is set to false.
2043 *out_secondary_dex_exists = false;
2044 return false;
2045 default:
2046 LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
2047 *out_secondary_dex_exists = false;
2048 return false;
2049 }
2050 }
2051
2052 // Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
2053 // Returns true if all parameters are valid and the hash successfully computed and stored in
2054 // out_secondary_dex_hash.
2055 // Also returns true with an empty hash if the file does not currently exist or is not accessible to
2056 // the app.
2057 // For any other errors (e.g. if any of the parameters are invalid) returns false.
hash_secondary_dex_file(const std::string & dex_path,const std::string & pkgname,int uid,const std::optional<std::string> & volume_uuid,int storage_flag,std::vector<uint8_t> * out_secondary_dex_hash)2058 bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
2059 const std::optional<std::string>& volume_uuid, int storage_flag,
2060 std::vector<uint8_t>* out_secondary_dex_hash) {
2061 out_secondary_dex_hash->clear();
2062
2063 const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
2064
2065 if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
2066 LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
2067 << storage_flag;
2068 return false;
2069 }
2070
2071 // Pipe to get the hash result back from our child process.
2072 unique_fd pipe_read, pipe_write;
2073 if (!Pipe(&pipe_read, &pipe_write)) {
2074 PLOG(ERROR) << "Failed to create pipe";
2075 return false;
2076 }
2077
2078 // Fork so that actual access to the files is done in the app's own UID, to ensure we only
2079 // access data the app itself can access.
2080 pid_t pid = fork();
2081 if (pid == 0) {
2082 // child -- drop privileges before continuing
2083 drop_capabilities(uid);
2084 pipe_read.reset();
2085
2086 if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
2087 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2088 "Could not validate secondary dex path %s", dex_path.c_str());
2089 _exit(DexoptReturnCodes::kHashValidatePath);
2090 }
2091
2092 unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
2093 if (fd == -1) {
2094 if (errno == EACCES || errno == ENOENT) {
2095 // Not treated as an error.
2096 _exit(0);
2097 }
2098 PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
2099 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2100 "Failed to open secondary dex %s: %d", dex_path.c_str(), errno);
2101 _exit(DexoptReturnCodes::kHashOpenPath);
2102 }
2103
2104 SHA256_CTX ctx;
2105 SHA256_Init(&ctx);
2106
2107 std::vector<uint8_t> buffer(65536);
2108 while (true) {
2109 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
2110 if (bytes_read == 0) {
2111 break;
2112 } else if (bytes_read == -1) {
2113 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
2114 "Failed to read secondary dex %s: %d", dex_path.c_str(), errno);
2115 _exit(DexoptReturnCodes::kHashReadDex);
2116 }
2117
2118 SHA256_Update(&ctx, buffer.data(), bytes_read);
2119 }
2120
2121 std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
2122 SHA256_Final(hash.data(), &ctx);
2123 if (!WriteFully(pipe_write, hash.data(), hash.size())) {
2124 _exit(DexoptReturnCodes::kHashWrite);
2125 }
2126
2127 _exit(0);
2128 }
2129
2130 // parent
2131 pipe_write.reset();
2132
2133 out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
2134 if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
2135 out_secondary_dex_hash->clear();
2136 }
2137 return wait_child(pid) == 0;
2138 }
2139
2140 // Helper for move_ab, so that we can have common failure-case cleanup.
unlink_and_rename(const char * from,const char * to)2141 static bool unlink_and_rename(const char* from, const char* to) {
2142 // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
2143 // return a failure.
2144 struct stat s;
2145 if (stat(to, &s) == 0) {
2146 if (!S_ISREG(s.st_mode)) {
2147 LOG(ERROR) << from << " is not a regular file to replace for A/B.";
2148 return false;
2149 }
2150 if (unlink(to) != 0) {
2151 LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
2152 return false;
2153 }
2154 } else {
2155 // This may be a permission problem. We could investigate the error code, but we'll just
2156 // let the rename failure do the work for us.
2157 }
2158
2159 // Try to rename "to" to "from."
2160 if (rename(from, to) != 0) {
2161 PLOG(ERROR) << "Could not rename " << from << " to " << to;
2162 return false;
2163 }
2164 return true;
2165 }
2166
2167 // Move/rename a B artifact (from) to an A artifact (to).
move_ab_path(const std::string & b_path,const std::string & a_path)2168 static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
2169 // Check whether B exists.
2170 {
2171 struct stat s;
2172 if (stat(b_path.c_str(), &s) != 0) {
2173 // Ignore for now. The service calling this isn't smart enough to
2174 // understand lack of artifacts at the moment.
2175 LOG(VERBOSE) << "A/B artifact " << b_path << " does not exist!";
2176 return false;
2177 }
2178 if (!S_ISREG(s.st_mode)) {
2179 LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
2180 // Try to unlink, but swallow errors.
2181 unlink(b_path.c_str());
2182 return false;
2183 }
2184 }
2185
2186 // Rename B to A.
2187 if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
2188 // Delete the b_path so we don't try again (or fail earlier).
2189 if (unlink(b_path.c_str()) != 0) {
2190 PLOG(ERROR) << "Could not unlink " << b_path;
2191 }
2192
2193 return false;
2194 }
2195
2196 return true;
2197 }
2198
move_ab(const char * apk_path,const char * instruction_set,const char * oat_dir)2199 bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2200 // Get the current slot suffix. No suffix, no A/B.
2201 const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
2202 if (slot_suffix.empty()) {
2203 return false;
2204 }
2205
2206 if (!ValidateTargetSlotSuffix(slot_suffix)) {
2207 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
2208 return false;
2209 }
2210
2211 // Validate other inputs.
2212 if (validate_apk_path(apk_path) != 0) {
2213 LOG(ERROR) << "Invalid apk_path: " << apk_path;
2214 return false;
2215 }
2216 if (validate_apk_path(oat_dir) != 0) {
2217 LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
2218 return false;
2219 }
2220
2221 char a_path[PKG_PATH_MAX];
2222 if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
2223 return false;
2224 }
2225 const std::string a_vdex_path = create_vdex_filename(a_path);
2226 const std::string a_image_path = create_image_filename(a_path);
2227
2228 // B path = A path + slot suffix.
2229 const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
2230 const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
2231 const std::string b_image_path = StringPrintf("%s.%s",
2232 a_image_path.c_str(),
2233 slot_suffix.c_str());
2234
2235 bool success = true;
2236 if (move_ab_path(b_path, a_path)) {
2237 if (move_ab_path(b_vdex_path, a_vdex_path)) {
2238 // Note: we can live without an app image. As such, ignore failure to move the image file.
2239 // If we decide to require the app image, or the app image being moved correctly,
2240 // then change accordingly.
2241 constexpr bool kIgnoreAppImageFailure = true;
2242
2243 if (!a_image_path.empty()) {
2244 if (!move_ab_path(b_image_path, a_image_path)) {
2245 unlink(a_image_path.c_str());
2246 if (!kIgnoreAppImageFailure) {
2247 success = false;
2248 }
2249 }
2250 }
2251 } else {
2252 // Cleanup: delete B image, ignore errors.
2253 unlink(b_image_path.c_str());
2254 success = false;
2255 }
2256 } else {
2257 // Cleanup: delete B image, ignore errors.
2258 unlink(b_vdex_path.c_str());
2259 unlink(b_image_path.c_str());
2260 success = false;
2261 }
2262 return success;
2263 }
2264
delete_odex(const char * apk_path,const char * instruction_set,const char * oat_dir)2265 int64_t delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
2266 // Delete the oat/odex file.
2267 char out_path[PKG_PATH_MAX];
2268 if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
2269 /*is_secondary_dex*/false, out_path)) {
2270 LOG(ERROR) << "Cannot create apk path for " << apk_path;
2271 return -1;
2272 }
2273
2274 // In case of a permission failure report the issue. Otherwise just print a warning.
2275 auto unlink_and_check = [](const char* path) -> int64_t {
2276 struct stat file_stat;
2277 if (stat(path, &file_stat) != 0) {
2278 if (errno != ENOENT) {
2279 PLOG(ERROR) << "Could not stat " << path;
2280 return -1;
2281 }
2282 return 0;
2283 }
2284
2285 if (unlink(path) != 0) {
2286 if (errno != ENOENT) {
2287 PLOG(ERROR) << "Could not unlink " << path;
2288 return -1;
2289 }
2290 }
2291 return static_cast<int64_t>(file_stat.st_size);
2292 };
2293
2294 // Delete the oat/odex file.
2295 int64_t return_value_oat = unlink_and_check(out_path);
2296
2297 // Derive and delete the app image.
2298 int64_t return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
2299
2300 // Derive and delete the vdex file.
2301 int64_t return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
2302
2303 // Report result
2304 if (return_value_oat == -1
2305 || return_value_art == -1
2306 || return_value_vdex == -1) {
2307 return -1;
2308 }
2309
2310 return return_value_oat + return_value_art + return_value_vdex;
2311 }
2312
is_absolute_path(const std::string & path)2313 static bool is_absolute_path(const std::string& path) {
2314 if (path.find('/') != 0 || path.find("..") != std::string::npos) {
2315 LOG(ERROR) << "Invalid absolute path " << path;
2316 return false;
2317 } else {
2318 return true;
2319 }
2320 }
2321
is_valid_instruction_set(const std::string & instruction_set)2322 static bool is_valid_instruction_set(const std::string& instruction_set) {
2323 // TODO: add explicit whitelisting of instruction sets
2324 if (instruction_set.find('/') != std::string::npos) {
2325 LOG(ERROR) << "Invalid instruction set " << instruction_set;
2326 return false;
2327 } else {
2328 return true;
2329 }
2330 }
2331
calculate_oat_file_path_default(char path[PKG_PATH_MAX],const char * oat_dir,const char * apk_path,const char * instruction_set)2332 bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
2333 const char *apk_path, const char *instruction_set) {
2334 std::string oat_dir_ = oat_dir;
2335 std::string apk_path_ = apk_path;
2336 std::string instruction_set_ = instruction_set;
2337
2338 if (!is_absolute_path(oat_dir_)) return false;
2339 if (!is_absolute_path(apk_path_)) return false;
2340 if (!is_valid_instruction_set(instruction_set_)) return false;
2341
2342 std::string::size_type end = apk_path_.rfind('.');
2343 std::string::size_type start = apk_path_.rfind('/', end);
2344 if (end == std::string::npos || start == std::string::npos) {
2345 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2346 return false;
2347 }
2348
2349 std::string res_ = oat_dir_ + '/' + instruction_set + '/'
2350 + apk_path_.substr(start + 1, end - start - 1) + ".odex";
2351 const char* res = res_.c_str();
2352 if (strlen(res) >= PKG_PATH_MAX) {
2353 LOG(ERROR) << "Result too large";
2354 return false;
2355 } else {
2356 strlcpy(path, res, PKG_PATH_MAX);
2357 return true;
2358 }
2359 }
2360
calculate_odex_file_path_default(char path[PKG_PATH_MAX],const char * apk_path,const char * instruction_set)2361 bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
2362 const char *instruction_set) {
2363 std::string apk_path_ = apk_path;
2364 std::string instruction_set_ = instruction_set;
2365
2366 if (!is_absolute_path(apk_path_)) return false;
2367 if (!is_valid_instruction_set(instruction_set_)) return false;
2368
2369 std::string::size_type end = apk_path_.rfind('.');
2370 std::string::size_type start = apk_path_.rfind('/', end);
2371 if (end == std::string::npos || start == std::string::npos) {
2372 LOG(ERROR) << "Invalid apk_path " << apk_path_;
2373 return false;
2374 }
2375
2376 std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
2377 return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
2378 }
2379
create_cache_path_default(char path[PKG_PATH_MAX],const char * src,const char * instruction_set)2380 bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
2381 const char *instruction_set) {
2382 std::string src_ = src;
2383 std::string instruction_set_ = instruction_set;
2384
2385 if (!is_absolute_path(src_)) return false;
2386 if (!is_valid_instruction_set(instruction_set_)) return false;
2387
2388 for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
2389 if (*it == '/') {
2390 *it = '@';
2391 }
2392 }
2393
2394 std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
2395 + DALVIK_CACHE_POSTFIX;
2396 const char* res = res_.c_str();
2397 if (strlen(res) >= PKG_PATH_MAX) {
2398 LOG(ERROR) << "Result too large";
2399 return false;
2400 } else {
2401 strlcpy(path, res, PKG_PATH_MAX);
2402 return true;
2403 }
2404 }
2405
open_classpath_files(const std::string & classpath,std::vector<unique_fd> * apk_fds,std::vector<std::string> * dex_locations)2406 bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
2407 std::vector<std::string>* dex_locations) {
2408 std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
2409 for (const std::string& elem : classpaths_elems) {
2410 unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
2411 if (fd < 0) {
2412 PLOG(ERROR) << "Could not open classpath elem " << elem;
2413 return false;
2414 } else {
2415 apk_fds->push_back(std::move(fd));
2416 dex_locations->push_back(elem);
2417 }
2418 }
2419 return true;
2420 }
2421
create_app_profile_snapshot(int32_t app_id,const std::string & package_name,const std::string & profile_name,const std::string & classpath)2422 static bool create_app_profile_snapshot(int32_t app_id,
2423 const std::string& package_name,
2424 const std::string& profile_name,
2425 const std::string& classpath) {
2426 int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
2427
2428 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2429 if (snapshot_fd < 0) {
2430 return false;
2431 }
2432
2433 std::vector<unique_fd> profiles_fd;
2434 unique_fd reference_profile_fd;
2435 open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
2436 &profiles_fd, &reference_profile_fd);
2437 if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
2438 return false;
2439 }
2440
2441 profiles_fd.push_back(std::move(reference_profile_fd));
2442
2443 // Open the class paths elements. These will be used to filter out profile data that does
2444 // not belong to the classpath during merge.
2445 std::vector<unique_fd> apk_fds;
2446 std::vector<std::string> dex_locations;
2447 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
2448 return false;
2449 }
2450
2451 RunProfman args;
2452 // This is specifically a snapshot for an app, so don't use boot image profiles.
2453 args.SetupMerge(profiles_fd,
2454 snapshot_fd,
2455 apk_fds,
2456 dex_locations,
2457 /* for_snapshot= */ true,
2458 /* for_boot_image= */ false);
2459 pid_t pid = fork();
2460 if (pid == 0) {
2461 /* child -- drop privileges before continuing */
2462 drop_capabilities(app_shared_gid);
2463 args.Exec();
2464 }
2465
2466 /* parent */
2467 int return_code = wait_child(pid);
2468 if (!WIFEXITED(return_code)) {
2469 LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2470 return false;
2471 }
2472
2473 // Verify that profman finished successfully.
2474 int profman_code = WEXITSTATUS(return_code);
2475 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2476 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2477 << ":" << profman_code;
2478 return false;
2479 }
2480 return true;
2481 }
2482
create_boot_image_profile_snapshot(const std::string & package_name,const std::string & profile_name,const std::string & classpath)2483 static bool create_boot_image_profile_snapshot(const std::string& package_name,
2484 const std::string& profile_name,
2485 const std::string& classpath) {
2486 // The reference profile directory for the android package might not be prepared. Do it now.
2487 const std::string ref_profile_dir =
2488 create_primary_reference_profile_package_dir_path(package_name);
2489 if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
2490 PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
2491 return false;
2492 }
2493
2494 // Return false for empty class path since it may otherwise return true below if profiles is
2495 // empty.
2496 if (classpath.empty()) {
2497 PLOG(ERROR) << "Class path is empty";
2498 return false;
2499 }
2500
2501 // Open and create the snapshot profile.
2502 unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
2503
2504 // Collect all non empty profiles.
2505 // The collection will traverse all applications profiles and find the non empty files.
2506 // This has the potential of inspecting a large number of files and directories (depending
2507 // on the number of applications and users). So there is a slight increase in the chance
2508 // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
2509 // fail the snapshot and aggregate whatever profile we could open.
2510 //
2511 // The profile snapshot is a best effort based on available data it's ok if some data
2512 // from some apps is missing. It will be counter productive for the snapshot to fail
2513 // because we could not open or read some of the files.
2514 std::vector<std::string> profiles;
2515 if (!collect_profiles(&profiles)) {
2516 LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
2517 }
2518
2519 // If we have no profiles return early.
2520 if (profiles.empty()) {
2521 return true;
2522 }
2523
2524 // Open the classpath elements. These will be used to filter out profile data that does
2525 // not belong to the classpath during merge.
2526 std::vector<unique_fd> apk_fds;
2527 std::vector<std::string> dex_locations;
2528 if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
2529 return false;
2530 }
2531
2532 // If we could not open any files from the classpath return an error.
2533 if (apk_fds.empty()) {
2534 LOG(ERROR) << "Could not open any of the classpath elements.";
2535 return false;
2536 }
2537
2538 // Aggregate the profiles in batches of kAggregationBatchSize.
2539 // We do this to avoid opening a huge a amount of files.
2540 static constexpr size_t kAggregationBatchSize = 10;
2541
2542 for (size_t i = 0; i < profiles.size(); ) {
2543 std::vector<unique_fd> profiles_fd;
2544 for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
2545 unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY, /*mode=*/ 0);
2546 if (fd.get() >= 0) {
2547 profiles_fd.push_back(std::move(fd));
2548 }
2549 }
2550
2551 // We aggregate (read & write) into the same fd multiple times in a row.
2552 // We need to reset the cursor every time to ensure we read the whole file every time.
2553 if (TEMP_FAILURE_RETRY(lseek(snapshot_fd, 0, SEEK_SET)) == static_cast<off_t>(-1)) {
2554 PLOG(ERROR) << "Cannot reset position for snapshot profile";
2555 return false;
2556 }
2557
2558 RunProfman args;
2559 args.SetupMerge(profiles_fd,
2560 snapshot_fd,
2561 apk_fds,
2562 dex_locations,
2563 /*for_snapshot=*/true,
2564 /*for_boot_image=*/true);
2565 pid_t pid = fork();
2566 if (pid == 0) {
2567 /* child -- drop privileges before continuing */
2568 drop_capabilities(AID_SYSTEM);
2569
2570 // The introduction of new access flags into boot jars causes them to
2571 // fail dex file verification.
2572 args.Exec();
2573 }
2574
2575 /* parent */
2576 int return_code = wait_child(pid);
2577
2578 if (!WIFEXITED(return_code)) {
2579 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2580 return false;
2581 }
2582
2583 // Verify that profman finished successfully.
2584 int profman_code = WEXITSTATUS(return_code);
2585 if (profman_code != PROFMAN_BIN_RETURN_CODE_SUCCESS) {
2586 LOG(WARNING) << "profman error for " << package_name << ":" << profile_name
2587 << ":" << profman_code;
2588 return false;
2589 }
2590 }
2591
2592 return true;
2593 }
2594
create_profile_snapshot(int32_t app_id,const std::string & package_name,const std::string & profile_name,const std::string & classpath)2595 bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
2596 const std::string& profile_name, const std::string& classpath) {
2597 if (app_id == -1) {
2598 return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
2599 } else {
2600 return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
2601 }
2602 }
2603
prepare_app_profile(const std::string & package_name,userid_t user_id,appid_t app_id,const std::string & profile_name,const std::string & code_path,const std::optional<std::string> & dex_metadata)2604 bool prepare_app_profile(const std::string& package_name,
2605 userid_t user_id,
2606 appid_t app_id,
2607 const std::string& profile_name,
2608 const std::string& code_path,
2609 const std::optional<std::string>& dex_metadata) {
2610 // Prepare the current profile.
2611 std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
2612 /*is_secondary_dex*/ false);
2613 uid_t uid = multiuser_get_uid(user_id, app_id);
2614 if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
2615 PLOG(ERROR) << "Failed to prepare " << cur_profile;
2616 return false;
2617 }
2618
2619 // Check if we need to install the profile from the dex metadata.
2620 if (!dex_metadata) {
2621 return true;
2622 }
2623
2624 // We have a dex metdata. Merge the profile into the reference profile.
2625 unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
2626 /*read_write*/ true, /*is_secondary_dex*/ false);
2627 unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
2628 open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
2629 unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
2630 if (apk_fd < 0) {
2631 PLOG(ERROR) << "Could not open code path " << code_path;
2632 return false;
2633 }
2634
2635 RunProfman args;
2636 args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
2637 std::move(ref_profile_fd),
2638 std::move(apk_fd),
2639 code_path);
2640 pid_t pid = fork();
2641 if (pid == 0) {
2642 /* child -- drop privileges before continuing */
2643 gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
2644 drop_capabilities(app_shared_gid);
2645
2646 // The copy and update takes ownership over the fds.
2647 args.Exec();
2648 }
2649
2650 /* parent */
2651 int return_code = wait_child(pid);
2652 if (!WIFEXITED(return_code)) {
2653 PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
2654 return false;
2655 }
2656 return true;
2657 }
2658
2659 } // namespace installd
2660 } // namespace android
2661