blob: c86993cb06711b8ba8b858ca4abb529fd142ff9f [file] [log] [blame]
Andreas Gampe01ad5982016-03-09 16:27:29 -08001/*
2 ** Copyright 2016, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
Andreas Gamped089ca12016-06-27 14:25:30 -070017#include <fcntl.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080018#include <linux/unistd.h>
19#include <sys/mount.h>
Roland Levillainc19c6042018-12-18 12:15:12 +000020#include <sys/stat.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080021#include <sys/wait.h>
22
Alex Light53e94382021-03-09 16:39:55 -080023#include <array>
Alex Lightcf7e6de2021-03-04 10:20:18 -080024#include <fstream>
Andreas Gamped089ca12016-06-27 14:25:30 -070025#include <sstream>
26
Alex Lightcf7e6de2021-03-04 10:20:18 -080027#include <android-base/file.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080028#include <android-base/logging.h>
29#include <android-base/macros.h>
Nikita Ioffe2a42aee2021-04-07 16:25:49 +010030#include <android-base/scopeguard.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080031#include <android-base/stringprintf.h>
Alex Lightcf7e6de2021-03-04 10:20:18 -080032#include <android-base/unique_fd.h>
Andreas Gampee90127d2019-03-22 11:21:34 -070033#include <libdm/dm.h>
Roland Levillainc19c6042018-12-18 12:15:12 +000034#include <selinux/android.h>
35
Jeff Sharkey0274c972016-12-06 09:32:04 -070036#include "installd_constants.h"
37#include "otapreopt_utils.h"
Andreas Gampe548bdb92016-06-02 17:56:45 -070038
Andreas Gampe01ad5982016-03-09 16:27:29 -080039#ifndef LOG_TAG
40#define LOG_TAG "otapreopt"
41#endif
42
43using android::base::StringPrintf;
44
45namespace android {
46namespace installd {
47
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +000048// We don't know the filesystem types of the partitions in the update package,
49// so just try the possibilities one by one.
50static constexpr std::array kTryMountFsTypes = {"ext4", "erofs"};
51
Andreas Gamped089ca12016-06-27 14:25:30 -070052static void CloseDescriptor(int fd) {
53 if (fd >= 0) {
54 int result = close(fd);
55 UNUSED(result); // Ignore result. Printing to logcat will open a new descriptor
56 // that we do *not* want.
57 }
58}
59
Nikita Ioffe32e49e22021-07-06 17:05:16 +000060static void CloseDescriptor(const char* descriptor_string) {
61 int fd = -1;
62 std::istringstream stream(descriptor_string);
63 stream >> fd;
64 if (!stream.fail()) {
65 CloseDescriptor(fd);
66 }
67}
68
Alex Light53e94382021-03-09 16:39:55 -080069static void ActivateApexPackages() {
70 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
71 std::string apexd_error_msg;
Roland Levillain6520cca2019-02-01 13:15:58 +000072
Alex Light53e94382021-03-09 16:39:55 -080073 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
74 if (!exec_result) {
75 PLOG(ERROR) << "Running otapreopt failed: " << apexd_error_msg;
76 exit(220);
Roland Levillain6520cca2019-02-01 13:15:58 +000077 }
78}
79
Nikita Ioffe2a42aee2021-04-07 16:25:49 +010080static void DeactivateApexPackages() {
81 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
82 std::string apexd_error_msg;
83 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
84 if (!exec_result) {
85 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
86 }
87}
88
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +000089static bool TryMountWithFstypes(const char* block_device, const char* target) {
90 for (int i = 0; i < kTryMountFsTypes.size(); ++i) {
91 const char* fstype = kTryMountFsTypes[i];
92 int mount_result = mount(block_device, target, fstype, MS_RDONLY, /* data */ nullptr);
93 if (mount_result == 0) {
94 return true;
95 }
96 if (errno == EINVAL && i < kTryMountFsTypes.size() - 1) {
97 // Only try the next fstype if mounting failed due to the current one
98 // being invalid.
99 LOG(WARNING) << "Failed to mount " << block_device << " on " << target << " with "
100 << fstype << " - trying " << kTryMountFsTypes[i + 1];
101 } else {
102 PLOG(ERROR) << "Failed to mount " << block_device << " on " << target << " with "
103 << fstype;
104 return false;
105 }
106 }
107 __builtin_unreachable();
108}
109
Andreas Gampe54b62c92019-03-21 11:34:19 -0700110static void TryExtraMount(const char* name, const char* slot, const char* target) {
Andreas Gampee90127d2019-03-22 11:21:34 -0700111 std::string partition_name = StringPrintf("%s%s", name, slot);
112
113 // See whether update_engine mounted a logical partition.
114 {
115 auto& dm = dm::DeviceMapper::Instance();
116 if (dm.GetState(partition_name) != dm::DmDeviceState::INVALID) {
117 std::string path;
118 if (dm.GetDmDevicePathByName(partition_name, &path)) {
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +0000119 if (TryMountWithFstypes(path.c_str(), target)) {
Andreas Gampee90127d2019-03-22 11:21:34 -0700120 return;
121 }
122 }
123 }
124 }
125
126 // Fall back and attempt a direct mount.
127 std::string block_device = StringPrintf("/dev/block/by-name/%s", partition_name.c_str());
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +0000128 (void)TryMountWithFstypes(block_device.c_str(), target);
Andreas Gampe54b62c92019-03-21 11:34:19 -0700129}
130
Andreas Gamped089ca12016-06-27 14:25:30 -0700131// Entry for otapreopt_chroot. Expected parameters are:
132// [cmd] [status-fd] [target-slot] "dexopt" [dexopt-params]
133// The file descriptor denoted by status-fd will be closed. The rest of the parameters will
134// be passed on to otapreopt in the chroot.
Andreas Gampe01ad5982016-03-09 16:27:29 -0800135static int otapreopt_chroot(const int argc, char **arg) {
Zach Riggle318853a2018-01-18 18:34:04 -0600136 // Validate arguments
137 // We need the command, status channel and target slot, at a minimum.
138 if(argc < 3) {
139 PLOG(ERROR) << "Not enough arguments.";
140 exit(208);
141 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700142 // Close all file descriptors. They are coming from the caller, we do not want to pass them
143 // on across our fork/exec into a different domain.
144 // 1) Default descriptors.
145 CloseDescriptor(STDIN_FILENO);
146 CloseDescriptor(STDOUT_FILENO);
147 CloseDescriptor(STDERR_FILENO);
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000148 // 2) The status channel.
149 CloseDescriptor(arg[1]);
Andreas Gamped089ca12016-06-27 14:25:30 -0700150
Andreas Gampe01ad5982016-03-09 16:27:29 -0800151 // We need to run the otapreopt tool from the postinstall partition. As such, set up a
152 // mount namespace and change root.
153
154 // Create our own mount namespace.
155 if (unshare(CLONE_NEWNS) != 0) {
156 PLOG(ERROR) << "Failed to unshare() for otapreopt.";
157 exit(200);
158 }
159
160 // Make postinstall private, so that our changes don't propagate.
161 if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) {
162 PLOG(ERROR) << "Failed to mount private.";
163 exit(201);
164 }
165
166 // Bind mount necessary directories.
167 constexpr const char* kBindMounts[] = {
Nikita Ioffe56fd71b2023-06-15 17:01:11 +0100168 "/data", "/dev", "/proc", "/sys",
169 "/sys/fs/selinux" /* Required for apexd which includes libselinux */
Andreas Gampe01ad5982016-03-09 16:27:29 -0800170 };
171 for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
172 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
173 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
174 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
175 exit(202);
176 }
177 }
178
Andreas Gampefd12eda2016-07-12 09:47:17 -0700179 // Try to mount the vendor partition. update_engine doesn't do this for us, but we
180 // want it for vendor APKs.
181 // Notes:
182 // 1) We pretty much guess a name here and hope to find the partition by name.
183 // It is just as complicated and brittle to scan /proc/mounts. But this requires
184 // validating the target-slot so as not to try to mount some totally random path.
185 // 2) We're in a mount namespace here, so when we die, this will be cleaned up.
186 // 3) Ignore errors. Printing anything at this stage will open a file descriptor
187 // for logging.
188 if (!ValidateTargetSlotSuffix(arg[2])) {
189 LOG(ERROR) << "Target slot suffix not legal: " << arg[2];
190 exit(207);
191 }
Andreas Gampe54b62c92019-03-21 11:34:19 -0700192 TryExtraMount("vendor", arg[2], "/postinstall/vendor");
Andreas Gampeb87a1c72018-04-13 17:42:23 -0700193
194 // Try to mount the product partition. update_engine doesn't do this for us, but we
195 // want it for product APKs. Same notes as vendor above.
Andreas Gampe54b62c92019-03-21 11:34:19 -0700196 TryExtraMount("product", arg[2], "/postinstall/product");
Andreas Gampefd12eda2016-07-12 09:47:17 -0700197
Alex Light1a4c1da2021-04-15 15:21:17 -0700198 // Try to mount the system_ext partition. update_engine doesn't do this for
199 // us, but we want it for system_ext APKs. Same notes as vendor and product
200 // above.
201 TryExtraMount("system_ext", arg[2], "/postinstall/system_ext");
202
Alex Light2b307a02021-03-03 18:35:47 -0800203 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
204 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
205 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
206 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
207 exit(215);
208 }
209
Roland Levillainc19c6042018-12-18 12:15:12 +0000210 // Setup APEX mount point and its security context.
211 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
212 // The following logic is similar to the one in system/core/rootdir/init.rc:
213 //
214 // mount tmpfs tmpfs /apex nodev noexec nosuid
215 // chmod 0755 /apex
216 // chown root root /apex
217 // restorecon /apex
218 //
Roland Levillain8d276812019-01-24 10:51:30 +0000219 // except we perform the `restorecon` step just after mounting the tmpfs
220 // filesystem in /postinstall/apex, so that this directory is correctly
221 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
222 // following operations (`chmod`, `chown`, etc.) following policies
223 // restricted to `postinstall_apex_mnt_dir`:
224 //
225 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
226 // restorecon /postinstall/apex
227 // chmod 0755 /postinstall/apex
228 // chown root root /postinstall/apex
229 //
Roland Levillainc19c6042018-12-18 12:15:12 +0000230 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
231 != 0) {
232 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
233 exit(209);
234 }
Roland Levillain8d276812019-01-24 10:51:30 +0000235 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
236 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
237 exit(214);
238 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000239 if (chmod(kPostinstallApexDir, 0755) != 0) {
240 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
241 exit(210);
242 }
243 if (chown(kPostinstallApexDir, 0, 0) != 0) {
244 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
245 exit(211);
246 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000247
Andreas Gampe01ad5982016-03-09 16:27:29 -0800248 // Chdir into /postinstall.
249 if (chdir("/postinstall") != 0) {
250 PLOG(ERROR) << "Unable to chdir into /postinstall.";
251 exit(203);
252 }
253
254 // Make /postinstall the root in our mount namespace.
255 if (chroot(".") != 0) {
256 PLOG(ERROR) << "Failed to chroot";
257 exit(204);
258 }
259
260 if (chdir("/") != 0) {
261 PLOG(ERROR) << "Unable to chdir into /.";
262 exit(205);
263 }
264
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100265 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
266 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
267 // wrong we need to register our own atexit handler.
268 // We want to register this handler before actually activating apex packages. This is mostly
269 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
270 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
271 // to do that. :)
272 if (atexit(DeactivateApexPackages) != 0) {
273 LOG(ERROR) << "Failed to register atexit hander";
274 exit(206);
275 }
276
Roland Levillainc19c6042018-12-18 12:15:12 +0000277 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100278 // the ART APEX, as it is required by otapreopt to run dex2oat.
Alex Light53e94382021-03-09 16:39:55 -0800279 ActivateApexPackages();
Roland Levillainc19c6042018-12-18 12:15:12 +0000280
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100281 auto cleanup = android::base::make_scope_guard([](){
282 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
283 std::string apexd_error_msg;
284 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
285 if (!exec_result) {
286 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
287 }
288 });
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100289 // Check that an ART APEX has been activated; clean up and exit
Roland Levillain8a8ca152019-07-11 18:48:05 +0100290 // early otherwise.
Alex Light2b307a02021-03-03 18:35:47 -0800291 static constexpr const std::string_view kRequiredApexs[] = {
292 "com.android.art",
293 "com.android.runtime",
Alex Lightfbdc7262021-04-26 16:48:18 -0700294 "com.android.sdkext", // For derive_classpath
Alex Light2b307a02021-03-03 18:35:47 -0800295 };
Alex Light53e94382021-03-09 16:39:55 -0800296 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
297 DIR* apex_dir = opendir("/apex");
298 if (apex_dir == nullptr) {
299 PLOG(ERROR) << "unable to open /apex";
300 exit(220);
301 }
302 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
303 for (int i = 0; i < found_apexs.size(); i++) {
304 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
305 found_apexs[i] = true;
306 break;
307 }
Alex Light2b307a02021-03-03 18:35:47 -0800308 }
309 }
Alex Light53e94382021-03-09 16:39:55 -0800310 closedir(apex_dir);
311 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
312 if (it != found_apexs.cend()) {
313 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
314 << " package!";
315 exit(221);
316 }
Alex Light2b307a02021-03-03 18:35:47 -0800317
318 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
319 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
320 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
321 exit(219);
322 }
323 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
324 "--target", "/linkerconfig"};
325 std::string linkerconfig_error_msg;
326 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
327 if (!linkerconfig_exec_result) {
328 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
329 exit(218);
Roland Levillain8a8ca152019-07-11 18:48:05 +0100330 }
331
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000332 // Now go on and run otapreopt.
333
334 // Incoming: cmd + status-fd + target-slot + cmd... | Incoming | = argc
335 // Outgoing: cmd + target-slot + cmd... | Outgoing | = argc - 1
336 std::vector<std::string> cmd;
337 cmd.reserve(argc);
338 cmd.push_back("/system/bin/otapreopt");
339
340 // The first parameter is the status file descriptor, skip.
341 for (size_t i = 2; i < static_cast<size_t>(argc); ++i) {
342 cmd.push_back(arg[i]);
Nikita Ioffe97f013c2021-06-29 03:42:56 +0100343 }
344
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000345 // Fork and execute otapreopt in its own process.
346 std::string error_msg;
347 bool exec_result = Exec(cmd, &error_msg);
348 if (!exec_result) {
349 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
350 }
Andreas Gampe01ad5982016-03-09 16:27:29 -0800351
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000352 if (!exec_result) {
353 exit(213);
Roland Levillain94b41802019-01-18 11:56:50 +0000354 }
355
356 return 0;
Andreas Gampe01ad5982016-03-09 16:27:29 -0800357}
358
359} // namespace installd
360} // namespace android
361
362int main(const int argc, char *argv[]) {
363 return android::installd::otapreopt_chroot(argc, argv);
364}