blob: c86adef11887a01a0b0c524601d5bb56197ef976 [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>
Martin Stjernholm47a9d992023-07-28 21:43:36 +010022#include <unistd.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080023
Martin Stjernholm47a9d992023-07-28 21:43:36 +010024#include <algorithm>
Alex Light53e94382021-03-09 16:39:55 -080025#include <array>
Alex Lightcf7e6de2021-03-04 10:20:18 -080026#include <fstream>
Martin Stjernholm47a9d992023-07-28 21:43:36 +010027#include <iostream>
Andreas Gamped089ca12016-06-27 14:25:30 -070028#include <sstream>
29
Alex Lightcf7e6de2021-03-04 10:20:18 -080030#include <android-base/file.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080031#include <android-base/logging.h>
32#include <android-base/macros.h>
Nikita Ioffe2a42aee2021-04-07 16:25:49 +010033#include <android-base/scopeguard.h>
Andreas Gampe01ad5982016-03-09 16:27:29 -080034#include <android-base/stringprintf.h>
Martin Stjernholm47a9d992023-07-28 21:43:36 +010035#include <android-base/strings.h>
Alex Lightcf7e6de2021-03-04 10:20:18 -080036#include <android-base/unique_fd.h>
Andreas Gampee90127d2019-03-22 11:21:34 -070037#include <libdm/dm.h>
Roland Levillainc19c6042018-12-18 12:15:12 +000038#include <selinux/android.h>
39
Jeff Sharkey0274c972016-12-06 09:32:04 -070040#include "installd_constants.h"
41#include "otapreopt_utils.h"
Andreas Gampe548bdb92016-06-02 17:56:45 -070042
Andreas Gampe01ad5982016-03-09 16:27:29 -080043#ifndef LOG_TAG
Martin Stjernholm47a9d992023-07-28 21:43:36 +010044#define LOG_TAG "otapreopt_chroot"
Andreas Gampe01ad5982016-03-09 16:27:29 -080045#endif
46
47using android::base::StringPrintf;
48
49namespace android {
50namespace installd {
51
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +000052// We don't know the filesystem types of the partitions in the update package,
53// so just try the possibilities one by one.
54static constexpr std::array kTryMountFsTypes = {"ext4", "erofs"};
55
Nikita Ioffe32e49e22021-07-06 17:05:16 +000056static void CloseDescriptor(const char* descriptor_string) {
57 int fd = -1;
58 std::istringstream stream(descriptor_string);
59 stream >> fd;
60 if (!stream.fail()) {
Martin Stjernholm47a9d992023-07-28 21:43:36 +010061 if (fd >= 0) {
62 if (close(fd) < 0) {
63 PLOG(ERROR) << "Failed to close " << fd;
64 }
65 }
66 }
67}
68
69static void SetCloseOnExec(int fd) {
70 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
71 PLOG(ERROR) << "Failed to set FD_CLOEXEC on " << fd;
Nikita Ioffe32e49e22021-07-06 17:05:16 +000072 }
73}
74
Alex Light53e94382021-03-09 16:39:55 -080075static void ActivateApexPackages() {
76 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
77 std::string apexd_error_msg;
Roland Levillain6520cca2019-02-01 13:15:58 +000078
Alex Light53e94382021-03-09 16:39:55 -080079 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
80 if (!exec_result) {
81 PLOG(ERROR) << "Running otapreopt failed: " << apexd_error_msg;
82 exit(220);
Roland Levillain6520cca2019-02-01 13:15:58 +000083 }
84}
85
Nikita Ioffe2a42aee2021-04-07 16:25:49 +010086static void DeactivateApexPackages() {
87 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
88 std::string apexd_error_msg;
89 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
90 if (!exec_result) {
91 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
92 }
93}
94
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +000095static bool TryMountWithFstypes(const char* block_device, const char* target) {
96 for (int i = 0; i < kTryMountFsTypes.size(); ++i) {
97 const char* fstype = kTryMountFsTypes[i];
98 int mount_result = mount(block_device, target, fstype, MS_RDONLY, /* data */ nullptr);
99 if (mount_result == 0) {
100 return true;
101 }
102 if (errno == EINVAL && i < kTryMountFsTypes.size() - 1) {
103 // Only try the next fstype if mounting failed due to the current one
104 // being invalid.
105 LOG(WARNING) << "Failed to mount " << block_device << " on " << target << " with "
106 << fstype << " - trying " << kTryMountFsTypes[i + 1];
107 } else {
108 PLOG(ERROR) << "Failed to mount " << block_device << " on " << target << " with "
109 << fstype;
110 return false;
111 }
112 }
113 __builtin_unreachable();
114}
115
Andreas Gampe54b62c92019-03-21 11:34:19 -0700116static void TryExtraMount(const char* name, const char* slot, const char* target) {
Andreas Gampee90127d2019-03-22 11:21:34 -0700117 std::string partition_name = StringPrintf("%s%s", name, slot);
118
119 // See whether update_engine mounted a logical partition.
120 {
121 auto& dm = dm::DeviceMapper::Instance();
122 if (dm.GetState(partition_name) != dm::DmDeviceState::INVALID) {
123 std::string path;
124 if (dm.GetDmDevicePathByName(partition_name, &path)) {
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +0000125 if (TryMountWithFstypes(path.c_str(), target)) {
Andreas Gampee90127d2019-03-22 11:21:34 -0700126 return;
127 }
128 }
129 }
130 }
131
132 // Fall back and attempt a direct mount.
133 std::string block_device = StringPrintf("/dev/block/by-name/%s", partition_name.c_str());
Martin Stjernholmf21cb6e2023-02-28 19:10:11 +0000134 (void)TryMountWithFstypes(block_device.c_str(), target);
Andreas Gampe54b62c92019-03-21 11:34:19 -0700135}
136
Andreas Gamped089ca12016-06-27 14:25:30 -0700137// Entry for otapreopt_chroot. Expected parameters are:
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100138//
139// [cmd] [status-fd] [target-slot-suffix]
140//
141// The file descriptor denoted by status-fd will be closed. Dexopt commands on
142// the form
143//
144// "dexopt" [dexopt-params]
145//
146// are then read from stdin until EOF and passed on to /system/bin/otapreopt one
147// by one. After each call a line with the current command count is written to
148// stdout and flushed.
Andreas Gampe01ad5982016-03-09 16:27:29 -0800149static int otapreopt_chroot(const int argc, char **arg) {
Zach Riggle318853a2018-01-18 18:34:04 -0600150 // Validate arguments
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100151 if (argc == 2 && std::string_view(arg[1]) == "--version") {
152 // Accept a single --version flag, to allow the script to tell this binary
153 // from the earlier one.
154 std::cout << "2" << std::endl;
155 return 0;
156 }
157 if (argc != 3) {
158 LOG(ERROR) << "Wrong number of arguments: " << argc;
Zach Riggle318853a2018-01-18 18:34:04 -0600159 exit(208);
160 }
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100161 const char* status_fd = arg[1];
162 const char* slot_suffix = arg[2];
163
164 // Set O_CLOEXEC on standard fds. They are coming from the caller, we do not
165 // want to pass them on across our fork/exec into a different domain.
166 SetCloseOnExec(STDIN_FILENO);
167 SetCloseOnExec(STDOUT_FILENO);
168 SetCloseOnExec(STDERR_FILENO);
169 // Close the status channel.
170 CloseDescriptor(status_fd);
Andreas Gamped089ca12016-06-27 14:25:30 -0700171
Andreas Gampe01ad5982016-03-09 16:27:29 -0800172 // We need to run the otapreopt tool from the postinstall partition. As such, set up a
173 // mount namespace and change root.
174
175 // Create our own mount namespace.
176 if (unshare(CLONE_NEWNS) != 0) {
177 PLOG(ERROR) << "Failed to unshare() for otapreopt.";
178 exit(200);
179 }
180
181 // Make postinstall private, so that our changes don't propagate.
182 if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) {
183 PLOG(ERROR) << "Failed to mount private.";
184 exit(201);
185 }
186
187 // Bind mount necessary directories.
188 constexpr const char* kBindMounts[] = {
Nikita Ioffe56fd71b2023-06-15 17:01:11 +0100189 "/data", "/dev", "/proc", "/sys",
190 "/sys/fs/selinux" /* Required for apexd which includes libselinux */
Andreas Gampe01ad5982016-03-09 16:27:29 -0800191 };
192 for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
193 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
194 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
195 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
196 exit(202);
197 }
198 }
199
Andreas Gampefd12eda2016-07-12 09:47:17 -0700200 // Try to mount the vendor partition. update_engine doesn't do this for us, but we
201 // want it for vendor APKs.
202 // Notes:
203 // 1) We pretty much guess a name here and hope to find the partition by name.
204 // It is just as complicated and brittle to scan /proc/mounts. But this requires
205 // validating the target-slot so as not to try to mount some totally random path.
206 // 2) We're in a mount namespace here, so when we die, this will be cleaned up.
207 // 3) Ignore errors. Printing anything at this stage will open a file descriptor
208 // for logging.
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100209 if (!ValidateTargetSlotSuffix(slot_suffix)) {
210 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
Andreas Gampefd12eda2016-07-12 09:47:17 -0700211 exit(207);
212 }
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100213 TryExtraMount("vendor", slot_suffix, "/postinstall/vendor");
Andreas Gampeb87a1c72018-04-13 17:42:23 -0700214
215 // Try to mount the product partition. update_engine doesn't do this for us, but we
216 // want it for product APKs. Same notes as vendor above.
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100217 TryExtraMount("product", slot_suffix, "/postinstall/product");
Andreas Gampefd12eda2016-07-12 09:47:17 -0700218
Alex Light1a4c1da2021-04-15 15:21:17 -0700219 // Try to mount the system_ext partition. update_engine doesn't do this for
220 // us, but we want it for system_ext APKs. Same notes as vendor and product
221 // above.
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100222 TryExtraMount("system_ext", slot_suffix, "/postinstall/system_ext");
Alex Light1a4c1da2021-04-15 15:21:17 -0700223
Alex Light2b307a02021-03-03 18:35:47 -0800224 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
225 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
226 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
227 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
228 exit(215);
229 }
230
Roland Levillainc19c6042018-12-18 12:15:12 +0000231 // Setup APEX mount point and its security context.
232 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
233 // The following logic is similar to the one in system/core/rootdir/init.rc:
234 //
235 // mount tmpfs tmpfs /apex nodev noexec nosuid
236 // chmod 0755 /apex
237 // chown root root /apex
238 // restorecon /apex
239 //
Roland Levillain8d276812019-01-24 10:51:30 +0000240 // except we perform the `restorecon` step just after mounting the tmpfs
241 // filesystem in /postinstall/apex, so that this directory is correctly
242 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
243 // following operations (`chmod`, `chown`, etc.) following policies
244 // restricted to `postinstall_apex_mnt_dir`:
245 //
246 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
247 // restorecon /postinstall/apex
248 // chmod 0755 /postinstall/apex
249 // chown root root /postinstall/apex
250 //
Roland Levillainc19c6042018-12-18 12:15:12 +0000251 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
252 != 0) {
253 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
254 exit(209);
255 }
Roland Levillain8d276812019-01-24 10:51:30 +0000256 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
257 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
258 exit(214);
259 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000260 if (chmod(kPostinstallApexDir, 0755) != 0) {
261 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
262 exit(210);
263 }
264 if (chown(kPostinstallApexDir, 0, 0) != 0) {
265 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
266 exit(211);
267 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000268
Andreas Gampe01ad5982016-03-09 16:27:29 -0800269 // Chdir into /postinstall.
270 if (chdir("/postinstall") != 0) {
271 PLOG(ERROR) << "Unable to chdir into /postinstall.";
272 exit(203);
273 }
274
275 // Make /postinstall the root in our mount namespace.
276 if (chroot(".") != 0) {
277 PLOG(ERROR) << "Failed to chroot";
278 exit(204);
279 }
280
281 if (chdir("/") != 0) {
282 PLOG(ERROR) << "Unable to chdir into /.";
283 exit(205);
284 }
285
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100286 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
287 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
288 // wrong we need to register our own atexit handler.
289 // We want to register this handler before actually activating apex packages. This is mostly
290 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
291 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
292 // to do that. :)
293 if (atexit(DeactivateApexPackages) != 0) {
294 LOG(ERROR) << "Failed to register atexit hander";
295 exit(206);
296 }
297
Roland Levillainc19c6042018-12-18 12:15:12 +0000298 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100299 // the ART APEX, as it is required by otapreopt to run dex2oat.
Alex Light53e94382021-03-09 16:39:55 -0800300 ActivateApexPackages();
Roland Levillainc19c6042018-12-18 12:15:12 +0000301
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100302 auto cleanup = android::base::make_scope_guard([](){
303 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
304 std::string apexd_error_msg;
305 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
306 if (!exec_result) {
307 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
308 }
309 });
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100310 // Check that an ART APEX has been activated; clean up and exit
Roland Levillain8a8ca152019-07-11 18:48:05 +0100311 // early otherwise.
Alex Light2b307a02021-03-03 18:35:47 -0800312 static constexpr const std::string_view kRequiredApexs[] = {
313 "com.android.art",
314 "com.android.runtime",
Alex Lightfbdc7262021-04-26 16:48:18 -0700315 "com.android.sdkext", // For derive_classpath
Alex Light2b307a02021-03-03 18:35:47 -0800316 };
Alex Light53e94382021-03-09 16:39:55 -0800317 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
318 DIR* apex_dir = opendir("/apex");
319 if (apex_dir == nullptr) {
320 PLOG(ERROR) << "unable to open /apex";
321 exit(220);
322 }
323 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
324 for (int i = 0; i < found_apexs.size(); i++) {
325 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
326 found_apexs[i] = true;
327 break;
328 }
Alex Light2b307a02021-03-03 18:35:47 -0800329 }
330 }
Alex Light53e94382021-03-09 16:39:55 -0800331 closedir(apex_dir);
332 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
333 if (it != found_apexs.cend()) {
334 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
335 << " package!";
336 exit(221);
337 }
Alex Light2b307a02021-03-03 18:35:47 -0800338
339 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
340 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
341 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
342 exit(219);
343 }
344 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
345 "--target", "/linkerconfig"};
346 std::string linkerconfig_error_msg;
347 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
348 if (!linkerconfig_exec_result) {
349 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
350 exit(218);
Roland Levillain8a8ca152019-07-11 18:48:05 +0100351 }
352
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100353 // Now go on and read dexopt lines from stdin and pass them on to otapreopt.
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000354
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100355 int count = 1;
Jiakai Zhanga7563092023-11-01 20:12:27 +0000356 for (std::array<char, 10000> linebuf;
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100357 std::cin.clear(), std::cin.getline(&linebuf[0], linebuf.size()); ++count) {
358 // Subtract one from gcount() since getline() counts the newline.
359 std::string line(&linebuf[0], std::cin.gcount() - 1);
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000360
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100361 if (std::cin.fail()) {
362 LOG(ERROR) << "Command exceeds max length " << linebuf.size() << " - skipped: " << line;
363 continue;
364 }
365
366 std::vector<std::string> tokenized_line = android::base::Tokenize(line, " ");
367 std::vector<std::string> cmd{"/system/bin/otapreopt", slot_suffix};
368 std::move(tokenized_line.begin(), tokenized_line.end(), std::back_inserter(cmd));
369
370 LOG(INFO) << "Command " << count << ": " << android::base::Join(cmd, " ");
371
372 // Fork and execute otapreopt in its own process.
373 std::string error_msg;
374 bool exec_result = Exec(cmd, &error_msg);
375 if (!exec_result) {
376 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
377 }
378
379 // Print the count to stdout and flush to indicate progress.
380 std::cout << count << std::endl;
Nikita Ioffe97f013c2021-06-29 03:42:56 +0100381 }
382
Martin Stjernholm47a9d992023-07-28 21:43:36 +0100383 LOG(INFO) << "No more dexopt commands";
Roland Levillain94b41802019-01-18 11:56:50 +0000384 return 0;
Andreas Gampe01ad5982016-03-09 16:27:29 -0800385}
386
387} // namespace installd
388} // namespace android
389
390int main(const int argc, char *argv[]) {
391 return android::installd::otapreopt_chroot(argc, argv);
392}