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