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